context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>AccessibleBiddingStrategy</c> resource.</summary> public sealed partial class AccessibleBiddingStrategyName : gax::IResourceName, sys::IEquatable<AccessibleBiddingStrategyName> { /// <summary>The possible contents of <see cref="AccessibleBiddingStrategyName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> CustomerBiddingStrategy = 1, } private static gax::PathTemplate s_customerBiddingStrategy = new gax::PathTemplate("customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}"); /// <summary> /// Creates a <see cref="AccessibleBiddingStrategyName"/> 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="AccessibleBiddingStrategyName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AccessibleBiddingStrategyName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AccessibleBiddingStrategyName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AccessibleBiddingStrategyName"/> with the pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// A new instance of <see cref="AccessibleBiddingStrategyName"/> constructed from the provided ids. /// </returns> public static AccessibleBiddingStrategyName FromCustomerBiddingStrategy(string customerId, string biddingStrategyId) => new AccessibleBiddingStrategyName(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AccessibleBiddingStrategyName"/> with /// pattern <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AccessibleBiddingStrategyName"/> with pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </returns> public static string Format(string customerId, string biddingStrategyId) => FormatCustomerBiddingStrategy(customerId, biddingStrategyId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AccessibleBiddingStrategyName"/> with /// pattern <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AccessibleBiddingStrategyName"/> with pattern /// <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c>. /// </returns> public static string FormatCustomerBiddingStrategy(string customerId, string biddingStrategyId) => s_customerBiddingStrategy.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId))); /// <summary> /// Parses the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> 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}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <returns>The parsed <see cref="AccessibleBiddingStrategyName"/> if successful.</returns> public static AccessibleBiddingStrategyName Parse(string accessibleBiddingStrategyName) => Parse(accessibleBiddingStrategyName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> 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}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// 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="AccessibleBiddingStrategyName"/> if successful.</returns> public static AccessibleBiddingStrategyName Parse(string accessibleBiddingStrategyName, bool allowUnparsed) => TryParse(accessibleBiddingStrategyName, allowUnparsed, out AccessibleBiddingStrategyName 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="AccessibleBiddingStrategyName"/> /// 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}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// The resource name in string form. Must not be <c>null</c>. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="AccessibleBiddingStrategyName"/>, 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 accessibleBiddingStrategyName, out AccessibleBiddingStrategyName result) => TryParse(accessibleBiddingStrategyName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AccessibleBiddingStrategyName"/> /// 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}/accessibleBiddingStrategies/{bidding_strategy_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="accessibleBiddingStrategyName"> /// 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="AccessibleBiddingStrategyName"/>, 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 accessibleBiddingStrategyName, bool allowUnparsed, out AccessibleBiddingStrategyName result) { gax::GaxPreconditions.CheckNotNull(accessibleBiddingStrategyName, nameof(accessibleBiddingStrategyName)); gax::TemplatedResourceName resourceName; if (s_customerBiddingStrategy.TryParseName(accessibleBiddingStrategyName, out resourceName)) { result = FromCustomerBiddingStrategy(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(accessibleBiddingStrategyName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private AccessibleBiddingStrategyName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string biddingStrategyId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; BiddingStrategyId = biddingStrategyId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="AccessibleBiddingStrategyName"/> class from the component parts of /// pattern <c>customers/{customer_id}/accessibleBiddingStrategies/{bidding_strategy_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="biddingStrategyId">The <c>BiddingStrategy</c> ID. Must not be <c>null</c> or empty.</param> public AccessibleBiddingStrategyName(string customerId, string biddingStrategyId) : this(ResourceNameType.CustomerBiddingStrategy, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), biddingStrategyId: gax::GaxPreconditions.CheckNotNullOrEmpty(biddingStrategyId, nameof(biddingStrategyId))) { } /// <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>BiddingStrategy</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string BiddingStrategyId { 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>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.CustomerBiddingStrategy: return s_customerBiddingStrategy.Expand(CustomerId, BiddingStrategyId); 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 AccessibleBiddingStrategyName); /// <inheritdoc/> public bool Equals(AccessibleBiddingStrategyName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AccessibleBiddingStrategyName a, AccessibleBiddingStrategyName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AccessibleBiddingStrategyName a, AccessibleBiddingStrategyName b) => !(a == b); } public partial class AccessibleBiddingStrategy { /// <summary> /// <see cref="gagvr::AccessibleBiddingStrategyName"/>-typed view over the <see cref="ResourceName"/> resource /// name property. /// </summary> internal AccessibleBiddingStrategyName ResourceNameAsAccessibleBiddingStrategyName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::AccessibleBiddingStrategyName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary> /// <see cref="gagvr::AccessibleBiddingStrategyName"/>-typed view over the <see cref="Name"/> resource name /// property. /// </summary> internal AccessibleBiddingStrategyName AccessibleBiddingStrategyName { get => string.IsNullOrEmpty(Name) ? null : gagvr::AccessibleBiddingStrategyName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections; using System.Net.Http; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Text; using Newtonsoft.Json; using System.IO; using System.Threading; using HttpUtility = System.Web.HttpUtility; namespace Refit { class RequestBuilderFactory : IRequestBuilderFactory { public IRequestBuilder Create(Type interfaceType, RefitSettings settings = null) { return new RequestBuilderImplementation(interfaceType, settings); } } class RequestBuilderImplementation : IRequestBuilder { readonly Type targetType; readonly Dictionary<string, RestMethodInfo> interfaceHttpMethods; readonly RefitSettings settings; public RequestBuilderImplementation(Type targetInterface, RefitSettings refitSettings = null) { settings = refitSettings ?? new RefitSettings(); if (targetInterface == null || !targetInterface.IsInterface()) { throw new ArgumentException("targetInterface must be an Interface"); } targetType = targetInterface; interfaceHttpMethods = targetInterface.GetMethods() .SelectMany(x => { var attrs = x.GetCustomAttributes(true); var hasHttpMethod = attrs.OfType<HttpMethodAttribute>().Any(); if (!hasHttpMethod) return Enumerable.Empty<RestMethodInfo>(); return EnumerableEx.Return(new RestMethodInfo(targetInterface, x, settings)); }) .ToDictionary(k => k.Name, v => v); } public IEnumerable<string> InterfaceHttpMethods { get { return interfaceHttpMethods.Keys; } } Func<object[], HttpRequestMessage> buildRequestFactoryForMethod(string methodName, string basePath, bool paramsContainsCancellationToken) { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; return paramList => { // make sure we strip out any cancelation tokens if (paramsContainsCancellationToken) { paramList = paramList.Where(o => o == null || o.GetType() != typeof(CancellationToken)).ToArray(); } var ret = new HttpRequestMessage { Method = restMethod.HttpMethod, }; // set up multipart content MultipartFormDataContent multiPartContent = null; if (restMethod.IsMultipart) { multiPartContent = new MultipartFormDataContent("----MyGreatBoundary"); ret.Content = multiPartContent; } string urlTarget = (basePath == "/" ? String.Empty : basePath) + restMethod.RelativePath; var queryParamsToAdd = new Dictionary<string, string>(); var headersToAdd = new Dictionary<string, string>(restMethod.Headers); for(int i=0; i < paramList.Length; i++) { // if part of REST resource URL, substitute it in if (restMethod.ParameterMap.ContainsKey(i)) { urlTarget = Regex.Replace( urlTarget, "{" + restMethod.ParameterMap[i] + "}", settings.UrlParameterFormatter .Format(paramList[i], restMethod.ParameterInfoMap[i]) .Replace("/", "%2F"), RegexOptions.IgnoreCase); continue; } // if marked as body, add to content if (restMethod.BodyParameterInfo != null && restMethod.BodyParameterInfo.Item2 == i) { var streamParam = paramList[i] as Stream; var stringParam = paramList[i] as string; var httpContentParam = paramList[i] as HttpContent; if (httpContentParam != null) { ret.Content = httpContentParam; } else if (streamParam != null) { ret.Content = new StreamContent(streamParam); } else if (stringParam != null) { ret.Content = new StringContent(stringParam); } else { switch (restMethod.BodyParameterInfo.Item1) { case BodySerializationMethod.UrlEncoded: ret.Content = new FormUrlEncodedContent(new FormValueDictionary(paramList[i])); break; case BodySerializationMethod.Json: ret.Content = new StringContent(JsonConvert.SerializeObject(paramList[i], settings.JsonSerializerSettings), Encoding.UTF8, "application/json"); break; } } continue; } // if header, add to request headers if (restMethod.HeaderParameterMap.ContainsKey(i)) { headersToAdd[restMethod.HeaderParameterMap[i]] = paramList[i] != null ? paramList[i].ToString() : null; continue; } // ignore nulls if (paramList[i] == null) continue; // for anything that fell through to here, if this is not // a multipart method, add the parameter to the query string if (!restMethod.IsMultipart) { queryParamsToAdd[restMethod.QueryParameterMap[i]] = settings.UrlParameterFormatter.Format(paramList[i], restMethod.ParameterInfoMap[i]); continue; } // we are in a multipart method, add the part to the content // the parameter name should be either the attachment name or the parameter name (as fallback) string itemName; if (! restMethod.AttachmentNameMap.TryGetValue(i, out itemName)) itemName = restMethod.QueryParameterMap[i]; addMultipartItem(multiPartContent, itemName, paramList[i]); } // NB: We defer setting headers until the body has been // added so any custom content headers don't get left out. foreach (var header in headersToAdd) { setHeader(ret, header.Key, header.Value); } // NB: The URI methods in .NET are dumb. Also, we do this // UriBuilder business so that we preserve any hardcoded query // parameters as well as add the parameterized ones. var uri = new UriBuilder(new Uri(new Uri("http://api"), urlTarget)); var query = HttpUtility.ParseQueryString(uri.Query ?? ""); foreach(var kvp in queryParamsToAdd) { query.Add(kvp.Key, kvp.Value); } if (query.HasKeys()) { var pairs = query.Keys.Cast<string>().Select(x => HttpUtility.UrlEncode(x) + "=" + HttpUtility.UrlEncode(query[x])); uri.Query = String.Join("&", pairs); } else { uri.Query = null; } ret.RequestUri = new Uri(uri.Uri.GetComponents(UriComponents.PathAndQuery, UriFormat.UriEscaped), UriKind.Relative); return ret; }; } static void setHeader(HttpRequestMessage request, string name, string value) { // Clear any existing version of this header that might be set, because // we want to allow removal/redefinition of headers. // We also don't want to double up content headers which may have been // set for us automatically. // NB: We have to enumerate the header names to check existence because // Contains throws if it's the wrong header type for the collection. if (request.Headers.Any(x => x.Key == name)) { request.Headers.Remove(name); } if (request.Content != null && request.Content.Headers.Any(x => x.Key == name)) { request.Content.Headers.Remove(name); } if (value == null) return; var added = request.Headers.TryAddWithoutValidation(name, value); // Don't even bother trying to add the header as a content header // if we just added it to the other collection. if (!added && request.Content != null) { request.Content.Headers.TryAddWithoutValidation(name, value); } } void addMultipartItem(MultipartFormDataContent multiPartContent, string itemName, object itemValue) { var streamValue = itemValue as Stream; var stringValue = itemValue as String; var byteArrayValue = itemValue as byte[]; if (streamValue != null) { var streamContent = new StreamContent(streamValue); streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = itemName }; multiPartContent.Add(streamContent); return; } if (stringValue != null) { multiPartContent.Add(new StringContent(stringValue), itemName); return; } #if !NETFX_CORE var fileInfoValue = itemValue as FileInfo; if (fileInfoValue != null) { var fileContent = new StreamContent(fileInfoValue.OpenRead()); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = fileInfoValue.Name }; multiPartContent.Add(fileContent); return; } #endif if (byteArrayValue != null) { var fileContent = new ByteArrayContent(byteArrayValue); fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = itemName }; multiPartContent.Add(fileContent); return; } throw new ArgumentException(string.Format("Unexpected parameter type in a Multipart request. Parameter {0} is of type {1}, whereas allowed types are String, Stream, FileInfo, and Byte array", itemName, itemValue.GetType().Name), "itemValue"); } public Func<HttpClient, object[], object> BuildRestResultFuncForMethod(string methodName) { if (!interfaceHttpMethods.ContainsKey(methodName)) { throw new ArgumentException("Method must be defined and have an HTTP Method attribute"); } var restMethod = interfaceHttpMethods[methodName]; if (restMethod.ReturnType == typeof(Task)) { return buildVoidTaskFuncForMethod(restMethod); } else if (restMethod.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) { // NB: This jacked up reflection code is here because it's // difficult to upcast Task<object> to an arbitrary T, especially // if you need to AOT everything, so we need to reflectively // invoke buildTaskFuncForMethod. var taskFuncMi = GetType().GetMethod("buildTaskFuncForMethod", BindingFlags.NonPublic | BindingFlags.Instance); var taskFunc = (MulticastDelegate)taskFuncMi.MakeGenericMethod(restMethod.SerializedReturnType) .Invoke(this, new[] { restMethod }); return (client, args) => { return taskFunc.DynamicInvoke(new object[] { client, args } ); }; } else { // Same deal var rxFuncMi = GetType().GetMethod("buildRxFuncForMethod", BindingFlags.NonPublic | BindingFlags.Instance); var rxFunc = (MulticastDelegate)rxFuncMi.MakeGenericMethod(restMethod.SerializedReturnType) .Invoke(this, new[] { restMethod }); return (client, args) => { return rxFunc.DynamicInvoke(new object[] { client, args }); }; } } Func<HttpClient, object[], Task> buildVoidTaskFuncForMethod(RestMethodInfo restMethod) { return async (client, paramList) => { var factory = buildRequestFactoryForMethod(restMethod.Name, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null); var rq = factory(paramList); var ct = CancellationToken.None; if (restMethod.CancellationToken != null) { ct = paramList.OfType<CancellationToken>().FirstOrDefault(); } using (var resp = await client.SendAsync(rq, ct).ConfigureAwait(false)) { if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(rq.RequestUri, restMethod.HttpMethod, resp, settings).ConfigureAwait(false); } } }; } Func<HttpClient, object[], Task<T>> buildTaskFuncForMethod<T>(RestMethodInfo restMethod) { var ret = buildCancellableTaskFuncForMethod<T>(restMethod); return (client, paramList) => { if(restMethod.CancellationToken != null) { return ret(client, paramList.OfType<CancellationToken>().FirstOrDefault(), paramList); } return ret(client, CancellationToken.None, paramList); }; } Func<HttpClient, CancellationToken, object[], Task<T>> buildCancellableTaskFuncForMethod<T>(RestMethodInfo restMethod) { return async (client, ct, paramList) => { var factory = buildRequestFactoryForMethod(restMethod.Name, client.BaseAddress.AbsolutePath, restMethod.CancellationToken != null); var rq = factory(paramList); var resp = await client.SendAsync(rq, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false); if (restMethod.SerializedReturnType == typeof(HttpResponseMessage)) { // NB: This double-casting manual-boxing hate crime is the only way to make // this work without a 'class' generic constraint. It could blow up at runtime // and would be A Bad Idea if we hadn't already vetted the return type. return (T)(object)resp; } if (!resp.IsSuccessStatusCode) { throw await ApiException.Create(rq.RequestUri, restMethod.HttpMethod, resp, restMethod.RefitSettings).ConfigureAwait(false); } if (restMethod.SerializedReturnType == typeof(HttpContent)) { return (T)(object)resp.Content; } var ms = new MemoryStream(); using (var fromStream = await resp.Content.ReadAsStreamAsync().ConfigureAwait(false)) { await fromStream.CopyToAsync(ms, 4096, ct).ConfigureAwait(false); } var bytes = ms.ToArray(); var content = Encoding.UTF8.GetString(bytes, 0, bytes.Length); if (restMethod.SerializedReturnType == typeof(string)) { return (T)(object)content; } return JsonConvert.DeserializeObject<T>(content, settings.JsonSerializerSettings); }; } Func<HttpClient, object[], IObservable<T>> buildRxFuncForMethod<T>(RestMethodInfo restMethod) { var taskFunc = buildCancellableTaskFuncForMethod<T>(restMethod); return (client, paramList) => { return new TaskToObservable<T>(ct => { var methodCt = CancellationToken.None; if (restMethod.CancellationToken != null) { methodCt = paramList.OfType<CancellationToken>().FirstOrDefault(); } // link the two var cts = CancellationTokenSource.CreateLinkedTokenSource(methodCt, ct); return taskFunc(client, cts.Token, paramList); }); }; } class TaskToObservable<T> : IObservable<T> { Func<CancellationToken, Task<T>> taskFactory; public TaskToObservable(Func<CancellationToken, Task<T>> taskFactory) { this.taskFactory = taskFactory; } public IDisposable Subscribe(IObserver<T> observer) { var cts = new CancellationTokenSource(); taskFactory(cts.Token).ContinueWith(t => { if (cts.IsCancellationRequested) return; if (t.Exception != null) { observer.OnError(t.Exception.InnerExceptions.First()); return; } try { observer.OnNext(t.Result); } catch (Exception ex) { observer.OnError(ex); } observer.OnCompleted(); }); return new AnonymousDisposable(cts.Cancel); } } } sealed class AnonymousDisposable : IDisposable { readonly Action block; public AnonymousDisposable(Action block) { this.block = block; } public void Dispose() { block(); } } public class RestMethodInfo { public string Name { get; set; } public Type Type { get; set; } public MethodInfo MethodInfo { get; set; } public HttpMethod HttpMethod { get; set; } public string RelativePath { get; set; } public bool IsMultipart { get; private set; } public Dictionary<int, string> ParameterMap { get; set; } public ParameterInfo CancellationToken { get; set; } public Dictionary<string, string> Headers { get; set; } public Dictionary<int, string> HeaderParameterMap { get; set; } public Tuple<BodySerializationMethod, int> BodyParameterInfo { get; set; } public Dictionary<int, string> QueryParameterMap { get; set; } public Dictionary<int, string> AttachmentNameMap { get; set; } public Dictionary<int, ParameterInfo> ParameterInfoMap { get; set; } public Type ReturnType { get; set; } public Type SerializedReturnType { get; set; } public RefitSettings RefitSettings { get; set; } static readonly Regex parameterRegex = new Regex(@"{(.*?)}"); static readonly HttpMethod patchMethod = new HttpMethod("PATCH"); public RestMethodInfo(Type targetInterface, MethodInfo methodInfo, RefitSettings refitSettings = null) { RefitSettings = refitSettings ?? new RefitSettings(); Type = targetInterface; Name = methodInfo.Name; MethodInfo = methodInfo; var hma = methodInfo.GetCustomAttributes(true) .OfType<HttpMethodAttribute>() .First(); HttpMethod = hma.Method; RelativePath = hma.Path; IsMultipart = methodInfo.GetCustomAttributes(true) .OfType<MultipartAttribute>() .Any(); verifyUrlPathIsSane(RelativePath); determineReturnTypeInfo(methodInfo); // Exclude cancellation token parameters from this list var parameterList = methodInfo.GetParameters().Where(p => p.ParameterType != typeof(CancellationToken)).ToList(); ParameterInfoMap = parameterList .Select((parameter, index) => new { index, parameter }) .ToDictionary(x => x.index, x => x.parameter); ParameterMap = buildParameterMap(RelativePath, parameterList); BodyParameterInfo = findBodyParameter(parameterList, IsMultipart, hma.Method); Headers = parseHeaders(methodInfo); HeaderParameterMap = buildHeaderParameterMap(parameterList); // get names for multipart attachments AttachmentNameMap = new Dictionary<int, string>(); if (IsMultipart) { for (int i = 0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i)) { continue; } var attachmentName = getAttachmentNameForParameter(parameterList[i]); if (attachmentName == null) continue; AttachmentNameMap[i] = attachmentName; } } QueryParameterMap = new Dictionary<int, string>(); for (int i=0; i < parameterList.Count; i++) { if (ParameterMap.ContainsKey(i) || HeaderParameterMap.ContainsKey(i) || (BodyParameterInfo != null && BodyParameterInfo.Item2 == i) || AttachmentNameMap.ContainsKey(i)) { continue; } QueryParameterMap[i] = getUrlNameForParameter(parameterList[i]); } var ctParams = methodInfo.GetParameters().Where(p => p.ParameterType == typeof(CancellationToken)).ToList(); if(ctParams.Count > 1) { throw new ArgumentException("Argument list can only contain a single CancellationToken"); } CancellationToken = ctParams.FirstOrDefault(); } void verifyUrlPathIsSane(string relativePath) { if (relativePath == "") return; if (!relativePath.StartsWith("/")) { goto bogusPath; } var parts = relativePath.Split('/'); if (parts.Length == 0) { goto bogusPath; } return; bogusPath: throw new ArgumentException("URL path must be of the form '/foo/bar/baz'"); } Dictionary<int, string> buildParameterMap(string relativePath, List<ParameterInfo> parameterInfo) { var ret = new Dictionary<int, string>(); var parameterizedParts = relativePath.Split('/', '?') .SelectMany(x => parameterRegex.Matches(x).Cast<Match>()) .ToList(); if (parameterizedParts.Count == 0) { return ret; } var paramValidationDict = parameterInfo.ToDictionary(k => getUrlNameForParameter(k).ToLowerInvariant(), v => v); foreach (var match in parameterizedParts) { var name = match.Groups[1].Value.ToLowerInvariant(); if (!paramValidationDict.ContainsKey(name)) { throw new ArgumentException(String.Format("URL has parameter {0}, but no method parameter matches", name)); } ret.Add(parameterInfo.IndexOf(paramValidationDict[name]), name); } return ret; } string getUrlNameForParameter(ParameterInfo paramInfo) { var aliasAttr = paramInfo.GetCustomAttributes(true) .OfType<AliasAsAttribute>() .FirstOrDefault(); return aliasAttr != null ? aliasAttr.Name : paramInfo.Name; } string getAttachmentNameForParameter(ParameterInfo paramInfo) { var nameAttr = paramInfo.GetCustomAttributes(true) .OfType<AttachmentNameAttribute>() .FirstOrDefault(); return nameAttr != null ? nameAttr.Name : null; } static Tuple<BodySerializationMethod, int> findBodyParameter(IList<ParameterInfo> parameterList, bool isMultipart, HttpMethod method) { // The body parameter is found using the following logic / order of precedence: // 1) [Body] attribute // 2) POST/PUT/PATCH: Reference type other than string // 3) If there are two reference types other than string, without the body attribute, throw var bodyParams = parameterList .Select(x => new { Parameter = x, BodyAttribute = x.GetCustomAttributes(true).OfType<BodyAttribute>().FirstOrDefault() }) .Where(x => x.BodyAttribute != null) .ToList(); // multipart requests may not contain a body, implicit or explicit if (isMultipart) { if (bodyParams.Count > 0) { throw new ArgumentException("Multipart requests may not contain a Body parameter"); } return null; } if (bodyParams.Count > 1) { throw new ArgumentException("Only one parameter can be a Body parameter"); } // #1, body attribute wins if (bodyParams.Count == 1) { var ret = bodyParams[0]; return Tuple.Create(ret.BodyAttribute.SerializationMethod, parameterList.IndexOf(ret.Parameter)); } // Not in post/put/patch? bail if (!method.Equals(HttpMethod.Post) && !method.Equals(HttpMethod.Put) && !method.Equals(patchMethod)) { return null; } // see if we're a post/put/patch var refParams = parameterList.Where(pi => !pi.ParameterType.GetTypeInfo().IsValueType && pi.ParameterType != typeof(string)).ToList(); // Check for rule #3 if (refParams.Count > 1) { throw new ArgumentException("Multiple complex types found. Specify one parameter as the body using BodyAttribute"); } if (refParams.Count == 1) { return Tuple.Create(BodySerializationMethod.Json, parameterList.IndexOf(refParams[0])); } return null; } Dictionary<string, string> parseHeaders(MethodInfo methodInfo) { var ret = new Dictionary<string, string>(); var declaringTypeAttributes = methodInfo.DeclaringType != null ? methodInfo.DeclaringType.GetCustomAttributes(true) : new Attribute[0]; // Headers set on the declaring type have to come first, // so headers set on the method can replace them. Switching // the order here will break stuff. var headers = declaringTypeAttributes.Concat(methodInfo.GetCustomAttributes(true)) .OfType<HeadersAttribute>() .SelectMany(ha => ha.Headers); foreach (var header in headers) { if (string.IsNullOrWhiteSpace(header)) continue; // NB: Silverlight doesn't have an overload for String.Split() // with a count parameter, but header values can contain // ':' so we have to re-join all but the first part to get the // value. var parts = header.Split(':'); ret[parts[0].Trim()] = parts.Length > 1 ? String.Join(":", parts.Skip(1)).Trim() : null; } return ret; } Dictionary<int, string> buildHeaderParameterMap(List<ParameterInfo> parameterList) { var ret = new Dictionary<int, string>(); for (int i = 0; i < parameterList.Count; i++) { var header = parameterList[i].GetCustomAttributes(true) .OfType<HeaderAttribute>() .Select(ha => ha.Header) .FirstOrDefault(); if (!string.IsNullOrWhiteSpace(header)) { ret[i] = header.Trim(); } } return ret; } void determineReturnTypeInfo(MethodInfo methodInfo) { if (methodInfo.ReturnType.IsGenericType() == false) { if (methodInfo.ReturnType != typeof (Task)) { goto bogusMethod; } ReturnType = methodInfo.ReturnType; SerializedReturnType = typeof(void); return; } var genericType = methodInfo.ReturnType.GetGenericTypeDefinition(); if (genericType != typeof(Task<>) && genericType != typeof(IObservable<>)) { goto bogusMethod; } ReturnType = methodInfo.ReturnType; SerializedReturnType = methodInfo.ReturnType.GetGenericArguments()[0]; return; bogusMethod: throw new ArgumentException("All REST Methods must return either Task<T> or IObservable<T>"); } } class FormValueDictionary : Dictionary<string, string> { static readonly Dictionary<Type, PropertyInfo[]> propertyCache = new Dictionary<Type, PropertyInfo[]>(); public FormValueDictionary(object source) { if (source == null) return; var dictionary = source as IDictionary; if (dictionary != null) { foreach (var key in dictionary.Keys) { Add(key.ToString(), string.Format("{0}", dictionary[key])); } return; } var type = source.GetType(); lock (propertyCache) { if (!propertyCache.ContainsKey(type)) { propertyCache[type] = getProperties(type); } foreach (var property in propertyCache[type]) { Add(getFieldNameForProperty(property), string.Format("{0}", property.GetValue(source, null))); } } } PropertyInfo[] getProperties(Type type) { return type.GetProperties() .Where(p => p.CanRead) .ToArray(); } string getFieldNameForProperty(PropertyInfo propertyInfo) { var aliasAttr = propertyInfo.GetCustomAttributes(true) .OfType<AliasAsAttribute>() .FirstOrDefault(); return aliasAttr != null ? aliasAttr.Name : propertyInfo.Name; } } class AuthenticatedHttpClientHandler : DelegatingHandler { readonly Func<Task<string>> getToken; public AuthenticatedHttpClientHandler(Func<Task<string>> getToken, HttpMessageHandler innerHandler = null) : base(innerHandler ?? new HttpClientHandler()) { if (getToken == null) throw new ArgumentNullException("getToken"); this.getToken = getToken; } protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { // See if the request has an authorize header var auth = request.Headers.Authorization; if (auth != null) { var token = await getToken().ConfigureAwait(false); request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token); } return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/dataproc/v1/clusters.proto // Original file comments: // Copyright 2016 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #region Designer generated code using System; using System.Threading; using System.Threading.Tasks; using Grpc.Core; namespace Google.Cloud.Dataproc.V1 { /// <summary> /// The ClusterControllerService provides methods to manage clusters /// of Google Compute Engine instances. /// </summary> public static class ClusterController { static readonly string __ServiceName = "google.cloud.dataproc.v1.ClusterController"; static readonly Marshaller<global::Google.Cloud.Dataproc.V1.CreateClusterRequest> __Marshaller_CreateClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.CreateClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.LongRunning.Operation> __Marshaller_Operation = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.LongRunning.Operation.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.UpdateClusterRequest> __Marshaller_UpdateClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.UpdateClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.DeleteClusterRequest> __Marshaller_DeleteClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.DeleteClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.GetClusterRequest> __Marshaller_GetClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.GetClusterRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.Cluster> __Marshaller_Cluster = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.Cluster.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.ListClustersRequest> __Marshaller_ListClustersRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.ListClustersRequest.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.ListClustersResponse> __Marshaller_ListClustersResponse = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.ListClustersResponse.Parser.ParseFrom); static readonly Marshaller<global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest> __Marshaller_DiagnoseClusterRequest = Marshallers.Create((arg) => global::Google.Protobuf.MessageExtensions.ToByteArray(arg), global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest.Parser.ParseFrom); static readonly Method<global::Google.Cloud.Dataproc.V1.CreateClusterRequest, global::Google.LongRunning.Operation> __Method_CreateCluster = new Method<global::Google.Cloud.Dataproc.V1.CreateClusterRequest, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "CreateCluster", __Marshaller_CreateClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Cloud.Dataproc.V1.UpdateClusterRequest, global::Google.LongRunning.Operation> __Method_UpdateCluster = new Method<global::Google.Cloud.Dataproc.V1.UpdateClusterRequest, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "UpdateCluster", __Marshaller_UpdateClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Cloud.Dataproc.V1.DeleteClusterRequest, global::Google.LongRunning.Operation> __Method_DeleteCluster = new Method<global::Google.Cloud.Dataproc.V1.DeleteClusterRequest, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "DeleteCluster", __Marshaller_DeleteClusterRequest, __Marshaller_Operation); static readonly Method<global::Google.Cloud.Dataproc.V1.GetClusterRequest, global::Google.Cloud.Dataproc.V1.Cluster> __Method_GetCluster = new Method<global::Google.Cloud.Dataproc.V1.GetClusterRequest, global::Google.Cloud.Dataproc.V1.Cluster>( MethodType.Unary, __ServiceName, "GetCluster", __Marshaller_GetClusterRequest, __Marshaller_Cluster); static readonly Method<global::Google.Cloud.Dataproc.V1.ListClustersRequest, global::Google.Cloud.Dataproc.V1.ListClustersResponse> __Method_ListClusters = new Method<global::Google.Cloud.Dataproc.V1.ListClustersRequest, global::Google.Cloud.Dataproc.V1.ListClustersResponse>( MethodType.Unary, __ServiceName, "ListClusters", __Marshaller_ListClustersRequest, __Marshaller_ListClustersResponse); static readonly Method<global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest, global::Google.LongRunning.Operation> __Method_DiagnoseCluster = new Method<global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest, global::Google.LongRunning.Operation>( MethodType.Unary, __ServiceName, "DiagnoseCluster", __Marshaller_DiagnoseClusterRequest, __Marshaller_Operation); /// <summary>Service descriptor</summary> public static global::Google.Protobuf.Reflection.ServiceDescriptor Descriptor { get { return global::Google.Cloud.Dataproc.V1.ClustersReflection.Descriptor.Services[0]; } } /// <summary>Base class for server-side implementations of ClusterController</summary> public abstract class ClusterControllerBase { /// <summary> /// Creates a cluster in a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> CreateCluster(global::Google.Cloud.Dataproc.V1.CreateClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Updates a cluster in a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> UpdateCluster(global::Google.Cloud.Dataproc.V1.UpdateClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Deletes a cluster in a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> DeleteCluster(global::Google.Cloud.Dataproc.V1.DeleteClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets the resource representation for a cluster in a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dataproc.V1.Cluster> GetCluster(global::Google.Cloud.Dataproc.V1.GetClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Lists all regions/{region}/clusters in a project. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.Cloud.Dataproc.V1.ListClustersResponse> ListClusters(global::Google.Cloud.Dataproc.V1.ListClustersRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } /// <summary> /// Gets cluster diagnostic information. /// After the operation completes, the Operation.response field /// contains `DiagnoseClusterOutputLocation`. /// </summary> public virtual global::System.Threading.Tasks.Task<global::Google.LongRunning.Operation> DiagnoseCluster(global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest request, ServerCallContext context) { throw new RpcException(new Status(StatusCode.Unimplemented, "")); } } /// <summary>Client for ClusterController</summary> public class ClusterControllerClient : ClientBase<ClusterControllerClient> { /// <summary>Creates a new client for ClusterController</summary> /// <param name="channel">The channel to use to make remote calls.</param> public ClusterControllerClient(Channel channel) : base(channel) { } /// <summary>Creates a new client for ClusterController that uses a custom <c>CallInvoker</c>.</summary> /// <param name="callInvoker">The callInvoker to use to make remote calls.</param> public ClusterControllerClient(CallInvoker callInvoker) : base(callInvoker) { } /// <summary>Protected parameterless constructor to allow creation of test doubles.</summary> protected ClusterControllerClient() : base() { } /// <summary>Protected constructor to allow creation of configured clients.</summary> /// <param name="configuration">The client configuration.</param> protected ClusterControllerClient(ClientBaseConfiguration configuration) : base(configuration) { } /// <summary> /// Creates a cluster in a project. /// </summary> public virtual global::Google.LongRunning.Operation CreateCluster(global::Google.Cloud.Dataproc.V1.CreateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a cluster in a project. /// </summary> public virtual global::Google.LongRunning.Operation CreateCluster(global::Google.Cloud.Dataproc.V1.CreateClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_CreateCluster, null, options, request); } /// <summary> /// Creates a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> CreateClusterAsync(global::Google.Cloud.Dataproc.V1.CreateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return CreateClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Creates a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> CreateClusterAsync(global::Google.Cloud.Dataproc.V1.CreateClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_CreateCluster, null, options, request); } /// <summary> /// Updates a cluster in a project. /// </summary> public virtual global::Google.LongRunning.Operation UpdateCluster(global::Google.Cloud.Dataproc.V1.UpdateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a cluster in a project. /// </summary> public virtual global::Google.LongRunning.Operation UpdateCluster(global::Google.Cloud.Dataproc.V1.UpdateClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_UpdateCluster, null, options, request); } /// <summary> /// Updates a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> UpdateClusterAsync(global::Google.Cloud.Dataproc.V1.UpdateClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return UpdateClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Updates a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> UpdateClusterAsync(global::Google.Cloud.Dataproc.V1.UpdateClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_UpdateCluster, null, options, request); } /// <summary> /// Deletes a cluster in a project. /// </summary> public virtual global::Google.LongRunning.Operation DeleteCluster(global::Google.Cloud.Dataproc.V1.DeleteClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a cluster in a project. /// </summary> public virtual global::Google.LongRunning.Operation DeleteCluster(global::Google.Cloud.Dataproc.V1.DeleteClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DeleteCluster, null, options, request); } /// <summary> /// Deletes a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> DeleteClusterAsync(global::Google.Cloud.Dataproc.V1.DeleteClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DeleteClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Deletes a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> DeleteClusterAsync(global::Google.Cloud.Dataproc.V1.DeleteClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DeleteCluster, null, options, request); } /// <summary> /// Gets the resource representation for a cluster in a project. /// </summary> public virtual global::Google.Cloud.Dataproc.V1.Cluster GetCluster(global::Google.Cloud.Dataproc.V1.GetClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the resource representation for a cluster in a project. /// </summary> public virtual global::Google.Cloud.Dataproc.V1.Cluster GetCluster(global::Google.Cloud.Dataproc.V1.GetClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_GetCluster, null, options, request); } /// <summary> /// Gets the resource representation for a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Dataproc.V1.Cluster> GetClusterAsync(global::Google.Cloud.Dataproc.V1.GetClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return GetClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets the resource representation for a cluster in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Dataproc.V1.Cluster> GetClusterAsync(global::Google.Cloud.Dataproc.V1.GetClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_GetCluster, null, options, request); } /// <summary> /// Lists all regions/{region}/clusters in a project. /// </summary> public virtual global::Google.Cloud.Dataproc.V1.ListClustersResponse ListClusters(global::Google.Cloud.Dataproc.V1.ListClustersRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListClusters(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists all regions/{region}/clusters in a project. /// </summary> public virtual global::Google.Cloud.Dataproc.V1.ListClustersResponse ListClusters(global::Google.Cloud.Dataproc.V1.ListClustersRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_ListClusters, null, options, request); } /// <summary> /// Lists all regions/{region}/clusters in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Dataproc.V1.ListClustersResponse> ListClustersAsync(global::Google.Cloud.Dataproc.V1.ListClustersRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return ListClustersAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Lists all regions/{region}/clusters in a project. /// </summary> public virtual AsyncUnaryCall<global::Google.Cloud.Dataproc.V1.ListClustersResponse> ListClustersAsync(global::Google.Cloud.Dataproc.V1.ListClustersRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_ListClusters, null, options, request); } /// <summary> /// Gets cluster diagnostic information. /// After the operation completes, the Operation.response field /// contains `DiagnoseClusterOutputLocation`. /// </summary> public virtual global::Google.LongRunning.Operation DiagnoseCluster(global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DiagnoseCluster(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets cluster diagnostic information. /// After the operation completes, the Operation.response field /// contains `DiagnoseClusterOutputLocation`. /// </summary> public virtual global::Google.LongRunning.Operation DiagnoseCluster(global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest request, CallOptions options) { return CallInvoker.BlockingUnaryCall(__Method_DiagnoseCluster, null, options, request); } /// <summary> /// Gets cluster diagnostic information. /// After the operation completes, the Operation.response field /// contains `DiagnoseClusterOutputLocation`. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> DiagnoseClusterAsync(global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest request, Metadata headers = null, DateTime? deadline = null, CancellationToken cancellationToken = default(CancellationToken)) { return DiagnoseClusterAsync(request, new CallOptions(headers, deadline, cancellationToken)); } /// <summary> /// Gets cluster diagnostic information. /// After the operation completes, the Operation.response field /// contains `DiagnoseClusterOutputLocation`. /// </summary> public virtual AsyncUnaryCall<global::Google.LongRunning.Operation> DiagnoseClusterAsync(global::Google.Cloud.Dataproc.V1.DiagnoseClusterRequest request, CallOptions options) { return CallInvoker.AsyncUnaryCall(__Method_DiagnoseCluster, null, options, request); } protected override ClusterControllerClient NewInstance(ClientBaseConfiguration configuration) { return new ClusterControllerClient(configuration); } } /// <summary>Creates service definition that can be registered with a server</summary> public static ServerServiceDefinition BindService(ClusterControllerBase serviceImpl) { return ServerServiceDefinition.CreateBuilder() .AddMethod(__Method_CreateCluster, serviceImpl.CreateCluster) .AddMethod(__Method_UpdateCluster, serviceImpl.UpdateCluster) .AddMethod(__Method_DeleteCluster, serviceImpl.DeleteCluster) .AddMethod(__Method_GetCluster, serviceImpl.GetCluster) .AddMethod(__Method_ListClusters, serviceImpl.ListClusters) .AddMethod(__Method_DiagnoseCluster, serviceImpl.DiagnoseCluster).Build(); } } } #endregion
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Text; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Pkcs.Tests.Pkcs12 { public static class Pkcs12InfoTests { [Fact] public static void ReadEmptyPfx() { Pkcs12Info info = Pkcs12Info.Decode(Pkcs12Documents.EmptyPfx, out int bytesRead, skipCopy: true); Assert.Equal(Pkcs12Documents.EmptyPfx.Length, bytesRead); Assert.Equal(Pkcs12IntegrityMode.Password, info.IntegrityMode); Assert.False(info.VerifyMac("hello"), "Wrong password"); Assert.True(info.VerifyMac(ReadOnlySpan<char>.Empty), "null password (ReadOnlySpan)"); Assert.True(info.VerifyMac(null), "null password (string)"); Assert.False(info.VerifyMac("".AsSpan()), "empty password (ReadOnlySpan)"); Assert.False(info.VerifyMac(""), "empty password (string)"); Assert.False(info.VerifyMac("hello".AsSpan(5)), "sliced out"); Assert.False(info.VerifyMac("hello".AsSpan(0, 0)), "zero-sliced"); Assert.False(info.VerifyMac(new char[0]), "empty array"); Assert.False(info.VerifyMac((new char[1]).AsSpan(1)), "sliced out array"); Assert.False(info.VerifyMac((new char[1]).AsSpan(0, 0)), "zero-sliced array"); ReadOnlyCollection<Pkcs12SafeContents> safes = info.AuthenticatedSafe; Assert.Equal(0, safes.Count); } [Fact] public static void ReadIndefiniteEncodingNoMac() { Pkcs12Info info = Pkcs12Info.Decode( Pkcs12Documents.IndefiniteEncodingNoMac, out int bytesRead, skipCopy: true); Assert.Equal(Pkcs12Documents.IndefiniteEncodingNoMac.Length, bytesRead); Assert.Equal(Pkcs12IntegrityMode.None, info.IntegrityMode); ReadOnlyCollection<Pkcs12SafeContents> safes = info.AuthenticatedSafe; Assert.Equal(2, safes.Count); Pkcs12SafeContents firstSafe = safes[0]; Pkcs12SafeContents secondSafe = safes[1]; Assert.Equal(Pkcs12ConfidentialityMode.None, firstSafe.ConfidentialityMode); Assert.Equal(Pkcs12ConfidentialityMode.None, secondSafe.ConfidentialityMode); Assert.True(firstSafe.IsReadOnly, "firstSafe.IsReadOnly"); Assert.True(secondSafe.IsReadOnly, "secondSafe.IsReadOnly"); Pkcs12SafeBag[] firstContents = firstSafe.GetBags().ToArray(); Pkcs12SafeBag[] secondContents = secondSafe.GetBags().ToArray(); Assert.Equal(1, firstContents.Length); Assert.Equal(1, secondContents.Length); Pkcs12KeyBag keyBag = Assert.IsType<Pkcs12KeyBag>(firstContents[0]); Pkcs12CertBag certBag = Assert.IsType<Pkcs12CertBag>(secondContents[0]); CryptographicAttributeObjectCollection keyBagAttrs = keyBag.Attributes; CryptographicAttributeObjectCollection certBagAttrs = certBag.Attributes; Assert.Equal(2, keyBagAttrs.Count); Assert.Equal(2, certBagAttrs.Count); Assert.Equal(Oids.FriendlyName, keyBagAttrs[0].Oid.Value); Assert.Equal(1, keyBagAttrs[0].Values.Count); Assert.Equal(Oids.LocalKeyId, keyBagAttrs[1].Oid.Value); Assert.Equal(1, keyBagAttrs[1].Values.Count); Pkcs9AttributeObject keyFriendlyName = Assert.IsAssignableFrom<Pkcs9AttributeObject>(keyBagAttrs[0].Values[0]); Pkcs9LocalKeyId keyKeyId = Assert.IsType<Pkcs9LocalKeyId>(keyBagAttrs[1].Values[0]); Assert.Equal(Oids.FriendlyName, certBagAttrs[0].Oid.Value); Assert.Equal(1, certBagAttrs[0].Values.Count); Assert.Equal(Oids.LocalKeyId, certBagAttrs[1].Oid.Value); Assert.Equal(1, certBagAttrs[1].Values.Count); Pkcs9AttributeObject certFriendlyName = Assert.IsAssignableFrom<Pkcs9AttributeObject>(certBagAttrs[0].Values[0]); Pkcs9LocalKeyId certKeyId = Assert.IsType<Pkcs9LocalKeyId>(certBagAttrs[1].Values[0]); // This PFX gave a friendlyName value of "cert" to both the key and the cert. Assert.Equal("1E080063006500720074", keyFriendlyName.RawData.ByteArrayToHex()); Assert.Equal(keyFriendlyName.RawData, certFriendlyName.RawData); // The private key (KeyBag) and the public key (CertBag) are matched from their keyId value. Assert.Equal("0414EDF3D122CF623CF0CFC9CD226261E8415A83E630", keyKeyId.RawData.ByteArrayToHex()); Assert.Equal("EDF3D122CF623CF0CFC9CD226261E8415A83E630", keyKeyId.KeyId.ByteArrayToHex()); Assert.Equal(keyKeyId.RawData, certKeyId.RawData); using (X509Certificate2 cert = certBag.GetCertificate()) using (RSA privateKey = RSA.Create()) using (RSA publicKey = cert.GetRSAPublicKey()) { privateKey.ImportPkcs8PrivateKey(keyBag.Pkcs8PrivateKey.Span, out _); Assert.Equal( publicKey.ExportSubjectPublicKeyInfo().ByteArrayToHex(), privateKey.ExportSubjectPublicKeyInfo().ByteArrayToHex()); } } [Fact] public static void ReadOracleWallet() { Pkcs12Info info = Pkcs12Info.Decode( Pkcs12Documents.SimpleOracleWallet, out int bytesRead, skipCopy: true); Assert.Equal(Pkcs12IntegrityMode.Password, info.IntegrityMode); Assert.False(info.VerifyMac(ReadOnlySpan<char>.Empty), "VerifyMac(no password)"); Assert.False(info.VerifyMac(""), "VerifyMac(empty password)"); Assert.True(info.VerifyMac(Pkcs12Documents.OracleWalletPassword), "VerifyMac(correct password)"); ReadOnlyCollection<Pkcs12SafeContents> authSafes = info.AuthenticatedSafe; Assert.Equal(1, authSafes.Count); Pkcs12SafeContents authSafe = authSafes[0]; Assert.Equal(Pkcs12ConfidentialityMode.Password, authSafe.ConfidentialityMode); // Wrong password Assert.ThrowsAny<CryptographicException>(() => authSafe.Decrypt(ReadOnlySpan<char>.Empty)); authSafe.Decrypt(Pkcs12Documents.OracleWalletPassword); Assert.Equal(Pkcs12ConfidentialityMode.None, authSafe.ConfidentialityMode); List<Pkcs12SafeBag> bags = authSafe.GetBags().ToList(); Assert.Equal(4, bags.Count); CheckOracleSecretBag( bags[0], "oracle.security.client.connect_string1", "a_prod_db", "E6B652DD0000000400000000000000060000000300000000"); CheckOracleSecretBag( bags[1], "a@#3#@b", "{pwd_cred_type}@#4#@NEVER_EXPIRE@#5#@c@#111#@d", "E6B652DD0000000400000000000000060000000200000000"); CheckOracleSecretBag( bags[2], "oracle.security.client.username1", "a_test_user", "E6B652DD0000000400000000000000060000000100000000"); CheckOracleSecretBag( bags[3], "oracle.security.client.password1", "potatos are tasty", "E6B652DD0000000400000000000000060000000000000000"); } private static void CheckOracleSecretBag( Pkcs12SafeBag safeBag, string key, string value, string keyId) { Pkcs12SecretBag secretBag = Assert.IsType<Pkcs12SecretBag>(safeBag); Assert.Equal("1.2.840.113549.1.16.12.12", secretBag.GetSecretType().Value); Assert.Equal( MakeOracleKeyValuePairHex(key, value), secretBag.SecretValue.ByteArrayToHex()); CryptographicAttributeObjectCollection attrs = secretBag.Attributes; Assert.Equal(1, attrs.Count); CryptographicAttributeObject firstAttr = attrs[0]; Assert.Equal(Oids.LocalKeyId, firstAttr.Oid.Value); Assert.Equal(1, firstAttr.Values.Count); Pkcs9LocalKeyId localKeyId = Assert.IsType<Pkcs9LocalKeyId>(firstAttr.Values[0]); Assert.Equal(keyId, localKeyId.KeyId.ByteArrayToHex()); } private static string MakeOracleKeyValuePairHex(string key, string value) { Span<byte> outputBuf = stackalloc byte[129]; outputBuf[0] = 0x30; // Two children, one byte tag, one byte length. Add content length as it comes. ref byte totalContents = ref outputBuf[1]; totalContents = 0x04; outputBuf[2] = 0x0C; ref byte keyLen = ref outputBuf[3]; Span<byte> keyDest = outputBuf.Slice(4); keyLen = (byte)Encoding.UTF8.GetBytes(key, keyDest); totalContents += keyLen; keyDest[keyLen] = 0x0C; ref byte valLen = ref keyDest[keyLen + 1]; Span<byte> valDest = keyDest.Slice(keyLen + 2); valLen = (byte)Encoding.UTF8.GetBytes(value, valDest); totalContents += valLen; Assert.InRange(totalContents, 4, 127); return outputBuf.Slice(0, totalContents + 2).ByteArrayToHex(); } [Fact] public static void VerifyMacWithNoMac() { const string FullyEmptyHex = "3016020103301106092A864886F70D010701A00404023000"; Pkcs12Info info = Pkcs12Info.Decode(FullyEmptyHex.HexToByteArray(), out _, skipCopy: true); Assert.Equal(Pkcs12IntegrityMode.None, info.IntegrityMode); Assert.Throws<InvalidOperationException>(() => info.VerifyMac("hi")); } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.1.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace applicationGateway { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExpressRouteCircuitsOperations operations. /// </summary> public partial interface IExpressRouteCircuitsOperations { /// <summary> /// Deletes the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets information about the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of express route circuit. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuit>> GetWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update express route circuit /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuit>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the currently advertised ARP table associated with the express /// route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitsArpTableListResult>> ListArpTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the currently advertised routes table associated with the /// express route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableListResult>> ListRoutesTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the currently advertised routes table summary associated with /// the express route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableSummaryListResult>> ListRoutesTableSummaryWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the stats from an express route circuit in a resource /// group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitStats>> GetStatsWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all stats from an express route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitStats>> GetPeeringStatsWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the express route circuits in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the express route circuits in a subscription. /// </summary> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes the specified express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string circuitName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Creates or updates an express route circuit. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the circuit. /// </param> /// <param name='parameters'> /// Parameters supplied to the create or update express route circuit /// operation. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuit>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string circuitName, ExpressRouteCircuit parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the currently advertised ARP table associated with the express /// route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitsArpTableListResult>> BeginListArpTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the currently advertised routes table associated with the /// express route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableListResult>> BeginListRoutesTableWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the currently advertised routes table summary associated with /// the express route circuit in a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='circuitName'> /// The name of the express route circuit. /// </param> /// <param name='peeringName'> /// The name of the peering. /// </param> /// <param name='devicePath'> /// The path of the device. /// </param> /// <param name='customHeaders'> /// The 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> Task<AzureOperationResponse<ExpressRouteCircuitsRoutesTableSummaryListResult>> BeginListRoutesTableSummaryWithHttpMessagesAsync(string resourceGroupName, string circuitName, string peeringName, string devicePath, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the express route circuits in a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="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> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets all the express route circuits in a subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="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> Task<AzureOperationResponse<IPage<ExpressRouteCircuit>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
/******************************************************************************* * Copyright 2019 Viridian Software Limited * * 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 Org.Mini2Dx.Core; using Org.Mini2Dx.Core.Assets; using Org.Mini2Dx.Core.Font; using Org.Mini2Dx.Core.Geom; using Org.Mini2Dx.Core.Graphics; using Org.Mini2Dx.Core.Util; using Color = Org.Mini2Dx.Core.Graphics.Color; using Texture = Org.Mini2Dx.Core.Graphics.Texture; namespace monogame.Graphics { public class MonoGameSprite : MonoGameTextureRegion, Sprite { private float _x, _y, _width, _height, _originX, _originY, _rotation, _scaleX = 1, _scaleY = 1, _90degRotation; internal Microsoft.Xna.Framework.Color _actualTint = Microsoft.Xna.Framework.Color.White; private Color _tint; public MonoGameSprite() { _tint = new MonoGameColor(_actualTint); setOriginCenter_EFE09FC0(); } public MonoGameSprite(Texture texture) : this(texture, texture.getWidth_0EE0D08D(), texture.getHeight_0EE0D08D()) { } public MonoGameSprite(Texture texture, int srcWidth, int srcHeight) : this(texture, 0, 0, srcWidth, srcHeight) { } public MonoGameSprite(Texture texture, int srcX, int srcY, int srcWidth, int srcHeight) : base(texture, srcX, srcY, srcWidth, srcHeight) { _tint = new MonoGameColor(_actualTint); setBounds_C2EDAFC0(srcX, srcY, srcWidth, srcHeight); setOriginCenter_EFE09FC0(); } public MonoGameSprite(TextureRegion region) : this(region, region.getRegionWidth_0EE0D08D(), region.getRegionHeight_0EE0D08D()) { } public MonoGameSprite(TextureRegion region, int width, int height) : this(region, 0, 0, width, height) { } public MonoGameSprite(TextureRegion region, int x, int y, int width, int height) : base(region, x, y, width, height) { _tint = new MonoGameColor(_actualTint); setFlip_62FCD310(region.isFlipX_FBE0B2A4(), region.isFlipY_FBE0B2A4()); setBounds_C2EDAFC0(x, y, width, height); setOriginCenter_EFE09FC0(); } public MonoGameSprite(TextureAtlasRegion region) : this(region, region.getRegionWidth_0EE0D08D(), region.getRegionHeight_0EE0D08D()) { } public MonoGameSprite(TextureAtlasRegion region, int width, int height) : this(region, 0, 0, width, height) { } public MonoGameSprite(TextureAtlasRegion region, int x, int y, int width, int height) : base(region, x, y, width, height) { _tint = new MonoGameColor(_actualTint); if (region.getRotatedPackedHeight_FFE0B8F0() != region.getRegionHeight_0EE0D08D()) { rotate90_AA5A2C66(false); } setOriginCenter_EFE09FC0(); setBounds_C2EDAFC0(x, y, width, height); } public void set_615359F5(Sprite s) { setRegion_EBB2FEFB(s); setBounds_C2EDAFC0(s.getX_FFE0B8F0(), s.getY_FFE0B8F0(), s.getWidth_FFE0B8F0(), s.getHeight_FFE0B8F0()); setOrigin_0948E7C0(s.getOriginX_FFE0B8F0(), s.getOriginY_FFE0B8F0()); _90degRotation = ((MonoGameSprite)s)._90degRotation; setRotation_97413DCA(s.getRotation_FFE0B8F0()); setScale_0948E7C0(s.getScaleX_FFE0B8F0(), s.getScaleY_FFE0B8F0()); } public void setBounds_C2EDAFC0(float x, float y, float width, float height) { setSize_0948E7C0(width, height); } public void setSize_0948E7C0(float width, float height) { _width = width; _height = height; } public void setPosition_0948E7C0(float x, float y) { _x = x; _y = y; } public void setOriginBasedPosition_0948E7C0(float x, float y) { setPosition_0948E7C0(x - _originX, y - _originY); } public void setCenterX_97413DCA(float x) { _x = x - _width / 2; } public void setCenterY_97413DCA(float y) { _y = y - _height / 2; } public void setCenter_0948E7C0(float x, float y) { setCenterX_97413DCA(x); setCenterY_97413DCA(y); } public void translateX_97413DCA(float xAmount) { _x += xAmount; } public void translateY_97413DCA(float yAmount) { _y += yAmount; } public void translate_0948E7C0(float xAmount, float yAmount) { translateX_97413DCA(xAmount); translateY_97413DCA(yAmount); } public void setOrigin_0948E7C0(float originX, float originY) { _originX = originX; _originY = originY; } public void setOriginCenter_EFE09FC0() { setOrigin_0948E7C0(getRegionWidth_0EE0D08D() / 2f, getRegionHeight_0EE0D08D() / 2f); } public float getRotation_FFE0B8F0() { return _rotation; } public float getTotalRotation() { return _rotation + _90degRotation; } public void setRotation_97413DCA(float degrees) { _rotation = degrees % 360; } public void rotate_97413DCA(float degrees) { setRotation_97413DCA(getRotation_FFE0B8F0() + degrees); } public void rotate90_AA5A2C66(bool clockwise) { if (clockwise) { _90degRotation += 90; } else { _90degRotation -= 90; } } public void setScale_97413DCA(float scaleXY) { setScale_0948E7C0(scaleXY, scaleXY); } public void setScale_0948E7C0(float scaleX, float scaleY) { _scaleX = scaleX; _scaleY = scaleY; } public void scale_97413DCA(float amount) { _scaleX += amount; _scaleY += amount; } public float[] getVertices_9E7A8229() { throw new NotImplementedException(); //should not be needed using MonoGame SpriteBatch } public Rectangle getBoundingRectangle_A029B76C() { var rect = new Rectangle(); rect._init_C2EDAFC0(_x, _y, _width, _height); rect.setRotation_97413DCA(_90degRotation + _rotation); return rect; } public float getX_FFE0B8F0() { return _x; } public void setX_97413DCA(float x) { _x = x; } public float getY_FFE0B8F0() { return _y; } public void setY_97413DCA(float y) { _y = y; } public float getWidth_FFE0B8F0() { return _width; } public float getHeight_FFE0B8F0() { return _height; } public float getOriginX_FFE0B8F0() { return _originX; } public float getOriginY_FFE0B8F0() { return _originY; } public float getScaleX_FFE0B8F0() { return _scaleX; } public float getScaleY_FFE0B8F0() { return _scaleY; } public Color getTint_F0D7D9CF() { return _tint; } public void setTint_24D51C91(Color c) { var oldAlpha = getAlpha_FFE0B8F0(); _tint.set_F18CABCA(c); setAlpha_97413DCA(oldAlpha); } public float getAlpha_FFE0B8F0() { return _tint.getAAsFloat_FFE0B8F0(); } public void setAlpha_97413DCA(float alpha) { _tint.setA_97413DCA(alpha); _actualTint.PackedValue = ((MonoGameColor) _tint)._color.PackedValue; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.NetCore.Extensions; namespace System.Tests { public class EnvironmentTests : RemoteExecutorTestBase { [Fact] public void CurrentDirectory_Null_Path_Throws_ArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("value", () => Environment.CurrentDirectory = null); } [Fact] public void CurrentDirectory_Empty_Path_Throws_ArgumentException() { AssertExtensions.Throws<ArgumentException>("value", null, () => Environment.CurrentDirectory = string.Empty); } [Fact] public void CurrentDirectory_SetToNonExistentDirectory_ThrowsDirectoryNotFoundException() { Assert.Throws<DirectoryNotFoundException>(() => Environment.CurrentDirectory = GetTestFilePath()); } [Fact] public void CurrentDirectory_SetToValidOtherDirectory() { RemoteInvoke(() => { Environment.CurrentDirectory = TestDirectory; Assert.Equal(Directory.GetCurrentDirectory(), Environment.CurrentDirectory); if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { // On OSX, the temp directory /tmp/ is a symlink to /private/tmp, so setting the current // directory to a symlinked path will result in GetCurrentDirectory returning the absolute // path that followed the symlink. Assert.Equal(TestDirectory, Directory.GetCurrentDirectory()); } return SuccessExitCode; }).Dispose(); } [Fact] public void CurrentManagedThreadId_Idempotent() { Assert.Equal(Environment.CurrentManagedThreadId, Environment.CurrentManagedThreadId); } [Fact] public void CurrentManagedThreadId_DifferentForActiveThreads() { var ids = new HashSet<int>(); Barrier b = new Barrier(10); Task.WaitAll((from i in Enumerable.Range(0, b.ParticipantCount) select Task.Factory.StartNew(() => { b.SignalAndWait(); lock (ids) ids.Add(Environment.CurrentManagedThreadId); b.SignalAndWait(); }, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default)).ToArray()); Assert.Equal(b.ParticipantCount, ids.Count); } [Fact] public void HasShutdownStarted_FalseWhileExecuting() { Assert.False(Environment.HasShutdownStarted); } [Fact] public void Is64BitProcess_MatchesIntPtrSize() { Assert.Equal(IntPtr.Size == 8, Environment.Is64BitProcess); } [Fact] public void Is64BitOperatingSystem_TrueIf64BitProcess() { if (Environment.Is64BitProcess) { Assert.True(Environment.Is64BitOperatingSystem); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void Is64BitOperatingSystem_Unix_TrueIff64BitProcess() { Assert.Equal(Environment.Is64BitProcess, Environment.Is64BitOperatingSystem); } [Fact] public void OSVersion_Idempotent() { Assert.Same(Environment.OSVersion, Environment.OSVersion); } [Fact] public void OSVersion_MatchesPlatform() { PlatformID id = Environment.OSVersion.Platform; Assert.Equal( RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? PlatformID.Win32NT : PlatformID.Unix, id); } [Fact] public void OSVersion_ValidVersion() { Version version = Environment.OSVersion.Version; string versionString = Environment.OSVersion.VersionString; Assert.False(string.IsNullOrWhiteSpace(versionString), "Expected non-empty version string"); Assert.True(version.Major > 0); Assert.Contains(version.ToString(2), versionString); Assert.Contains(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "Windows" : "Unix", versionString); } [Fact] public void SystemPageSize_Valid() { int pageSize = Environment.SystemPageSize; Assert.Equal(pageSize, Environment.SystemPageSize); Assert.True(pageSize > 0, "Expected positive page size"); Assert.True((pageSize & (pageSize - 1)) == 0, "Expected power-of-2 page size"); } [Fact] public void UserInteractive_True() { Assert.True(Environment.UserInteractive); } [Fact] public void UserName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserName)); } [Fact] public void UserDomainName_Valid() { Assert.False(string.IsNullOrWhiteSpace(Environment.UserDomainName)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void UserDomainName_Unix_MatchesMachineName() { Assert.Equal(Environment.MachineName, Environment.UserDomainName); } [Fact] public void Version_MatchesFixedVersion() { Assert.Equal(new Version(4, 0, 30319, 42000), Environment.Version); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Uap)] // Throws InvalidOperationException in Uap as NtQuerySystemInformation Pinvoke is not available public void WorkingSet_Valid() { Assert.True(Environment.WorkingSet > 0, "Expected positive WorkingSet value"); } [Fact] [SkipOnTargetFramework(~TargetFrameworkMonikers.Uap)] public void WorkingSet_Valid_Uap() { Assert.Throws<PlatformNotSupportedException>(() => Environment.WorkingSet); } [Trait(XunitConstants.Category, XunitConstants.IgnoreForCI)] // fail fast crashes the process [OuterLoop] [Fact] [ActiveIssue("https://github.com/dotnet/corefx/issues/21404", TargetFrameworkMonikers.Uap)] public void FailFast_ExpectFailureExitCode() { using (Process p = RemoteInvoke(() => { Environment.FailFast("message"); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } using (Process p = RemoteInvoke(() => { Environment.FailFast("message", new Exception("uh oh")); return SuccessExitCode; }).Process) { p.WaitForExit(); Assert.NotEqual(SuccessExitCode, p.ExitCode); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment public void GetFolderPath_Unix_PersonalIsHomeAndUserProfile() { Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.Personal)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)); Assert.Equal(Environment.GetEnvironmentVariable("HOME"), Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); } [Fact] public void GetSystemDirectory() { if (PlatformDetection.IsWindowsNanoServer) { // https://github.com/dotnet/corefx/issues/19110 // On Windows Nano, ShGetKnownFolderPath currently doesn't give // the correct result for SystemDirectory. // Assert that it's wrong, so that if it's fixed, we don't forget to // enable this test for Nano. Assert.NotEqual(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); return; } Assert.Equal(Environment.GetFolderPath(Environment.SpecialFolder.System), Environment.SystemDirectory); } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.UserProfile, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.Personal, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.MyDocuments, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonApplicationData, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.CommonTemplates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Desktop, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.DesktopDirectory, Environment.SpecialFolderOption.DoNotVerify)] // Not set on Unix (amongst others) //[InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Templates, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyVideos, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyMusic, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.MyPictures, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.Fonts, Environment.SpecialFolderOption.DoNotVerify)] public void GetFolderPath_Unix_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } [Theory] [PlatformSpecific(TestPlatforms.OSX)] // Tests OS-specific environment [InlineData(Environment.SpecialFolder.Favorites, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.InternetCache, Environment.SpecialFolderOption.DoNotVerify)] [InlineData(Environment.SpecialFolder.ProgramFiles, Environment.SpecialFolderOption.None)] [InlineData(Environment.SpecialFolder.System, Environment.SpecialFolderOption.None)] public void GetFolderPath_OSX_NonEmptyFolderPaths(Environment.SpecialFolder folder, Environment.SpecialFolderOption option) { Assert.NotEmpty(Environment.GetFolderPath(folder, option)); if (option == Environment.SpecialFolderOption.None) { Assert.NotEmpty(Environment.GetFolderPath(folder)); } } // Requires recent RS3 builds and needs to run inside AppContainer [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater), nameof(PlatformDetection.IsInAppContainer))] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] public void GetFolderPath_UapExistAndAccessible(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); AssertDirectoryExists(knownFolder); } // Requires recent RS3 builds and needs to run inside AppContainer [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsWindows10Version16251OrGreater), nameof(PlatformDetection.IsInAppContainer))] [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonVideos)] // These are in the package folder [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] public void GetFolderPath_UapNotEmpty(Environment.SpecialFolder folder) { // The majority of the paths here cannot be accessed from an appcontainer string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); } private void AssertDirectoryExists(string path) { // Directory.Exists won't tell us if access was denied, etc. Invoking directly // to get diagnosable test results. FileAttributes attributes = GetFileAttributesW(path); if (attributes == (FileAttributes)(-1)) { int error = Marshal.GetLastWin32Error(); Assert.False(true, $"error {error} getting attributes for {path}"); } Assert.True((attributes & FileAttributes.Directory) == FileAttributes.Directory, $"not a directory: {path}"); } // The commented out folders aren't set on all systems. [ConditionalTheory(typeof(PlatformDetection), nameof(PlatformDetection.IsNotWindowsNanoServer))] // https://github.com/dotnet/corefx/issues/19110 [InlineData(Environment.SpecialFolder.ApplicationData)] [InlineData(Environment.SpecialFolder.CommonApplicationData)] [InlineData(Environment.SpecialFolder.LocalApplicationData)] [InlineData(Environment.SpecialFolder.Cookies)] [InlineData(Environment.SpecialFolder.Desktop)] [InlineData(Environment.SpecialFolder.Favorites)] [InlineData(Environment.SpecialFolder.History)] [InlineData(Environment.SpecialFolder.InternetCache)] [InlineData(Environment.SpecialFolder.Programs)] // [InlineData(Environment.SpecialFolder.MyComputer)] [InlineData(Environment.SpecialFolder.MyMusic)] [InlineData(Environment.SpecialFolder.MyPictures)] [InlineData(Environment.SpecialFolder.MyVideos)] [InlineData(Environment.SpecialFolder.Recent)] [InlineData(Environment.SpecialFolder.SendTo)] [InlineData(Environment.SpecialFolder.StartMenu)] [InlineData(Environment.SpecialFolder.Startup)] [InlineData(Environment.SpecialFolder.System)] [InlineData(Environment.SpecialFolder.Templates)] [InlineData(Environment.SpecialFolder.DesktopDirectory)] [InlineData(Environment.SpecialFolder.Personal)] [InlineData(Environment.SpecialFolder.ProgramFiles)] [InlineData(Environment.SpecialFolder.CommonProgramFiles)] [InlineData(Environment.SpecialFolder.AdminTools)] //[InlineData(Environment.SpecialFolder.CDBurning)] // Not available on Server Core [InlineData(Environment.SpecialFolder.CommonAdminTools)] [InlineData(Environment.SpecialFolder.CommonDocuments)] [InlineData(Environment.SpecialFolder.CommonMusic)] // [InlineData(Environment.SpecialFolder.CommonOemLinks)] [InlineData(Environment.SpecialFolder.CommonPictures)] [InlineData(Environment.SpecialFolder.CommonStartMenu)] [InlineData(Environment.SpecialFolder.CommonPrograms)] [InlineData(Environment.SpecialFolder.CommonStartup)] [InlineData(Environment.SpecialFolder.CommonDesktopDirectory)] [InlineData(Environment.SpecialFolder.CommonTemplates)] [InlineData(Environment.SpecialFolder.CommonVideos)] [InlineData(Environment.SpecialFolder.Fonts)] [InlineData(Environment.SpecialFolder.NetworkShortcuts)] // [InlineData(Environment.SpecialFolder.PrinterShortcuts)] [InlineData(Environment.SpecialFolder.UserProfile)] [InlineData(Environment.SpecialFolder.CommonProgramFilesX86)] [InlineData(Environment.SpecialFolder.ProgramFilesX86)] [InlineData(Environment.SpecialFolder.Resources)] // [InlineData(Environment.SpecialFolder.LocalizedResources)] [InlineData(Environment.SpecialFolder.SystemX86)] [InlineData(Environment.SpecialFolder.Windows)] [PlatformSpecific(TestPlatforms.Windows)] // Tests OS-specific environment [SkipOnTargetFramework(TargetFrameworkMonikers.Uap | TargetFrameworkMonikers.UapAot)] // Don't run on UAP public unsafe void GetFolderPath_Windows(Environment.SpecialFolder folder) { string knownFolder = Environment.GetFolderPath(folder); Assert.NotEmpty(knownFolder); // Call the older folder API to compare our results. char* buffer = stackalloc char[260]; SHGetFolderPathW(IntPtr.Zero, (int)folder, IntPtr.Zero, 0, buffer); string folderPath = new string(buffer); Assert.Equal(folderPath, knownFolder); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // Uses P/Invokes public void GetLogicalDrives_Unix_AtLeastOneIsRoot() { string[] drives = Environment.GetLogicalDrives(); Assert.NotNull(drives); Assert.True(drives.Length > 0, "Expected at least one drive"); Assert.All(drives, d => Assert.NotNull(d)); Assert.Contains(drives, d => d == "/"); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes public void GetLogicalDrives_Windows_MatchesExpectedLetters() { string[] drives = Environment.GetLogicalDrives(); uint mask = (uint)GetLogicalDrives(); var bits = new BitArray(new[] { (int)mask }); Assert.Equal(bits.Cast<bool>().Count(b => b), drives.Length); for (int bit = 0, d = 0; bit < bits.Length; bit++) { if (bits[bit]) { Assert.Contains((char)('A' + bit), drives[d++]); } } } [DllImport("kernel32.dll", SetLastError = true)] internal static extern int GetLogicalDrives(); [DllImport("shell32.dll", SetLastError = false, BestFitMapping = false, ExactSpelling = true)] internal static extern unsafe int SHGetFolderPathW( IntPtr hwndOwner, int nFolder, IntPtr hToken, uint dwFlags, char* pszPath); [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, ExactSpelling = true)] internal static extern FileAttributes GetFileAttributesW(string lpFileName); public static IEnumerable<object[]> EnvironmentVariableTargets { get { yield return new object[] { EnvironmentVariableTarget.Process }; yield return new object[] { EnvironmentVariableTarget.User }; yield return new object[] { EnvironmentVariableTarget.Machine }; } } } }
#if UNITY_WEBGL || UNITY_XBOXONE // -------------------------------------------------------------------------------------------------------------------- // <copyright file="SocketTcp.cs" company="Exit Games GmbH"> // Copyright (c) Exit Games GmbH. All rights reserved. // </copyright> // <summary> // Internal class to encapsulate the network i/o functionality for the realtime libary. // </summary> // <author>developer@exitgames.com</author> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections; using UnityEngine; using SupportClassPun = ExitGames.Client.Photon.SupportClass; namespace ExitGames.Client.Photon { /// <summary> /// Internal class to encapsulate the network i/o functionality for the realtime libary. /// </summary> public class SocketWebTcp : IPhotonSocket, IDisposable { private WebSocket sock; private readonly object syncer = new object(); public SocketWebTcp(PeerBase npeer) : base(npeer) { ServerAddress = npeer.ServerAddress; if (this.ReportDebugOfLevel(DebugLevel.INFO)) { Listener.DebugReturn(DebugLevel.INFO, "new SocketWebTcp() for Unity. Server: " + ServerAddress); } this.Protocol = ConnectionProtocol.WebSocket; this.PollReceive = false; } public void Dispose() { this.State = PhotonSocketState.Disconnecting; if (this.sock != null) { try { if (this.sock.Connected) this.sock.Close(); } catch (Exception ex) { this.EnqueueDebugReturn(DebugLevel.INFO, "Exception in Dispose(): " + ex); } } this.sock = null; this.State = PhotonSocketState.Disconnected; } GameObject websocketConnectionObject; public override bool Connect() { //bool baseOk = base.Connect(); //if (!baseOk) //{ // return false; //} State = PhotonSocketState.Connecting; if (this.websocketConnectionObject != null) { UnityEngine.Object.Destroy(this.websocketConnectionObject); } this.websocketConnectionObject = new GameObject("websocketConnectionObject"); MonoBehaviour mb = this.websocketConnectionObject.AddComponent<MonoBehaviourExt>(); this.websocketConnectionObject.hideFlags = HideFlags.HideInHierarchy; UnityEngine.Object.DontDestroyOnLoad(this.websocketConnectionObject); this.sock = new WebSocket(new Uri(ServerAddress)); this.sock.Connect(); mb.StartCoroutine(this.ReceiveLoop()); return true; } public override bool Disconnect() { if (ReportDebugOfLevel(DebugLevel.INFO)) { this.Listener.DebugReturn(DebugLevel.INFO, "SocketWebTcp.Disconnect()"); } State = PhotonSocketState.Disconnecting; lock (this.syncer) { if (this.sock != null) { try { this.sock.Close(); } catch (Exception ex) { this.Listener.DebugReturn(DebugLevel.ERROR, "Exception in Disconnect(): " + ex); } this.sock = null; } } if (this.websocketConnectionObject != null) { UnityEngine.Object.Destroy(this.websocketConnectionObject); } State = PhotonSocketState.Disconnected; return true; } /// <summary> /// used by TPeer* /// </summary> public override PhotonSocketError Send(byte[] data, int length) { if (this.State != PhotonSocketState.Connected) { return PhotonSocketError.Skipped; } try { if (this.ReportDebugOfLevel(DebugLevel.ALL)) { this.Listener.DebugReturn(DebugLevel.ALL, "Sending: " + SupportClassPun.ByteArrayToString(data)); } this.sock.Send(data); } catch (Exception e) { this.Listener.DebugReturn(DebugLevel.ERROR, "Cannot send to: " + this.ServerAddress + ". " + e.Message); HandleException(StatusCode.Exception); return PhotonSocketError.Exception; } return PhotonSocketError.Success; } public override PhotonSocketError Receive(out byte[] data) { data = null; return PhotonSocketError.NoData; } internal const int ALL_HEADER_BYTES = 9; internal const int TCP_HEADER_BYTES = 7; internal const int MSG_HEADER_BYTES = 2; public IEnumerator ReceiveLoop() { this.Listener.DebugReturn(DebugLevel.INFO, "ReceiveLoop()"); while (!this.sock.Connected && this.sock.Error == null) { yield return new WaitForSeconds(0.1f); // while connecting } if (this.sock.Error != null) { this.Listener.DebugReturn(DebugLevel.ERROR, "Exiting receive thread. Server: " + this.ServerAddress + ":" + this.ServerPort + " Error: " + this.sock.Error); this.HandleException(StatusCode.ExceptionOnConnect); } else { // connected if (this.ReportDebugOfLevel(DebugLevel.ALL)) { this.Listener.DebugReturn(DebugLevel.ALL, "Receiving by websocket. this.State: " + State); } State = PhotonSocketState.Connected; while (State == PhotonSocketState.Connected) { if (this.sock.Error != null) { this.Listener.DebugReturn(DebugLevel.ERROR, "Exiting receive thread (inside loop). Server: "+this.ServerAddress+":"+this.ServerPort+" Error: " + this.sock.Error); this.HandleException(StatusCode.ExceptionOnReceive); break; } else { byte[] inBuff = this.sock.Recv(); if (inBuff == null || inBuff.Length == 0) { yield return new WaitForSeconds(0.02f); // nothing received. wait a bit, try again continue; } if (this.ReportDebugOfLevel(DebugLevel.ALL)) { this.Listener.DebugReturn(DebugLevel.ALL, "TCP << " + inBuff.Length + " = " + SupportClassPun.ByteArrayToString(inBuff)); } if (inBuff.Length > 0) { try { HandleReceivedDatagram(inBuff, inBuff.Length, false); } catch (Exception e) { if (this.State != PhotonSocketState.Disconnecting && this.State != PhotonSocketState.Disconnected) { if (this.ReportDebugOfLevel(DebugLevel.ERROR)) { this.EnqueueDebugReturn(DebugLevel.ERROR, "Receive issue. State: " + this.State + ". Server: '" + this.ServerAddress + "' Exception: " + e); } this.HandleException(StatusCode.ExceptionOnReceive); } } } } } } this.Disconnect(); } } internal class MonoBehaviourExt : MonoBehaviour {} } #endif
// // Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // #if !NETSTANDARD1_3 namespace NLog.Targets { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.ComponentModel; using NLog.Common; using NLog.Internal; using NLog.Layouts; /// <summary> /// Writes log messages to the console. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Console-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Console/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Console/Simple/Example.cs" /> /// </example> [Target("Console")] public sealed class ConsoleTarget : TargetWithLayoutHeaderAndFooter { /// <summary> /// Should logging being paused/stopped because of the race condition bug in Console.Writeline? /// </summary> /// <remarks> /// Console.Out.Writeline / Console.Error.Writeline could throw 'IndexOutOfRangeException', which is a bug. /// See https://stackoverflow.com/questions/33915790/console-out-and-console-error-race-condition-error-in-a-windows-service-written /// and https://connect.microsoft.com/VisualStudio/feedback/details/2057284/console-out-probable-i-o-race-condition-issue-in-multi-threaded-windows-service /// /// Full error: /// Error during session close: System.IndexOutOfRangeException: Probable I/ O race condition detected while copying memory. /// The I/ O package is not thread safe by default. In multi threaded applications, /// a stream must be accessed in a thread-safe way, such as a thread - safe wrapper returned by TextReader's or /// TextWriter's Synchronized methods.This also applies to classes like StreamWriter and StreamReader. /// /// </remarks> private bool _pauseLogging; private readonly ReusableBufferCreator _reusableEncodingBuffer = new ReusableBufferCreator(16 * 1024); /// <summary> /// Gets or sets a value indicating whether to send the log messages to the standard error instead of the standard output. /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool Error { get; set; } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ /// <summary> /// The encoding for writing messages to the <see cref="Console"/>. /// </summary> /// <remarks>Has side effect</remarks> /// <docgen category='Console Options' order='10' /> public Encoding Encoding { get => ConsoleTargetHelper.GetConsoleOutputEncoding(_encoding, IsInitialized, _pauseLogging); set { if (ConsoleTargetHelper.SetConsoleOutputEncoding(value, IsInitialized, _pauseLogging)) _encoding = value; } } private Encoding _encoding; #endif /// <summary> /// Gets or sets a value indicating whether to auto-check if the console is available /// - Disables console writing if Environment.UserInteractive = False (Windows Service) /// - Disables console writing if Console Standard Input is not available (Non-Console-App) /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool DetectConsoleAvailable { get; set; } /// <summary> /// Gets or sets a value indicating whether to auto-flush after <see cref="Console.WriteLine()"/> /// </summary> /// <remarks> /// Normally not required as standard Console.Out will have <see cref="StreamWriter.AutoFlush"/> = true, but not when pipe to file /// </remarks> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool AutoFlush { get; set; } /// <summary> /// Gets or sets whether to enable batch writing using char[]-buffers, instead of using <see cref="Console.WriteLine()"/> /// </summary> /// <docgen category='Console Options' order='10' /> [DefaultValue(false)] public bool WriteBuffer { get; set; } = false; /// <summary> /// Initializes a new instance of the <see cref="ConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public ConsoleTarget() : base() { OptimizeBufferReuse = true; } /// <summary> /// /// Initializes a new instance of the <see cref="ConsoleTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public ConsoleTarget(string name) : this() { Name = name; } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { _pauseLogging = false; if (DetectConsoleAvailable) { string reason; _pauseLogging = !ConsoleTargetHelper.IsConsoleAvailable(out reason); if (_pauseLogging) { InternalLogger.Info("Console(Name={0}): Console has been detected as turned off. Disable DetectConsoleAvailable to skip detection. Reason: {1}", Name, reason); } } #if !SILVERLIGHT && !__IOS__ && !__ANDROID__ if (_encoding != null) ConsoleTargetHelper.SetConsoleOutputEncoding(_encoding, true, _pauseLogging); #endif base.InitializeTarget(); if (Header != null) { RenderToOutput(Header, LogEventInfo.CreateNullEvent()); } } /// <summary> /// Closes the target and releases any unmanaged resources. /// </summary> protected override void CloseTarget() { if (Footer != null) { RenderToOutput(Footer, LogEventInfo.CreateNullEvent()); } ExplicitConsoleFlush(); base.CloseTarget(); } /// <inheritdoc /> protected override void FlushAsync(AsyncContinuation asyncContinuation) { try { ExplicitConsoleFlush(); base.FlushAsync(asyncContinuation); } catch (Exception ex) { asyncContinuation(ex); } } private void ExplicitConsoleFlush() { if (!_pauseLogging && !AutoFlush) { var output = GetOutput(); output.Flush(); } } /// <summary> /// Writes the specified logging event to the Console.Out or /// Console.Error depending on the value of the Error flag. /// </summary> /// <param name="logEvent">The logging event.</param> /// <remarks> /// Note that the Error option is not supported on .NET Compact Framework. /// </remarks> protected override void Write(LogEventInfo logEvent) { if (_pauseLogging) { //check early for performance return; } RenderToOutput(Layout, logEvent); } /// <inheritdoc/> protected override void Write(IList<AsyncLogEventInfo> logEvents) { if (_pauseLogging) { return; } if (WriteBuffer) { WriteBufferToOutput(logEvents); } else { base.Write(logEvents); // Console.WriteLine } } /// <summary> /// Write to output /// </summary> private void RenderToOutput(Layout layout, LogEventInfo logEvent) { if (_pauseLogging) { return; } var output = GetOutput(); if (WriteBuffer) { WriteBufferToOutput(output, layout, logEvent); } else { WriteLineToOutput(output, RenderLogEvent(layout, logEvent)); } } private void WriteBufferToOutput(TextWriter output, Layout layout, LogEventInfo logEvent) { int targetBufferPosition = 0; using (var targetBuffer = _reusableEncodingBuffer.Allocate()) using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { RenderLogEventToWriteBuffer(output, layout, logEvent, targetBuilder.Result, targetBuffer.Result, ref targetBufferPosition); if (targetBufferPosition > 0) { WriteBufferToOutput(output, targetBuffer.Result, targetBufferPosition); } } } private void WriteBufferToOutput(IList<AsyncLogEventInfo> logEvents) { var output = GetOutput(); using (var targetBuffer = _reusableEncodingBuffer.Allocate()) using (var targetBuilder = ReusableLayoutBuilder.Allocate()) { int targetBufferPosition = 0; try { for (int i = 0; i < logEvents.Count; ++i) { targetBuilder.Result.ClearBuilder(); RenderLogEventToWriteBuffer(output, Layout, logEvents[i].LogEvent, targetBuilder.Result, targetBuffer.Result, ref targetBufferPosition); logEvents[i].Continuation(null); } } finally { if (targetBufferPosition > 0) { WriteBufferToOutput(output, targetBuffer.Result, targetBufferPosition); } } } } private void RenderLogEventToWriteBuffer(TextWriter output, Layout layout, LogEventInfo logEvent, StringBuilder targetBuilder, char[] targetBuffer, ref int targetBufferPosition) { int environmentNewLineLength = System.Environment.NewLine.Length; layout.RenderAppendBuilder(logEvent, targetBuilder); if (targetBuilder.Length > targetBuffer.Length - targetBufferPosition - environmentNewLineLength) { if (targetBufferPosition > 0) { WriteBufferToOutput(output, targetBuffer, targetBufferPosition); targetBufferPosition = 0; } if (targetBuilder.Length > targetBuffer.Length - environmentNewLineLength) { WriteLineToOutput(output, targetBuilder.ToString()); return; } } targetBuilder.Append(System.Environment.NewLine); targetBuilder.CopyToBuffer(targetBuffer, targetBufferPosition); targetBufferPosition += targetBuilder.Length; } private void WriteLineToOutput(TextWriter output, string message) { try { ConsoleTargetHelper.WriteLineThreadSafe(output, message, AutoFlush); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { //this is a bug and therefor stopping logging. For docs, see PauseLogging property _pauseLogging = true; InternalLogger.Warn(ex, "Console(Name={0}): {1} has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", Name, ex.GetType()); } } private void WriteBufferToOutput(TextWriter output, char[] buffer, int length) { try { ConsoleTargetHelper.WriteBufferThreadSafe(output, buffer, length, AutoFlush); } catch (Exception ex) when (ex is OverflowException || ex is IndexOutOfRangeException || ex is ArgumentOutOfRangeException) { //this is a bug and therefor stopping logging. For docs, see PauseLogging property _pauseLogging = true; InternalLogger.Warn(ex, "Console(Name={0}): {1} has been thrown and this is probably due to a race condition." + "Logging to the console will be paused. Enable by reloading the config or re-initialize the targets", Name, ex.GetType()); } } private TextWriter GetOutput() { return Error ? Console.Error : Console.Out; } } } #endif
using System.Collections; using UnityEngine.Events; namespace UnityEngine.UI.CoroutineTween { // Base interface for tweeners, // using an interface instead of // an abstract class as we want the // tweens to be structs. internal interface ITweenValue { void TweenValue(float floatPercentage); bool ignoreTimeScale { get; } float duration { get; } bool ValidTarget(); } // Color tween class, receives the // TweenValue callback and then sets // the value on the target. internal struct ColorTween : ITweenValue { public enum ColorTweenMode { All, RGB, Alpha } public class ColorTweenCallback : UnityEvent<Color> {} private ColorTweenCallback m_Target; private Color m_StartColor; private Color m_TargetColor; private ColorTweenMode m_TweenMode; private float m_Duration; private bool m_IgnoreTimeScale; public Color startColor { get { return m_StartColor; } set { m_StartColor = value; } } public Color targetColor { get { return m_TargetColor; } set { m_TargetColor = value; } } public ColorTweenMode tweenMode { get { return m_TweenMode; } set { m_TweenMode = value; } } public float duration { get { return m_Duration; } set { m_Duration = value; } } public bool ignoreTimeScale { get { return m_IgnoreTimeScale; } set { m_IgnoreTimeScale = value; } } public void TweenValue(float floatPercentage) { if (!ValidTarget()) return; var newColor = Color.Lerp(m_StartColor, m_TargetColor, floatPercentage); if (m_TweenMode == ColorTweenMode.Alpha) { newColor.r = m_StartColor.r; newColor.g = m_StartColor.g; newColor.b = m_StartColor.b; } else if (m_TweenMode == ColorTweenMode.RGB) { newColor.a = m_StartColor.a; } m_Target.Invoke(newColor); } public void AddOnChangedCallback(UnityAction<Color> callback) { if (m_Target == null) m_Target = new ColorTweenCallback(); m_Target.AddListener(callback); } public bool GetIgnoreTimescale() { return m_IgnoreTimeScale; } public float GetDuration() { return m_Duration; } public bool ValidTarget() { return m_Target != null; } } /* // Float tween class, receives the // TweenValue callback and then sets // the value on the target. public struct TweenFloat : ITweenValue { public UnityAction<float> target; public float startAlpha; public float targetAlpha; public float duriation; public bool ignoreTimeScale; public void TweenValue(float floatPercentage) { if (!ValidTarget()) return; var newColor = Mathf.Lerp (startAlpha, targetAlpha, floatPercentage); target.Invoke (newColor); } public bool GetIgnoreTimescale() { return ignoreTimeScale; } public float GetDuration() { return duriation; } public bool ValidTarget() { return target != null; } }*/ // Tween runner, executes the given tween. // The coroutine will live within the given // behaviour container. internal class TweenRunner<T> where T : struct, ITweenValue { protected MonoBehaviour m_CoroutineContainer; protected IEnumerator m_Tween; // utility function for starting the tween private static IEnumerator Start(T tweenInfo) { if (!tweenInfo.ValidTarget()) yield break; var elapsedTime = 0.0f; while (elapsedTime < tweenInfo.duration) { elapsedTime += tweenInfo.ignoreTimeScale ? Time.unscaledDeltaTime : Time.deltaTime; var percentage = Mathf.Clamp01(elapsedTime / tweenInfo.duration); tweenInfo.TweenValue(percentage); yield return null; } tweenInfo.TweenValue(1.0f); } public void Init(MonoBehaviour coroutineContainer) { m_CoroutineContainer = coroutineContainer; } public void StartTween(T info) { if (m_CoroutineContainer == null) { Debug.LogWarning("Coroutine container not configured... did you forget to call Init?"); return; } if (m_Tween != null) { m_CoroutineContainer.StopCoroutine(m_Tween); m_Tween = null; } if (!m_CoroutineContainer.gameObject.activeInHierarchy) { info.TweenValue(1.0f); return; } m_Tween = Start(info); m_CoroutineContainer.StartCoroutine(m_Tween); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Globalization; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; namespace System { public partial class Uri { // // All public ctors go through here // private void CreateThis(string uri, bool dontEscape, UriKind uriKind) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } _string = uri == null ? string.Empty : uri; if (dontEscape) _flags |= Flags.UserEscaped; ParsingError err = ParseScheme(_string, ref _flags, ref _syntax); UriFormatException e; InitializeUri(err, uriKind, out e); if (e != null) throw e; } private void InitializeUri(ParsingError err, UriKind uriKind, out UriFormatException e) { if (err == ParsingError.None) { if (IsImplicitFile) { // V1 compat // A relative Uri wins over implicit UNC path unless the UNC path is of the form "\\something" and // uriKind != Absolute if (NotAny(Flags.DosPath) && uriKind != UriKind.Absolute && (uriKind == UriKind.Relative || (_string.Length >= 2 && (_string[0] != '\\' || _string[1] != '\\')))) { _syntax = null; //make it be relative Uri _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otheriwse an absolute file Uri wins when it's of the form "\\something" } // // V1 compat issue // We should support relative Uris of the form c:\bla or c:/bla // else if (uriKind == UriKind.Relative && InFact(Flags.DosPath)) { _syntax = null; //make it be relative Uri _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri e = null; return; // Otheriwse an absolute file Uri wins when it's of the form "c:\something" } } } else if (err > ParsingError.LastRelativeUriOkErrIndex) { //This is a fatal error based solely on scheme name parsing _string = null; // make it be invalid Uri e = GetException(err); return; } bool hasUnicode = false; _iriParsing = (s_IriParsing && ((_syntax == null) || _syntax.InFact(UriSyntaxFlags.AllowIriParsing))); if (_iriParsing && (CheckForUnicode(_string) || CheckForEscapedUnreserved(_string))) { _flags |= Flags.HasUnicode; hasUnicode = true; // switch internal strings _originalUnicodeString = _string; // original string location changed } if (_syntax != null) { if (_syntax.IsSimple) { if ((err = PrivateParseMinimal()) != ParsingError.None) { if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { // RFC 3986 Section 5.4.2 - http:(relativeUri) may be considered a valid relative Uri. _syntax = null; // convert to relative uri e = null; _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } else e = GetException(err); } else if (uriKind == UriKind.Relative) { // Here we know that we can create an absolute Uri, but the user has requested only a relative one e = GetException(ParsingError.CannotCreateRelative); } else e = null; // will return from here if (_iriParsing && hasUnicode) { // In this scenario we need to parse the whole string EnsureParseRemaining(); } } else { // offer custom parser to create a parsing context _syntax = _syntax.InternalOnNewUri(); // incase they won't call us _flags |= Flags.UserDrivenParsing; // Ask a registered type to validate this uri _syntax.InternalValidate(this, out e); if (e != null) { // Can we still take it as a relative Uri? if (uriKind != UriKind.Absolute && err != ParsingError.None && err <= ParsingError.LastRelativeUriOkErrIndex) { _syntax = null; // convert it to relative e = null; _flags &= Flags.UserEscaped; // the only flag that makes sense for a relative uri } } else // e == null { if (err != ParsingError.None || InFact(Flags.ErrorOrParsingRecursion)) { // User parser took over on an invalid Uri SetUserDrivenParsing(); } else if (uriKind == UriKind.Relative) { // Here we know that custom parser can create an absolute Uri, but the user has requested only a // relative one e = GetException(ParsingError.CannotCreateRelative); } if (_iriParsing && hasUnicode) { // In this scenario we need to parse the whole string EnsureParseRemaining(); } } // will return from here } } // If we encountered any parsing errors that indicate this may be a relative Uri, // and we'll allow relative Uri's, then create one. else if (err != ParsingError.None && uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) { e = null; _flags &= (Flags.UserEscaped | Flags.HasUnicode); // the only flags that makes sense for a relative uri if (_iriParsing && hasUnicode) { // Iri'ze and then normalize relative uris _string = EscapeUnescapeIri(_originalUnicodeString, 0, _originalUnicodeString.Length, (UriComponents)0); } } else { _string = null; // make it be invalid Uri e = GetException(err); } } // // Unescapes entire string and checks if it has unicode chars // private bool CheckForUnicode(string data) { bool hasUnicode = false; char[] chars = new char[data.Length]; int count = 0; chars = UriHelper.UnescapeString(data, 0, data.Length, chars, ref count, c_DummyChar, c_DummyChar, c_DummyChar, UnescapeMode.Unescape | UnescapeMode.UnescapeAll, null, false); for (int i = 0; i < count; ++i) { if (chars[i] > '\x7f') { // Unicode hasUnicode = true; break; } } return hasUnicode; } // Does this string have any %6A sequences that are 3986 Unreserved characters? These should be un-escaped. private unsafe bool CheckForEscapedUnreserved(string data) { fixed (char* tempPtr = data) { for (int i = 0; i < data.Length - 2; ++i) { if (tempPtr[i] == '%' && IsHexDigit(tempPtr[i + 1]) && IsHexDigit(tempPtr[i + 2]) && tempPtr[i + 1] >= '0' && tempPtr[i + 1] <= '7') // max 0x7F { char ch = UriHelper.EscapedAscii(tempPtr[i + 1], tempPtr[i + 2]); if (ch != c_DummyChar && UriHelper.Is3986Unreserved(ch)) { return true; } } } } return false; } // // Returns true if the string represents a valid argument to the Uri ctor // If uriKind != AbsoluteUri then certain parsing erros are ignored but Uri usage is limited // public static bool TryCreate(string uriString, UriKind uriKind, out Uri result) { if ((object)uriString == null) { result = null; return false; } UriFormatException e = null; result = CreateHelper(uriString, false, uriKind, ref e); return (object)e == null && result != null; } public static bool TryCreate(Uri baseUri, string relativeUri, out Uri result) { Uri relativeLink; if (TryCreate(relativeUri, UriKind.RelativeOrAbsolute, out relativeLink)) { if (!relativeLink.IsAbsoluteUri) return TryCreate(baseUri, relativeLink, out result); result = relativeLink; return true; } result = null; return false; } public static bool TryCreate(Uri baseUri, Uri relativeUri, out Uri result) { result = null; //TODO: Work out the baseUri==null case if ((object)baseUri == null || (object)relativeUri == null) return false; if (baseUri.IsNotAbsoluteUri) return false; UriFormatException e; string newUriString = null; bool dontEscape; if (baseUri.Syntax.IsSimple) { dontEscape = relativeUri.UserEscaped; result = ResolveHelper(baseUri, relativeUri, ref newUriString, ref dontEscape, out e); } else { dontEscape = false; newUriString = baseUri.Syntax.InternalResolve(baseUri, relativeUri, out e); } if (e != null) return false; if ((object)result == null) result = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e); return (object)e == null && result != null && result.IsAbsoluteUri; } public string GetComponents(UriComponents components, UriFormat format) { if (((components & UriComponents.SerializationInfoString) != 0) && components != UriComponents.SerializationInfoString) throw new ArgumentOutOfRangeException("components", components, SR.net_uri_NotJustSerialization); if ((format & ~UriFormat.SafeUnescaped) != 0) throw new ArgumentOutOfRangeException("format"); if (IsNotAbsoluteUri) { if (components == UriComponents.SerializationInfoString) return GetRelativeSerializationString(format); else throw new InvalidOperationException(SR.net_uri_NotAbsolute); } if (Syntax.IsSimple) return GetComponentsHelper(components, format); return Syntax.InternalGetComponents(this, components, format); } // // This is for languages that do not support == != operators overloading // // Note that Uri.Equals will get an optimized path but is limited to true/fasle result only // public static int Compare(Uri uri1, Uri uri2, UriComponents partsToCompare, UriFormat compareFormat, StringComparison comparisonType) { if ((object)uri1 == null) { if (uri2 == null) return 0; // Equal return -1; // null < non-null } if ((object)uri2 == null) return 1; // non-null > null // a relative uri is always less than an absolute one if (!uri1.IsAbsoluteUri || !uri2.IsAbsoluteUri) return uri1.IsAbsoluteUri ? 1 : uri2.IsAbsoluteUri ? -1 : string.Compare(uri1.OriginalString, uri2.OriginalString, comparisonType); return string.Compare( uri1.GetParts(partsToCompare, compareFormat), uri2.GetParts(partsToCompare, compareFormat), comparisonType ); } public bool IsWellFormedOriginalString() { if (IsNotAbsoluteUri || Syntax.IsSimple) return InternalIsWellFormedOriginalString(); return Syntax.InternalIsWellFormedOriginalString(this); } // TODO: (perf) Making it to not create a Uri internally public static bool IsWellFormedUriString(string uriString, UriKind uriKind) { Uri result; if (!Uri.TryCreate(uriString, uriKind, out result)) return false; return result.IsWellFormedOriginalString(); } // // Internal stuff // // Returns false if OriginalString value // (1) is not correctly escaped as per URI spec excluding intl UNC name case // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file" // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file" // (4) or contains unescaped backslashes even if they will be treated // as forward slashes like http:\\host/path\file or file:\\\c:\path // internal unsafe bool InternalIsWellFormedOriginalString() { if (UserDrivenParsing) throw new InvalidOperationException(SR.Format(SR.net_uri_UserDrivenParsing, this.GetType().ToString())); fixed (char* str = _string) { ushort idx = 0; // // For a relative Uri we only care about escaping and backslashes // if (!IsAbsoluteUri) { // my:scheme/path?query is not well formed because the colon is ambiguous if (CheckForColonInFirstPathSegment(_string)) { return false; } return (CheckCanonical(str, ref idx, (ushort)_string.Length, c_EOL) & (Check.BackslashInPath | Check.EscapedCanonical)) == Check.EscapedCanonical; } // // (2) or is an absolute Uri that represents implicit file Uri "c:\dir\file" // if (IsImplicitFile) return false; //This will get all the offsets, a Host name will be checked separatelly below EnsureParseRemaining(); Flags nonCanonical = (_flags & (Flags.E_CannotDisplayCanonical | Flags.IriCanonical)); // User, Path, Query or Fragment may have some non escaped characters if (((nonCanonical & Flags.E_CannotDisplayCanonical & (Flags.E_UserNotCanonical | Flags.E_PathNotCanonical | Flags.E_QueryNotCanonical | Flags.E_FragmentNotCanonical)) != Flags.Zero) && (!_iriParsing || (_iriParsing && (((nonCanonical & Flags.E_UserNotCanonical) == 0) || ((nonCanonical & Flags.UserIriCanonical) == 0)) && (((nonCanonical & Flags.E_PathNotCanonical) == 0) || ((nonCanonical & Flags.PathIriCanonical) == 0)) && (((nonCanonical & Flags.E_QueryNotCanonical) == 0) || ((nonCanonical & Flags.QueryIriCanonical) == 0)) && (((nonCanonical & Flags.E_FragmentNotCanonical) == 0) || ((nonCanonical & Flags.FragmentIriCanonical) == 0))))) { return false; } // checking on scheme:\\ or file://// if (InFact(Flags.AuthorityFound)) { idx = (ushort)(_info.Offset.Scheme + _syntax.SchemeName.Length + 2); if (idx >= _info.Offset.User || _string[idx - 1] == '\\' || _string[idx] == '\\') return false; if (InFact(Flags.UncPath | Flags.DosPath)) { while (++idx < _info.Offset.User && (_string[idx] == '/' || _string[idx] == '\\')) return false; } } // (3) or is an absolute Uri that misses a slash before path "file://c:/dir/file" // Note that for this check to be more general we assert that if Path is non empty and if it requires a first slash // (which looks absent) then the method has to fail. // Today it's only possible for a Dos like path, i.e. file://c:/bla would fail below check. if (InFact(Flags.FirstSlashAbsent) && _info.Offset.Query > _info.Offset.Path) return false; // (4) or contains unescaped backslashes even if they will be treated // as forward slashes like http:\\host/path\file or file:\\\c:\path // Note we do not check for Flags.ShouldBeCompressed i.e. allow // /./ and alike as valid if (InFact(Flags.BackslashInPath)) return false; // Capturing a rare case like file:///c|/dir if (IsDosPath && _string[_info.Offset.Path + SecuredPathIndex - 1] == '|') return false; // // May need some real CPU processing to anwser the request // // // Check escaping for authority // // IPv6 hosts cannot be properly validated by CheckCannonical if ((_flags & Flags.CanonicalDnsHost) == 0 && HostType != Flags.IPv6HostType) { idx = _info.Offset.User; Check result = CheckCanonical(str, ref idx, (ushort)_info.Offset.Path, '/'); if (((result & (Check.ReservedFound | Check.BackslashInPath | Check.EscapedCanonical)) != Check.EscapedCanonical) && (!_iriParsing || (_iriParsing && ((result & (Check.DisplayCanonical | Check.FoundNonAscii | Check.NotIriCanonical)) != (Check.DisplayCanonical | Check.FoundNonAscii))))) { return false; } } // Want to ensure there are slashes after the scheme if ((_flags & (Flags.SchemeNotCanonical | Flags.AuthorityFound)) == (Flags.SchemeNotCanonical | Flags.AuthorityFound)) { idx = (ushort)_syntax.SchemeName.Length; while (str[idx++] != ':') ; if (idx + 1 >= _string.Length || str[idx] != '/' || str[idx + 1] != '/') return false; } } // // May be scheme, host, port or path need some canonicalization but still the uri string is found to be a // "well formed" one // return true; } public static string UnescapeDataString(string stringToUnescape) { if ((object)stringToUnescape == null) throw new ArgumentNullException("stringToUnescape"); if (stringToUnescape.Length == 0) return string.Empty; unsafe { fixed (char* pStr = stringToUnescape) { int position; for (position = 0; position < stringToUnescape.Length; ++position) if (pStr[position] == '%') break; if (position == stringToUnescape.Length) return stringToUnescape; UnescapeMode unescapeMode = UnescapeMode.Unescape | UnescapeMode.UnescapeAll; position = 0; char[] dest = new char[stringToUnescape.Length]; dest = UriHelper.UnescapeString(stringToUnescape, 0, stringToUnescape.Length, dest, ref position, c_DummyChar, c_DummyChar, c_DummyChar, unescapeMode, null, false); return new string(dest, 0, position); } } } // // Where stringToEscape is intented to be a completely unescaped URI string. // This method will escape any character that is not a reserved or unreserved character, including percent signs. // Note that EscapeUriString will also do not escape a '#' sign. // public static string EscapeUriString(string stringToEscape) { if ((object)stringToEscape == null) throw new ArgumentNullException("stringToEscape"); if (stringToEscape.Length == 0) return string.Empty; int position = 0; char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, true, c_DummyChar, c_DummyChar, c_DummyChar); if ((object)dest == null) return stringToEscape; return new string(dest, 0, position); } // // Where stringToEscape is intended to be URI data, but not an entire URI. // This method will escape any character that is not an unreserved character, including percent signs. // public static string EscapeDataString(string stringToEscape) { if ((object)stringToEscape == null) throw new ArgumentNullException("stringToEscape"); if (stringToEscape.Length == 0) return string.Empty; int position = 0; char[] dest = UriHelper.EscapeString(stringToEscape, 0, stringToEscape.Length, null, ref position, false, c_DummyChar, c_DummyChar, c_DummyChar); if (dest == null) return stringToEscape; return new string(dest, 0, position); } // // Cleans up the specified component according to Iri rules // a) Chars allowed by iri in a component are unescaped if found escaped // b) Bidi chars are stripped // // should be called only if IRI parsing is switched on internal unsafe string EscapeUnescapeIri(string input, int start, int end, UriComponents component) { fixed (char* pInput = input) { return IriHelper.EscapeUnescapeIri(pInput, start, end, component); } } // Should never be used except by the below method private Uri(Flags flags, UriParser uriParser, string uri) { _flags = flags; _syntax = uriParser; _string = uri; } // // a Uri.TryCreate() method goes through here. // internal static Uri CreateHelper(string uriString, bool dontEscape, UriKind uriKind, ref UriFormatException e) { // if (!Enum.IsDefined(typeof(UriKind), uriKind)) -- We currently believe that Enum.IsDefined() is too slow // to be used here. if ((int)uriKind < (int)UriKind.RelativeOrAbsolute || (int)uriKind > (int)UriKind.Relative) { throw new ArgumentException(SR.Format(SR.net_uri_InvalidUriKind, uriKind)); } UriParser syntax = null; Flags flags = Flags.Zero; ParsingError err = ParseScheme(uriString, ref flags, ref syntax); if (dontEscape) flags |= Flags.UserEscaped; // We won't use User factory for these errors if (err != ParsingError.None) { // If it looks as a relative Uri, custom factory is ignored if (uriKind != UriKind.Absolute && err <= ParsingError.LastRelativeUriOkErrIndex) return new Uri((flags & Flags.UserEscaped), null, uriString); return null; } // Cannot be relative Uri if came here Uri result = new Uri(flags, syntax, uriString); // Validate instance using ether built in or a user Parser try { result.InitializeUri(err, uriKind, out e); if (e == null) return result; return null; } catch (UriFormatException ee) { Debug.Assert(!syntax.IsSimple, "A UriPraser threw on InitializeAndValidate."); e = ee; // A precaution since custom Parser should never throw in this case. return null; } } // // Resolves into either baseUri or relativeUri according to conditions OR if not possible it uses newUriString // to return combined URI strings from both Uris // otherwise if e != null on output the operation has failed // internal static Uri ResolveHelper(Uri baseUri, Uri relativeUri, ref string newUriString, ref bool userEscaped, out UriFormatException e) { Debug.Assert(!baseUri.IsNotAbsoluteUri && !baseUri.UserDrivenParsing, "Uri::ResolveHelper()|baseUri is not Absolute or is controlled by User Parser."); e = null; string relativeStr = string.Empty; if ((object)relativeUri != null) { if (relativeUri.IsAbsoluteUri) return relativeUri; relativeStr = relativeUri.OriginalString; userEscaped = relativeUri.UserEscaped; } else relativeStr = string.Empty; // Here we can assert that passed "relativeUri" is indeed a relative one if (relativeStr.Length > 0 && (IsLWS(relativeStr[0]) || IsLWS(relativeStr[relativeStr.Length - 1]))) relativeStr = relativeStr.Trim(s_WSchars); if (relativeStr.Length == 0) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri, baseUri.UserEscaped ? UriFormat.UriEscaped : UriFormat.SafeUnescaped); return null; } // Check for a simple fragment in relative part if (relativeStr[0] == '#' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveFragment)) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.UriEscaped) + relativeStr; return null; } // Check for a simple query in relative part if (relativeStr[0] == '?' && !baseUri.IsImplicitFile && baseUri.Syntax.InFact(UriSyntaxFlags.MayHaveQuery)) { newUriString = baseUri.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Query & ~UriComponents.Fragment, UriFormat.UriEscaped) + relativeStr; return null; } // Check on the DOS path in the relative Uri (a special case) if (relativeStr.Length >= 3 && (relativeStr[1] == ':' || relativeStr[1] == '|') && IsAsciiLetter(relativeStr[0]) && (relativeStr[2] == '\\' || relativeStr[2] == '/')) { if (baseUri.IsImplicitFile) { // It could have file:/// prepended to the result but we want to keep it as *Implicit* File Uri newUriString = relativeStr; return null; } else if (baseUri.Syntax.InFact(UriSyntaxFlags.AllowDOSPath)) { // The scheme is not changed just the path gets replaced string prefix; if (baseUri.InFact(Flags.AuthorityFound)) prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":///" : "://"; else prefix = baseUri.Syntax.InFact(UriSyntaxFlags.PathIsRooted) ? ":/" : ":"; newUriString = baseUri.Scheme + prefix + relativeStr; return null; } // If we are here then input like "http://host/path/" + "C:\x" will produce the result http://host/path/c:/x } ParsingError err = GetCombinedString(baseUri, relativeStr, userEscaped, ref newUriString); if (err != ParsingError.None) { e = GetException(err); return null; } if ((object)newUriString == (object)baseUri._string) return baseUri; return null; } private unsafe string GetRelativeSerializationString(UriFormat format) { if (format == UriFormat.UriEscaped) { if (_string.Length == 0) return string.Empty; int position = 0; char[] dest = UriHelper.EscapeString(_string, 0, _string.Length, null, ref position, true, c_DummyChar, c_DummyChar, '%'); if ((object)dest == null) return _string; return new string(dest, 0, position); } else if (format == UriFormat.Unescaped) return UnescapeDataString(_string); else if (format == UriFormat.SafeUnescaped) { if (_string.Length == 0) return string.Empty; char[] dest = new char[_string.Length]; int position = 0; dest = UriHelper.UnescapeString(_string, 0, _string.Length, dest, ref position, c_DummyChar, c_DummyChar, c_DummyChar, UnescapeMode.EscapeUnescape, null, false); return new string(dest, 0, position); } else throw new ArgumentOutOfRangeException("format"); } // // UriParser helpers methods // internal string GetComponentsHelper(UriComponents uriComponents, UriFormat uriFormat) { if (uriComponents == UriComponents.Scheme) return _syntax.SchemeName; // A serialzation info is "almost" the same as AbsoluteUri except for IPv6 + ScopeID hostname case if ((uriComponents & UriComponents.SerializationInfoString) != 0) uriComponents |= UriComponents.AbsoluteUri; //This will get all the offsets, HostString will be created below if needed EnsureParseRemaining(); if ((uriComponents & UriComponents.NormalizedHost) != 0) { // Down the path we rely on Host to be ON for NormalizedHost uriComponents |= UriComponents.Host; } //Check to see if we need the host/authotity string if ((uriComponents & UriComponents.Host) != 0) EnsureHostString(true); //This, single Port request is always processed here if (uriComponents == UriComponents.Port || uriComponents == UriComponents.StrongPort) { if (((_flags & Flags.NotDefaultPort) != 0) || (uriComponents == UriComponents.StrongPort && _syntax.DefaultPort != UriParser.NoDefaultPort)) { // recreate string from the port value return _info.Offset.PortValue.ToString(CultureInfo.InvariantCulture); } return string.Empty; } if ((uriComponents & UriComponents.StrongPort) != 0) { // Down the path we rely on Port to be ON for StrongPort uriComponents |= UriComponents.Port; } //This request sometime is faster to process here if (uriComponents == UriComponents.Host && (uriFormat == UriFormat.UriEscaped || ((_flags & (Flags.HostNotCanonical | Flags.E_HostNotCanonical)) == 0))) { EnsureHostString(false); return _info.Host; } switch (uriFormat) { case UriFormat.UriEscaped: return GetEscapedParts(uriComponents); case V1ToStringUnescape: case UriFormat.SafeUnescaped: case UriFormat.Unescaped: return GetUnescapedParts(uriComponents, uriFormat); default: throw new ArgumentOutOfRangeException("uriFormat"); } } public bool IsBaseOf(Uri uri) { if ((object)uri == null) throw new ArgumentNullException("uri"); if (!IsAbsoluteUri) return false; if (Syntax.IsSimple) return IsBaseOfHelper(uri); return Syntax.InternalIsBaseOf(this, uri); } internal bool IsBaseOfHelper(Uri uriLink) { if (!IsAbsoluteUri || UserDrivenParsing) return false; if (!uriLink.IsAbsoluteUri) { //a relative uri could have quite tricky form, it's better to fix it now. string newUriString = null; UriFormatException e; bool dontEscape = false; uriLink = ResolveHelper(this, uriLink, ref newUriString, ref dontEscape, out e); if (e != null) return false; if ((object)uriLink == null) uriLink = CreateHelper(newUriString, dontEscape, UriKind.Absolute, ref e); if (e != null) return false; } if (Syntax.SchemeName != uriLink.Syntax.SchemeName) return false; // Canonicalize and test for substring match up to the last path slash string self = GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped); string other = uriLink.GetParts(UriComponents.AbsoluteUri & ~UriComponents.Fragment, UriFormat.SafeUnescaped); unsafe { fixed (char* selfPtr = self) { fixed (char* otherPtr = other) { return UriHelper.TestForSubPath(selfPtr, (ushort)self.Length, otherPtr, (ushort)other.Length, IsUncOrDosPath || uriLink.IsUncOrDosPath); } } } } // // Only a ctor time call // private void CreateThisFromUri(Uri otherUri) { // Clone the other guy but develop own UriInfo member _info = null; _flags = otherUri._flags; if (InFact(Flags.MinimalUriInfoSet)) { _flags &= ~(Flags.MinimalUriInfoSet | Flags.AllUriInfoSet | Flags.IndexMask); // Port / Path offset int portIndex = otherUri._info.Offset.Path; if (InFact(Flags.NotDefaultPort)) { // Find the start of the port. Account for non-canonical ports like :00123 while (otherUri._string[portIndex] != ':' && portIndex > otherUri._info.Offset.Host) { portIndex--; } if (otherUri._string[portIndex] != ':') { // Something wrong with the NotDefaultPort flag. Reset to path index Debug.Assert(false, "Uri failed to locate custom port at index: " + portIndex); portIndex = otherUri._info.Offset.Path; } } _flags |= (Flags)portIndex; // Port or path } _syntax = otherUri._syntax; _string = otherUri._string; _iriParsing = otherUri._iriParsing; if (otherUri.OriginalStringSwitched) { _originalUnicodeString = otherUri._originalUnicodeString; } if (otherUri.AllowIdn && (otherUri.InFact(Flags.IdnHost) || otherUri.InFact(Flags.UnicodeHost))) { _dnsSafeHost = otherUri._dnsSafeHost; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Linq; using System.Linq.Expressions; using System.Security.Principal; using System.Text; using System.Web; using System.Web.Mvc; using Cats.Areas.EarlyWarning.Controllers; using Cats.Areas.EarlyWarning.Models; using Cats.Helpers; using Cats.Models; using Cats.Models.Security; using Cats.Services.EarlyWarning; using Cats.Services.Security; using Cats.ViewModelBinder; using Kendo.Mvc.UI; using log4net; using Moq; using NUnit.Framework; namespace Cats.Tests.ControllersTests { [TestFixture] public class HRDControllerTests { #region SetUp / TearDown private HRDController _hrdController; [SetUp] public void Init() { var hrds = new List<HRD> { new HRD() { Year = 2013, Season = new Season() {Name = "Mehere", SeasonID = 1}, RationID = 1, HRDDetails = new List<HRDDetail>() { new HRDDetail() { DurationOfAssistance = 2, HRDDetailID = 1, NumberOfBeneficiaries = 300, WoredaID = 1, AdminUnit = new AdminUnit() { Name = "Woreda", AdminUnitID = 2, AdminUnit2 = new AdminUnit() { Name = "Zone", AdminUnitID = 3, AdminUnit2 = new AdminUnit() { Name = "Region", AdminUnitID = 6 } } } } } } }; var rationDetails = new List<RationDetail> { new RationDetail() {Amount = 1, CommodityID = 1, RationID = 1,Commodity=new Commodity(){CommodityID=1,Name="Creal"}} }; var hrdService = new Mock<IHRDService>(); hrdService.Setup( t => t.Get(It.IsAny<Expression<Func<HRD, bool>>>(), It.IsAny<Func<IQueryable<HRD>, IOrderedQueryable<HRD>>>(), It.IsAny<string>())).Returns(hrds); var adminUnitService = new Mock<IAdminUnitService>(); adminUnitService.Setup(t => t.GetRegions()).Returns(new List<AdminUnit>() {new AdminUnit() {AdminUnitID = 1, Name = "Region"}}); var rationService = new Mock<IRationService>(); var rationDetailService = new Mock<IRationDetailService>(); rationDetailService.Setup( t => t.Get(It.IsAny<Expression<Func<RationDetail, bool>>>(), It.IsAny<Func<IQueryable<RationDetail>, IOrderedQueryable<RationDetail>>>(), It.IsAny<string>())). Returns(rationDetails); var hrdDetailService = new Mock<IHRDDetailService>(); hrdDetailService.Setup( t => t.Get(It.IsAny<Expression<Func<HRDDetail, bool>>>(), It.IsAny<Func<IQueryable<HRDDetail>, IOrderedQueryable<HRDDetail>>>(), It.IsAny<string>())). Returns(hrds.First().HRDDetails); var commodityService = new Mock<ICommodityService>(); var needAssesmentDetailService = new Mock<INeedAssessmentDetailService>(); var needAssesmentHeaderService = new Mock<INeedAssessmentHeaderService>(); var workflowSatusService = new Mock<IWorkflowStatusService>(); var seasonService = new Mock<ISeasonService>(); var userAccountService = new Mock<IUserAccountService>(); var log = new Mock<ILog>(); var plan = new List<Plan> { new Plan {PlanID = 1,PlanName = "Mehere 2005",ProgramID = 1,StartDate = new DateTime(12/12/2006),EndDate = new DateTime(12/12/2007)}, new Plan {PlanID = 2,PlanName = "Belg 2005",ProgramID = 1,StartDate = new DateTime(12/12/2006),EndDate = new DateTime(12/12/2007)} }; var planService = new Mock<IPlanService>(); planService.Setup(m => m.GetAllPlan()).Returns(plan); var transactionService = new Mock<Cats.Services.Transaction.ITransactionService>(); userAccountService.Setup(t => t.GetUserInfo(It.IsAny<string>())).Returns(new UserInfo() { UserName = "x", DatePreference = "en", PreferedWeightMeasurment = "mt" }); var fakeContext = new Mock<HttpContextBase>(); var identity = new GenericIdentity("Admin"); var principal = new GenericPrincipal(identity, null); fakeContext.Setup(t => t.User).Returns(principal); var controllerContext = new Mock<ControllerContext>(); controllerContext.Setup(t => t.HttpContext).Returns(fakeContext.Object); _hrdController = new HRDController(adminUnitService.Object, hrdService.Object, rationService.Object, rationDetailService.Object, hrdDetailService.Object, commodityService.Object, needAssesmentDetailService.Object, needAssesmentHeaderService.Object, workflowSatusService.Object, seasonService.Object, userAccountService.Object, log.Object, planService.Object,null ); _hrdController.ControllerContext = controllerContext.Object; } [TearDown] public void Dispose() { _hrdController.Dispose(); } #endregion #region Tests [Test] public void ShouldDisplayCompareTwoHRD() { //ACT var result = _hrdController.Compare(); //Assert Assert.IsInstanceOf<ViewResult>(result); } [Test] public void ShouldCompareTwoHRD() { //ACT var request = new DataSourceRequest(); var result = _hrdController.Compare_HRD(request,1,1,1); //Assert Assert.IsInstanceOf<JsonResult>(result); } [Test] public void ShouldDisplayHRDDetail() { //act var result = _hrdController.Detail(1); // Assert.AreEqual(1, ((DataTable)((ViewResult)result).Model).Rows.Count); } [Test] public void ShouldDisplayHRDSummary() { //act var result = _hrdController.RegionalSummary(1); // Assert.AreEqual(1, ((DataTable)((ViewResult)result).Model).Rows.Count); } #endregion } }
using System; using System.Diagnostics; using HANDLE = System.IntPtr; using System.Text; namespace System.Data.SQLite { internal partial class Sqlite3 { /* ** 2006 June 7 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** This file contains code used to dynamically load extensions into ** the SQLite library. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908e ** ************************************************************************* */ #if !SQLITE_CORE //#define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */ const int SQLITE_CORE = 1; #endif //#include "sqlite3ext.h" //#include "sqliteInt.h" //#include <string.h> #if !SQLITE_OMIT_LOAD_EXTENSION /* ** Some API routines are omitted when various features are ** excluded from a build of SQLite. Substitute a NULL pointer ** for any missing APIs. */ #if !SQLITE_ENABLE_COLUMN_METADATA //# define sqlite3_column_database_name 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name 0 //# define sqlite3_column_origin_name16 0 //# define sqlite3_table_column_metadata 0 #endif #if SQLITE_OMIT_AUTHORIZATION //# define sqlite3_set_authorizer 0 #endif #if SQLITE_OMIT_UTF16 //# define sqlite3_bind_text16 0 //# define sqlite3_collation_needed16 0 //# define sqlite3_column_decltype16 0 //# define sqlite3_column_name16 0 //# define sqlite3_column_text16 0 //# define sqlite3_complete16 0 //# define sqlite3_create_collation16 0 //# define sqlite3_create_function16 0 //# define sqlite3_errmsg16 0 static string sqlite3_errmsg16(sqlite3 db) { return ""; } //# define sqlite3_open16 0 //# define sqlite3_prepare16 0 //# define sqlite3_prepare16_v2 0 //# define sqlite3_result_error16 0 //# define sqlite3_result_text16 0 static void sqlite3_result_text16(sqlite3_context pCtx, string z, int n, dxDel xDel) { } //# define sqlite3_result_text16be 0 //# define sqlite3_result_text16le 0 //# define sqlite3_value_text16 0 //# define sqlite3_value_text16be 0 //# define sqlite3_value_text16le 0 //# define sqlite3_column_database_name16 0 //# define sqlite3_column_table_name16 0 //# define sqlite3_column_origin_name16 0 #endif #if SQLITE_OMIT_COMPLETE //# define sqlite3_complete 0 //# define sqlite3_complete16 0 #endif #if SQLITE_OMIT_DECLTYPE //# define sqlite3_column_decltype16 0 //# define sqlite3_column_decltype 0 #endif #if SQLITE_OMIT_PROGRESS_CALLBACK //# define sqlite3_progress_handler 0 static void sqlite3_progress_handler (sqlite3 db, int nOps, dxProgress xProgress, object pArg){} #endif #if SQLITE_OMIT_VIRTUALTABLE //# define sqlite3_create_module 0 //# define sqlite3_create_module_v2 0 //# define sqlite3_declare_vtab 0 #endif #if SQLITE_OMIT_SHARED_CACHE //# define sqlite3_enable_shared_cache 0 #endif #if SQLITE_OMIT_TRACE //# define sqlite3_profile 0 //# define sqlite3_trace 0 #endif #if SQLITE_OMIT_GET_TABLE //# define //sqlite3_free_table 0 //# define sqlite3_get_table 0 static public int sqlite3_get_table( sqlite3 db, /* An open database */ string zSql, /* SQL to be evaluated */ ref string[] pazResult, /* Results of the query */ ref int pnRow, /* Number of result rows written here */ ref int pnColumn, /* Number of result columns written here */ ref string pzErrmsg /* Error msg written here */ ) { return 0; } #endif #if SQLITE_OMIT_INCRBLOB //#define sqlite3_bind_zeroblob 0 //#define sqlite3_blob_bytes 0 //#define sqlite3_blob_close 0 //#define sqlite3_blob_open 0 //#define sqlite3_blob_read 0 //#define sqlite3_blob_write 0 #endif /* ** The following structure contains pointers to all SQLite API routines. ** A pointer to this structure is passed into extensions when they are ** loaded so that the extension can make calls back into the SQLite ** library. ** ** When adding new APIs, add them to the bottom of this structure ** in order to preserve backwards compatibility. ** ** Extensions that use newer APIs should first call the ** sqlite3_libversion_number() to make sure that the API they ** intend to use is supported by the library. Extensions should ** also check to make sure that the pointer to the function is ** not NULL before calling it. */ public class sqlite3_api_routines { public sqlite3 context_db_handle; }; static sqlite3_api_routines sqlite3Apis = new sqlite3_api_routines(); //{ // sqlite3_aggregate_context, #if !SQLITE_OMIT_DEPRECATED / sqlite3_aggregate_count, #else // 0, #endif // sqlite3_bind_blob, // sqlite3_bind_double, // sqlite3_bind_int, // sqlite3_bind_int64, // sqlite3_bind_null, // sqlite3_bind_parameter_count, // sqlite3_bind_parameter_index, // sqlite3_bind_parameter_name, // sqlite3_bind_text, // sqlite3_bind_text16, // sqlite3_bind_value, // sqlite3_busy_handler, // sqlite3_busy_timeout, // sqlite3_changes, // sqlite3_close, // sqlite3_collation_needed, // sqlite3_collation_needed16, // sqlite3_column_blob, // sqlite3_column_bytes, // sqlite3_column_bytes16, // sqlite3_column_count, // sqlite3_column_database_name, // sqlite3_column_database_name16, // sqlite3_column_decltype, // sqlite3_column_decltype16, // sqlite3_column_double, // sqlite3_column_int, // sqlite3_column_int64, // sqlite3_column_name, // sqlite3_column_name16, // sqlite3_column_origin_name, // sqlite3_column_origin_name16, // sqlite3_column_table_name, // sqlite3_column_table_name16, // sqlite3_column_text, // sqlite3_column_text16, // sqlite3_column_type, // sqlite3_column_value, // sqlite3_commit_hook, // sqlite3_complete, // sqlite3_complete16, // sqlite3_create_collation, // sqlite3_create_collation16, // sqlite3_create_function, // sqlite3_create_function16, // sqlite3_create_module, // sqlite3_data_count, // sqlite3_db_handle, // sqlite3_declare_vtab, // sqlite3_enable_shared_cache, // sqlite3_errcode, // sqlite3_errmsg, // sqlite3_errmsg16, // sqlite3_exec, #if !SQLITE_OMIT_DEPRECATED //sqlite3_expired, #else //0, #endif // sqlite3_finalize, // //sqlite3_free, // //sqlite3_free_table, // sqlite3_get_autocommit, // sqlite3_get_auxdata, // sqlite3_get_table, // 0, /* Was sqlite3_global_recover(), but that function is deprecated */ // sqlite3_interrupt, // sqlite3_last_insert_rowid, // sqlite3_libversion, // sqlite3_libversion_number, // sqlite3_malloc, // sqlite3_mprintf, // sqlite3_open, // sqlite3_open16, // sqlite3_prepare, // sqlite3_prepare16, // sqlite3_profile, // sqlite3_progress_handler, // sqlite3_realloc, // sqlite3_reset, // sqlite3_result_blob, // sqlite3_result_double, // sqlite3_result_error, // sqlite3_result_error16, // sqlite3_result_int, // sqlite3_result_int64, // sqlite3_result_null, // sqlite3_result_text, // sqlite3_result_text16, // sqlite3_result_text16be, // sqlite3_result_text16le, // sqlite3_result_value, // sqlite3_rollback_hook, // sqlite3_set_authorizer, // sqlite3_set_auxdata, // sqlite3_snprintf, // sqlite3_step, // sqlite3_table_column_metadata, #if !SQLITE_OMIT_DEPRECATED //sqlite3_thread_cleanup, #else // 0, #endif // sqlite3_total_changes, // sqlite3_trace, #if !SQLITE_OMIT_DEPRECATED //sqlite3_transfer_bindings, #else // 0, #endif // sqlite3_update_hook, // sqlite3_user_data, // sqlite3_value_blob, // sqlite3_value_bytes, // sqlite3_value_bytes16, // sqlite3_value_double, // sqlite3_value_int, // sqlite3_value_int64, // sqlite3_value_numeric_type, // sqlite3_value_text, // sqlite3_value_text16, // sqlite3_value_text16be, // sqlite3_value_text16le, // sqlite3_value_type, // sqlite3_vmprintf, // /* // ** The original API set ends here. All extensions can call any // ** of the APIs above provided that the pointer is not NULL. But // ** before calling APIs that follow, extension should check the // ** sqlite3_libversion_number() to make sure they are dealing with // ** a library that is new enough to support that API. // ************************************************************************* // */ // sqlite3_overload_function, // /* // ** Added after 3.3.13 // */ // sqlite3_prepare_v2, // sqlite3_prepare16_v2, // sqlite3_clear_bindings, // /* // ** Added for 3.4.1 // */ // sqlite3_create_module_v2, // /* // ** Added for 3.5.0 // */ // sqlite3_bind_zeroblob, // sqlite3_blob_bytes, // sqlite3_blob_close, // sqlite3_blob_open, // sqlite3_blob_read, // sqlite3_blob_write, // sqlite3_create_collation_v2, // sqlite3_file_control, // sqlite3_memory_highwater, // sqlite3_memory_used, #if SQLITE_MUTEX_OMIT // 0, // 0, // 0, // 0, // 0, #else // sqlite3MutexAlloc, // sqlite3_mutex_enter, // sqlite3_mutex_free, // sqlite3_mutex_leave, // sqlite3_mutex_try, #endif // sqlite3_open_v2, // sqlite3_release_memory, // sqlite3_result_error_nomem, // sqlite3_result_error_toobig, // sqlite3_sleep, // sqlite3_soft_heap_limit, // sqlite3_vfs_find, // sqlite3_vfs_register, // sqlite3_vfs_unregister, // /* // ** Added for 3.5.8 // */ // sqlite3_threadsafe, // sqlite3_result_zeroblob, // sqlite3_result_error_code, // sqlite3_test_control, // sqlite3_randomness, // sqlite3_context_db_handle, // /* // ** Added for 3.6.0 // */ // sqlite3_extended_result_codes, // sqlite3_limit, // sqlite3_next_stmt, // sqlite3_sql, // sqlite3_status, // /* // ** Added for 3.7.4 // */ // sqlite3_backup_finish, // sqlite3_backup_init, // sqlite3_backup_pagecount, // sqlite3_backup_remaining, // sqlite3_backup_step, //#if !SQLITE_OMIT_COMPILEOPTION_DIAGS // sqlite3_compileoption_get, // sqlite3_compileoption_used, //#else // 0, // 0, //#endif // sqlite3_create_function_v2, // sqlite3_db_config, // sqlite3_db_mutex, // sqlite3_db_status, // sqlite3_extended_errcode, // sqlite3_log, // sqlite3_soft_heap_limit64, // sqlite3_sourceid, // sqlite3_stmt_status, // sqlite3_strnicmp, //#if SQLITE_ENABLE_UNLOCK_NOTIFY // sqlite3_unlock_notify, //#else // 0, //#endif //#if !SQLITE_OMIT_WAL // sqlite3_wal_autocheckpoint, // sqlite3_wal_checkpoint, // sqlite3_wal_hook, //#else // 0, // 0, // 0, //#endif //}; /* ** Attempt to load an SQLite extension library contained in the file ** zFile. The entry point is zProc. zProc may be 0 in which case a ** default entry point name (sqlite3_extension_init) is used. Use ** of the default name is recommended. ** ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong. ** ** If an error occurs and pzErrMsg is not 0, then fill pzErrMsg with ** error message text. The calling function should free this memory ** by calling sqlite3DbFree(db, ). */ static int sqlite3LoadExtension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { sqlite3_vfs pVfs = db.pVfs; HANDLE handle; dxInit xInit; //int (*xInit)(sqlite3*,char**,const sqlite3_api_routines); StringBuilder zErrmsg = new StringBuilder(100); //object aHandle; const int nMsg = 300; if (pzErrMsg != null) pzErrMsg = null; /* Ticket #1863. To avoid a creating security problems for older ** applications that relink against newer versions of SQLite, the ** ability to run load_extension is turned off by default. One ** must call sqlite3_enable_load_extension() to turn on extension ** loading. Otherwise you get the following error. */ if ((db.flags & SQLITE_LoadExtension) == 0) { //if( pzErrMsg != null){ pzErrMsg = sqlite3_mprintf("not authorized"); //} return SQLITE_ERROR; } if (zProc == null || zProc == "") { zProc = "sqlite3_extension_init"; } handle = sqlite3OsDlOpen(pVfs, zFile); if (handle == IntPtr.Zero) { // if( pzErrMsg ){ pzErrMsg = "";//*pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); //if( zErrmsg !=null){ sqlite3_snprintf(nMsg, zErrmsg, "unable to open shared library [%s]", zFile); sqlite3OsDlError(pVfs, nMsg - 1, zErrmsg.ToString()); return SQLITE_ERROR; } //xInit = (int()(sqlite3*,char**,const sqlite3_api_routines)) // sqlite3OsDlSym(pVfs, handle, zProc); xInit = (dxInit)sqlite3OsDlSym(pVfs, handle, ref zProc); Debugger.Break(); // TODO -- //if( xInit==0 ){ // if( pzErrMsg ){ // *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg); // if( zErrmsg ){ // sqlite3_snprintf(nMsg, zErrmsg, // "no entry point [%s] in shared library [%s]", zProc,zFile); // sqlite3OsDlError(pVfs, nMsg-1, zErrmsg); // } // sqlite3OsDlClose(pVfs, handle); // } // return SQLITE_ERROR; // }else if( xInit(db, ref zErrmsg, sqlite3Apis) ){ //// if( pzErrMsg !=null){ // pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg); // //} // sqlite3DbFree(db,ref zErrmsg); // sqlite3OsDlClose(pVfs, ref handle); // return SQLITE_ERROR; // } // /* Append the new shared library handle to the db.aExtension array. */ // aHandle = sqlite3DbMallocZero(db, sizeof(handle)*db.nExtension+1); // if( aHandle==null ){ // return SQLITE_NOMEM; // } // if( db.nExtension>0 ){ // memcpy(aHandle, db.aExtension, sizeof(handle)*(db.nExtension)); // } // sqlite3DbFree(db,ref db.aExtension); // db.aExtension = aHandle; // db.aExtension[db.nExtension++] = handle; return SQLITE_OK; } static public int sqlite3_load_extension( sqlite3 db, /* Load the extension into this database connection */ string zFile, /* Name of the shared library containing extension */ string zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */ ref string pzErrMsg /* Put error message here if not 0 */ ) { int rc; sqlite3_mutex_enter(db.mutex); rc = sqlite3LoadExtension(db, zFile, zProc, ref pzErrMsg); rc = sqlite3ApiExit(db, rc); sqlite3_mutex_leave(db.mutex); return rc; } /* ** Call this routine when the database connection is closing in order ** to clean up loaded extensions */ static void sqlite3CloseExtensions(sqlite3 db) { int i; Debug.Assert(sqlite3_mutex_held(db.mutex)); for (i = 0; i < db.nExtension; i++) { sqlite3OsDlClose(db.pVfs, (HANDLE)db.aExtension[i]); } sqlite3DbFree(db, ref db.aExtension); } /* ** Enable or disable extension loading. Extension loading is disabled by ** default so as not to open security holes in older applications. */ static public int sqlite3_enable_load_extension(sqlite3 db, int onoff) { sqlite3_mutex_enter(db.mutex); if (onoff != 0) { db.flags |= SQLITE_LoadExtension; } else { db.flags &= ~SQLITE_LoadExtension; } sqlite3_mutex_leave(db.mutex); return SQLITE_OK; } #endif //* SQLITE_OMIT_LOAD_EXTENSION */ /* ** The auto-extension code added regardless of whether or not extension ** loading is supported. We need a dummy sqlite3Apis pointer for that ** code if regular extension loading is not available. This is that ** dummy pointer. */ #if SQLITE_OMIT_LOAD_EXTENSION const sqlite3_api_routines sqlite3Apis = null; #endif /* ** The following object holds the list of automatically loaded ** extensions. ** ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER ** mutex must be held while accessing this list. */ //typedef struct sqlite3AutoExtList sqlite3AutoExtList; public class sqlite3AutoExtList { public int nExt = 0; /* Number of entries in aExt[] */ public dxInit[] aExt = null; /* Pointers to the extension init functions */ public sqlite3AutoExtList(int nExt, dxInit[] aExt) { this.nExt = nExt; this.aExt = aExt; } } static sqlite3AutoExtList sqlite3Autoext = new sqlite3AutoExtList(0, null); /* The "wsdAutoext" macro will resolve to the autoextension ** state vector. If writable static data is unsupported on the target, ** we have to locate the state vector at run-time. In the more common ** case where writable static data is supported, wsdStat can refer directly ** to the "sqlite3Autoext" state vector declared above. */ #if SQLITE_OMIT_WSD //# define wsdAutoextInit \ sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext) //# define wsdAutoext x[0] #else //# define wsdAutoextInit static void wsdAutoextInit() { } //# define wsdAutoext sqlite3Autoext static sqlite3AutoExtList wsdAutoext = sqlite3Autoext; #endif /* ** Register a statically linked extension that is automatically ** loaded by every new database connection. */ static int sqlite3_auto_extension(dxInit xInit) { int rc = SQLITE_OK; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if (rc != 0) { return rc; } else #endif { int i; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit(); sqlite3_mutex_enter(mutex); for (i = 0; i < wsdAutoext.nExt; i++) { if (wsdAutoext.aExt[i] == xInit) break; } //if( i==wsdAutoext.nExt ){ // int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]); // void **aNew; // aNew = sqlite3_realloc(wsdAutoext.aExt, nByte); // if( aNew==0 ){ // rc = SQLITE_NOMEM; // }else{ Array.Resize(ref wsdAutoext.aExt, wsdAutoext.nExt + 1);// wsdAutoext.aExt = aNew; wsdAutoext.aExt[wsdAutoext.nExt] = xInit; wsdAutoext.nExt++; //} sqlite3_mutex_leave(mutex); Debug.Assert((rc & 0xff) == rc); return rc; } } /* ** Reset the automatic extension loading mechanism. */ static void sqlite3_reset_auto_extension() { #if !SQLITE_OMIT_AUTOINIT if (sqlite3_initialize() == SQLITE_OK) #endif { #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif wsdAutoextInit(); sqlite3_mutex_enter(mutex); #if SQLITE_OMIT_WSD //sqlite3_free( ref wsdAutoext.aExt ); wsdAutoext.aExt = null; wsdAutoext.nExt = 0; #else //sqlite3_free( ref sqlite3Autoext.aExt ); sqlite3Autoext.aExt = null; sqlite3Autoext.nExt = 0; #endif sqlite3_mutex_leave(mutex); } } /* ** Load all automatic extensions. ** ** If anything goes wrong, set an error in the database connection. */ static void sqlite3AutoLoadExtensions(sqlite3 db) { int i; bool go = true; dxInit xInit;//)(sqlite3*,char**,const sqlite3_api_routines); wsdAutoextInit(); #if SQLITE_OMIT_WSD if ( wsdAutoext.nExt == 0 ) #else if (sqlite3Autoext.nExt == 0) #endif { /* Common case: early out without every having to acquire a mutex */ return; } for (i = 0; go; i++) { string zErrmsg = ""; #if SQLITE_THREADSAFE sqlite3_mutex mutex = sqlite3MutexAlloc( SQLITE_MUTEX_STATIC_MASTER ); #else sqlite3_mutex mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); #endif sqlite3_mutex_enter(mutex); if (i >= wsdAutoext.nExt) { xInit = null; go = false; } else { xInit = (dxInit) wsdAutoext.aExt[i]; } sqlite3_mutex_leave(mutex); zErrmsg = ""; if (xInit != null && xInit(db, ref zErrmsg, (sqlite3_api_routines)sqlite3Apis) != 0) { sqlite3Error(db, SQLITE_ERROR, "automatic extension loading failed: %s", zErrmsg); go = false; } sqlite3DbFree(db, ref zErrmsg); } } } }
using PlayFab; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; public class PlayerUIEffectsController : MonoBehaviour { public TweenPos shaker; public float defaultShakeTime = .333f; public bool isShaking = false; public PlayerActionBarController ActionBar; public PlayerEncounterInputController EncounterBar; public CalloutController playerAction; public GameplayController gameplayController; // UI ELEMENTS public Image CreepEncountersImage; public Text CreepEncountersText; public Image HeroEncountersImage; public Text HeroEncountersText; public Image GoldCollectedImage; public Text GoldCollecteText; public Image ItemsCollectedImage; public Text ItemsCollectedText; public FillBarController LifeBar; public FillBarController ManaBar; public Text PlayerLevel; public Text PlayerName; public Image PlayerIcon; public Text LivesCount; private int pendingValue = 0; void OnEnable() { GameplayController.OnGameplayEvent += OnGameplayEventReceived; } void OnDisable() { GameplayController.OnGameplayEvent -= OnGameplayEventReceived; } void OnGameplayEventReceived(string message, PF_GamePlay.GameplayEventTypes type) { if (type == PF_GamePlay.GameplayEventTypes.IntroQuest) { ActionBar.UpdateSpellBar(); Init(); } if (type == PF_GamePlay.GameplayEventTypes.IntroEncounter) StartCoroutine(PF_GamePlay.Wait(.5f, () => { TransitionEncounterBarIn(); })); if (type == PF_GamePlay.GameplayEventTypes.PlayerTurnBegins) TransitionActionBarIn(); } public void Init() { UpdateQuestStats(); LifeBar.maxValue = PF_PlayerData.activeCharacter.PlayerVitals.Health; StartCoroutine(LifeBar.UpdateBar(PF_PlayerData.activeCharacter.PlayerVitals.Health, true)); } public void TakeDamage(int dmg) { pendingValue = dmg; RequestShake(defaultShakeTime, PF_GamePlay.ShakeEffects.DecreaseHealth); PF_PlayerData.activeCharacter.PlayerVitals.Health -= dmg; } public void Callout(Sprite sprite, string message, UnityAction callback) { TransitionActionBarOut(); playerAction.actionIcon.overrideSprite = sprite; playerAction.actionText.text = message; playerAction.CastSpell(callback); } public void RequestShake(float seconds, PF_GamePlay.ShakeEffects effect) { if (!isShaking) { shaker.enabled = true; StartCoroutine(Shake(seconds, effect)); } } public void StartEncounterInput(PF_GamePlay.PlayerEncounterInputs input) { switch (input) { case PF_GamePlay.PlayerEncounterInputs.Attack: TransitionEncounterBarOut(() => { TransitionActionBarIn(); }); break; case PF_GamePlay.PlayerEncounterInputs.UseItem: UseItem(); break; case PF_GamePlay.PlayerEncounterInputs.Evade: TransitionActionBarOut(); // this causes a bug on boss types (cant evade) (should remove this option on un-evadable encounters) gameplayController.turnController.Evade(); break; case PF_GamePlay.PlayerEncounterInputs.ViewStore: string storeId; gameplayController.turnController.currentEncounter.Data.EncounterActions.TryGetValue(GlobalStrings.ENCOUNTER_STORE, out storeId); if (!string.IsNullOrEmpty(storeId)) DialogCanvasController.RequestStore(storeId); else Debug.LogError("No store found for merchant"); break; case PF_GamePlay.PlayerEncounterInputs.Rescue: gameplayController.turnController.CompleteEncounter(); break; } } public void UpdateQuestStats() { if (PF_GamePlay.QuestProgress != null) { CreepEncountersText.text = string.Format("{0} / {1}", PF_GamePlay.QuestProgress.CreepEncounters, PF_GamePlay.QuestProgress.CreepEncounters > 0 ? PF_GamePlay.encounters.Count + PF_GamePlay.QuestProgress.CreepEncounters - 1 : PF_GamePlay.encounters.Count); GoldCollecteText.text = string.Format("x{0:n0}", PF_GamePlay.QuestProgress.GoldCollected); ItemsCollectedText.text = "x" + PF_GamePlay.QuestProgress.ItemsFound.Count; HeroEncountersText.text = "x" + PF_GamePlay.QuestProgress.HeroRescues; } if (PF_PlayerData.activeCharacter != null) { PlayerIcon.overrideSprite = GameController.Instance.iconManager.GetIconById(PF_PlayerData.activeCharacter.baseClass.Icon, IconManager.IconTypes.Class); LivesCount.text = "" + PF_PlayerData.virtualCurrency[GlobalStrings.HEART_CURRENCY]; PlayerLevel.text = "" + PF_PlayerData.activeCharacter.characterData.CharacterLevel; PlayerName.text = PF_PlayerData.activeCharacter.characterDetails.CharacterName; } } public void TransitionEncounterBarIn(UnityAction cb = null) { if (cb != null) cb(); } public void TransitionEncounterBarOut(UnityAction cb = null) { if (cb != null) cb(); } public void TransitionActionBarIn(UnityAction cb = null) { ActionBar.FleeButton.interactable = gameplayController.turnController.currentEncounter.Data.EncounterType != EncounterTypes.BossCreep; var txt = ActionBar.UseItemButton.GetComponentInChildren<Text>(); var img = ActionBar.UseItemButton.GetComponent<Image>(); ActionBar.UseItemButton.interactable = true; if (gameplayController.turnController.currentEncounter.Data.EncounterType == EncounterTypes.Store) { // open store txt.text = "View Store"; img.color = Color.green; ActionBar.UseItemButton.onClick.RemoveAllListeners(); ActionBar.UseItemButton.onClick.AddListener(() => { StartEncounterInput(PF_GamePlay.PlayerEncounterInputs.ViewStore); }); } else if (gameplayController.turnController.currentEncounter.Data.EncounterType == EncounterTypes.Hero) { // rescue txt.text = "Rescue"; img.color = Color.magenta; ActionBar.UseItemButton.onClick.RemoveAllListeners(); ActionBar.UseItemButton.onClick.AddListener(() => { StartEncounterInput(PF_GamePlay.PlayerEncounterInputs.Rescue); }); } else { // use item txt.text = "Use Item"; img.color = Color.blue; ActionBar.UseItemButton.onClick.RemoveAllListeners(); ActionBar.UseItemButton.onClick.AddListener(() => { StartEncounterInput(PF_GamePlay.PlayerEncounterInputs.UseItem); }); } var isCreep = gameplayController.turnController.currentEncounter.Data.EncounterType.ToString().Contains("Creep"); ActionBar.Spell1Button.SpellButton.interactable = !ActionBar.Spell1Button.isLocked && !ActionBar.Spell1Button.isOnCD && isCreep; ActionBar.Spell2Button.SpellButton.interactable = !ActionBar.Spell2Button.isLocked && !ActionBar.Spell2Button.isOnCD && isCreep; ActionBar.Spell3Button.SpellButton.interactable = !ActionBar.Spell3Button.isLocked && !ActionBar.Spell3Button.isOnCD && isCreep; } public void TransitionActionBarOut(UnityAction cb = null) { ActionBar.Spell1Button.SpellButton.interactable = false; ActionBar.Spell2Button.SpellButton.interactable = false; ActionBar.Spell3Button.SpellButton.interactable = false; ActionBar.FleeButton.interactable = false; ActionBar.UseItemButton.interactable = false; } IEnumerator Shake(float seconds, PF_GamePlay.ShakeEffects effect = PF_GamePlay.ShakeEffects.None) { yield return new WaitForSeconds(seconds); shaker.ResetToBeginning(); isShaking = false; shaker.enabled = false; if (effect == PF_GamePlay.ShakeEffects.DecreaseHealth) { var remainingHp = LifeBar.currentValue - pendingValue; yield return StartCoroutine(LifeBar.UpdateBar(remainingHp)); if (remainingHp > 0) StartCoroutine(PF_GamePlay.Wait(1.0f, () => { GameplayController.RaiseGameplayEvent(GlobalStrings.ENEMY_TURN_END_EVENT, PF_GamePlay.GameplayEventTypes.EnemyTurnEnds); })); else GameplayController.RaiseGameplayEvent(GlobalStrings.OUTRO_PLAYER_DEATH_EVENT, PF_GamePlay.GameplayEventTypes.OutroEncounter); } else if (effect == PF_GamePlay.ShakeEffects.IncreaseHealth) { var remainingHp = LifeBar.currentValue + pendingValue; yield return StartCoroutine(LifeBar.UpdateBar(remainingHp)); StartCoroutine(PF_GamePlay.Wait(.5f, () => { GameplayController.RaiseGameplayEvent(GlobalStrings.PLAYER_TURN_END_EVENT, PF_GamePlay.GameplayEventTypes.PlayerTurnEnds); })); } else if (effect == PF_GamePlay.ShakeEffects.DecreaseMana) { StartCoroutine(ManaBar.UpdateBar(ManaBar.currentValue - pendingValue)); } else if (effect == PF_GamePlay.ShakeEffects.IncreaseMana) { StartCoroutine(ManaBar.UpdateBar(ManaBar.currentValue + pendingValue)); } pendingValue = 0; } private void UseCombatItem(string item) { var JsonUtil = PluginManager.GetPlugin<ISerializerPlugin>(PluginContract.PlayFab_Serializer); Debug.Log("Using " + item); InventoryCategory obj; if (!PF_PlayerData.inventoryByCategory.TryGetValue(item, out obj) || obj.count == 0) return; var attributes = JsonUtil.DeserializeObject<Dictionary<string, string>>(obj.catalogRef.CustomData); if (!attributes.ContainsKey("modifies") || !attributes.ContainsKey("modifyPercent") || !attributes.ContainsKey("target") || !string.Equals(attributes["target"], "self")) return; // item effect applies to the player var mod = attributes["modifies"]; var modPercent = float.Parse(attributes["modifyPercent"]); switch (mod) { case "HP": pendingValue = Mathf.CeilToInt(LifeBar.maxValue*modPercent); PF_PlayerData.activeCharacter.PlayerVitals.Health += pendingValue; RequestShake(defaultShakeTime, PF_GamePlay.ShakeEffects.IncreaseHealth); break; } gameplayController.DecrementPlayerCDs(); PF_GamePlay.ConsumeItem(obj.inventory[0].ItemInstanceId); PF_GamePlay.QuestProgress.ItemsUsed++; } public void UseItem() { DialogCanvasController.RequestInventoryPrompt(UseCombatItem, DialogCanvasController.InventoryFilters.UsableInCombat); } }
using System; using System.Reactive; using System.Reactive.Subjects; using Moq; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Layout; using Avalonia.Platform; using Avalonia.Rendering; using Avalonia.Styling; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class WindowBaseTests { [Fact] public void Activate_Should_Call_Impl_Activate() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var impl = new Mock<IWindowBaseImpl>(); var target = new TestWindowBase(impl.Object); target.Activate(); impl.Verify(x => x.Activate()); } } [Fact] public void Impl_Activate_Should_Call_Raise_Activated_Event() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var impl = new Mock<IWindowBaseImpl>(); impl.SetupAllProperties(); bool raised = false; var target = new TestWindowBase(impl.Object); target.Activated += (s, e) => raised = true; impl.Object.Activated(); Assert.True(raised); } } [Fact] public void Impl_Deactivate_Should_Call_Raise_Deativated_Event() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var impl = new Mock<IWindowBaseImpl>(); impl.SetupAllProperties(); bool raised = false; var target = new TestWindowBase(impl.Object); target.Deactivated += (s, e) => raised = true; impl.Object.Deactivated(); Assert.True(raised); } } [Fact] public void IsVisible_Should_Initially_Be_False() { using (UnitTestApplication.Start(TestServices.MockWindowingPlatform)) { var target = new TestWindowBase(); Assert.False(target.IsVisible); } } [Fact] public void IsVisible_Should_Be_True_After_Show() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new TestWindowBase(); target.Show(); Assert.True(target.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_Atfer_Hide() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new TestWindowBase(); target.Show(); target.Hide(); Assert.False(target.IsVisible); } } [Fact] public void IsVisible_Should_Be_False_Atfer_Impl_Signals_Close() { var windowImpl = new Mock<IPopupImpl>(); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); windowImpl.SetupProperty(x => x.Closed); using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new TestWindowBase(windowImpl.Object); target.Show(); windowImpl.Object.Closed(); Assert.False(target.IsVisible); } } [Fact] public void Setting_IsVisible_True_Shows_Window() { var windowImpl = new Mock<IPopupImpl>(); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new TestWindowBase(windowImpl.Object); target.IsVisible = true; windowImpl.Verify(x => x.Show(true, false)); } } [Fact] public void Setting_IsVisible_False_Hides_Window() { var windowImpl = new Mock<IPopupImpl>(); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new TestWindowBase(windowImpl.Object); target.Show(); target.IsVisible = false; windowImpl.Verify(x => x.Hide()); } } [Fact] public void Showing_Should_Start_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new TestWindowBase(renderer.Object); target.Show(); renderer.Verify(x => x.Start(), Times.Once); } } [Fact] public void Showing_Should_Raise_Opened() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var target = new TestWindowBase(); var raised = false; target.Opened += (s, e) => raised = true; target.Show(); Assert.True(raised); } } [Fact] public void Hiding_Should_Stop_Renderer() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var target = new TestWindowBase(renderer.Object); target.Show(); target.Hide(); renderer.Verify(x => x.Stop(), Times.Once); } } [Fact] public void Renderer_Should_Be_Disposed_When_Impl_Signals_Close() { using (UnitTestApplication.Start(TestServices.StyledWindow)) { var renderer = new Mock<IRenderer>(); var windowImpl = new Mock<IPopupImpl>(); windowImpl.Setup(x => x.DesktopScaling).Returns(1); windowImpl.Setup(x => x.RenderScaling).Returns(1); windowImpl.SetupProperty(x => x.Closed); windowImpl.Setup(x => x.CreateRenderer(It.IsAny<IRenderRoot>())).Returns(renderer.Object); var target = new TestWindowBase(windowImpl.Object); target.Show(); windowImpl.Object.Closed(); renderer.Verify(x => x.Dispose(), Times.Once); } } private FuncControlTemplate<TestWindowBase> CreateTemplate() { return new FuncControlTemplate<TestWindowBase>((x, scope) => new ContentPresenter { Name = "PART_ContentPresenter", [!ContentPresenter.ContentProperty] = x[!ContentControl.ContentProperty], }.RegisterInNameScope(scope)); } private class TestWindowBase : WindowBase { public bool IsClosed { get; private set; } public TestWindowBase(IRenderer renderer = null) : base(Mock.Of<IWindowBaseImpl>(x => x.RenderScaling == 1 && x.CreateRenderer(It.IsAny<IRenderRoot>()) == renderer)) { } public TestWindowBase(IWindowBaseImpl impl) : base(impl) { } } } }
using ExperimentalTools.Tests.Infrastructure.Refactoring; using System.Collections.Generic; using System.Threading.Tasks; using Xunit.Abstractions; using Microsoft.CodeAnalysis.CodeRefactorings; using ExperimentalTools.Roslyn.Features.Braces; using ExperimentalTools.Options; using Xunit; namespace ExperimentalTools.Tests.Features.Braces { public class RemoveBracesRefactoringTests : RefactoringTest { public RemoveBracesRefactoringTests(ITestOutputHelper output) : base(output) { } protected override CodeRefactoringProvider Provider => new RemoveBracesRefactoring(new OptionsService()); [Theory, MemberData(nameof(HasActionTestData))] public Task HasActionTest(string test, string input, string expectedOutput) => RunSingleActionTestAsync(input, expectedOutput); public static IEnumerable<object[]> HasActionTestData => new[] { new object[] { "Inner statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) { throw new A@::@rgumentNullException(nameof(arg)); } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } } }" }, new object[] { "Block", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) {@::@ throw new ArgumentNullException(nameof(arg)); } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } } }" }, new object[] { "Parent statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { @::@if (arg == null) { throw new ArgumentNullException(nameof(arg)); } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) throw new ArgumentNullException(nameof(arg)); } } }" }, new object[] { "While statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int i) { while (true) {@::@ i++; } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int i) { while (true) i++; } } }" }, new object[] { "For statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int i) { for (int n = 0; n < 10; n++) {@::@ i++; } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int i) { for (int n = 0; n < 10; n++) i++; } } }" }, new object[] { "Foreach statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int[] arr) { foreach(var n in arr) {@::@ Console.WriteLine(n); } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int[] arr) { foreach(var n in arr) Console.WriteLine(n); } } }" }, new object[] { "Else if statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else if (arg == ""1"") {@::@ arg = ""2""; } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else if (arg == ""1"") arg = ""2""; } } }" }, new object[] { "Else clause (inside inner statement)", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else { @::@arg = ""2""; } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else arg = ""2""; } } }" }, new object[] { "Else clause (inside block)", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else {@::@ arg = ""2""; } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else arg = ""2""; } } }" }, new object[] { "Else clause", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; el@::@se { arg = ""2""; } } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else arg = ""2""; } } }" }, new object[] { "Do statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int i) { do {@::@ i = i + 1; } while (true); } } }", @" using System; namespace HelloWorld { class TestService { public void TestMethod(int i) { do i = i + 1; while (true); } } }" }, new object[] { "Lock statement", @" using System; namespace HelloWorld { class TestService { private int i; public void TestMethod() { lock(this) {@::@ i = i + 1; } } } }", @" using System; namespace HelloWorld { class TestService { private int i; public void TestMethod() { lock(this) i = i + 1; } } }" }, new object[] { "Using statement", @" using System; using System.IO; namespace HelloWorld { class TestService { public void TestMethod() { using (var fs = new FileStream("""", FileMode.Open)) {@::@ fs.ReadByte(); } } } }", @" using System; using System.IO; namespace HelloWorld { class TestService { public void TestMethod() { using (var fs = new FileStream("""", FileMode.Open)) fs.ReadByte(); } } }" }, new object[] { "Fixed statement", @" using System; namespace HelloWorld { class TestService { public unsafe void TestMethod() { string str = ""Hello World""; fixed (char* p = str) {@::@ Console.WriteLine(*p); } } } }", @" using System; namespace HelloWorld { class TestService { public unsafe void TestMethod() { string str = ""Hello World""; fixed (char* p = str) Console.WriteLine(*p); } } }" }, new object[] { "No else clause escape case", @" using System; namespace HelloWorld { class TestService { public string TestMethod() { if (true)@::@ { if (false) return ""A""; else return ""D""; } else return ""B""; return ""C""; } } }", @" using System; namespace HelloWorld { class TestService { public string TestMethod() { if (true) if (false) return ""A""; else return ""D""; else return ""B""; return ""C""; } } }" } }; [Theory, MemberData(nameof(NoActionTestData))] public Task NoActionTest(string test, string input) => RunNoActionTestAsync(input); public static IEnumerable<object[]> NoActionTestData => new[] { new object[] { "Inside a statement which is not in a block", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg != null) Console.Write@::@Line(arg); } } }" }, new object[] { "Inside one of the statements of a multistatement block", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg != null) { arg = arg + ""1""; Console.Wri@::@teLine(arg); } } } }" }, new object[] { "Inside a block with multiple statements", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg != null) {@::@ arg = arg + ""1""; Console.WriteLine(arg); } } } }" }, new object[] { "Inside a parent statement with multiple statements", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { @::@if (arg != null) { arg = arg + ""1""; Console.WriteLine(arg); } } } }" }, new object[] { "Inside an empty parent statement", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { @::@if (arg != null) { } } } }" }, new object[] { "Inside an empty block", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg != null) {@::@ } } } }" }, new object[] { "Inside one of the statements of a multistatement else clause", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else { @::@arg = ""2""; Console.WriteLine(arg); } } } }" }, new object[] { "Inside a block of a multistatement else clause", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; else {@::@ arg = ""2""; Console.WriteLine(arg); } } } }" }, new object[] { "Multistatement else clause", @" using System; namespace HelloWorld { class TestService { public void TestMethod(string arg) { if (arg == null) arg = """"; el@::@se { arg = ""2""; Console.WriteLine(arg); } } } }" }, new object[] { "Else clause escape case (parent statement)", @" using System; namespace HelloWorld { class TestService { public string TestMethod() { if (true)@::@ { if (false) return ""A""; } else return ""B""; return ""C""; } } }" }, new object[] { "Else clause escape case (inner statement)", @" using System; namespace HelloWorld { class TestService { public string TestMethod() { if (true) { @::@if (false) return ""A""; } else return ""B""; return ""C""; } } }" }, new object[] { "Else clause escape case (block)", @" using System; namespace HelloWorld { class TestService { public string TestMethod() { if (true) {@::@ if (false) return ""A""; } else return ""B""; return ""C""; } } }" } }; } }
// 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.Threading; using System.Collections; using Xunit; public class DictionaryBase_OnMethods { public bool runTest() { //////////// Global Variables used for all tests int iCountErrors = 0; int iCountTestcases = 0; MyDictionaryBase myDict; Foo f, newF; string expectedExceptionMessage; try { do { ///////////////////////// START TESTS //////////////////////////// /////////////////////////////////////////////////////////////////// /*********************************************************************************************************************** Add ***********************************************************************************************************************/ //[] Vanilla Add iCountTestcases++; myDict = new MyDictionaryBase(); f = new Foo(); myDict.Add(f, 0.ToString()); if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.OnInsertCompleteCalled) { iCountErrors++; Console.WriteLine("Err_4072ayps OnInsertComplete was never called"); } else if (!myDict.Contains(f)) { iCountErrors++; Console.WriteLine("Err_0181salh Item was added"); } //[] Add where Validate throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnValidateThrow = true; expectedExceptionMessage = "OnValidate"; f = new Foo(); try { myDict.Add(f, 0.ToString()); iCountErrors++; Console.WriteLine("Err_1570pyqa Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_2708apsa Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnInsertCalled) { iCountErrors++; Console.WriteLine("Err_56707awwaps OnInsert was called"); } else if (0 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_2708apsa Expected Empty Collection actual {0} elements", myDict.Count); } //[] Add where OnInsert throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnInsertThrow = true; expectedExceptionMessage = "OnInsert"; f = new Foo(); try { myDict.Add(f, 0.ToString()); iCountErrors++; Console.WriteLine("Err_35208asdo Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_30437sfdah Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnInsertCompleteCalled) { iCountErrors++; Console.WriteLine("Err_370asjhs OnInsertComplete was called"); } else if (0 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_3y07aza Expected Empty Collection actual {0} elements", myDict.Count); } //[] Add where OnInsertComplete throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnInsertCompleteThrow = true; expectedExceptionMessage = "OnInsertComplete"; f = new Foo(); try { myDict.Add(f, 0.ToString()); iCountErrors++; Console.WriteLine("Err_2548ashz Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_2708alkw Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (0 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_3680ahksd Expected Empty Collection actual {0} elements", myDict.Count); } /*********************************************************************************************************************** Remove ***********************************************************************************************************************/ //[] Vanilla Remove iCountTestcases++; myDict = new MyDictionaryBase(); f = new Foo(); myDict.Add(f, 0.ToString()); myDict.Remove(f); if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.OnRemoveCompleteCalled) { iCountErrors++; Console.WriteLine("Err_348awq OnRemoveComplete was never called"); } else if (myDict.Contains(f)) { iCountErrors++; Console.WriteLine("Err_0824answ Item was not removed"); } //[] Remove where Validate throws iCountTestcases++; myDict = new MyDictionaryBase(); expectedExceptionMessage = "OnValidate"; f = new Foo(); try { myDict.Add(f, 0.ToString()); myDict.OnValidateThrow = true; myDict.Remove(f); iCountErrors++; Console.WriteLine("Err_08207hnas Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_87082aspz Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnRemoveCalled) { iCountErrors++; Console.WriteLine("Err_7207snmqla OnRemove was called"); } else if (!myDict.Contains(f)) { iCountErrors++; Console.WriteLine("Err_7270pahnz Element was actually removed {0}", myDict.Contains(f)); } //[] Remove where OnRemove throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnRemoveThrow = true; expectedExceptionMessage = "OnRemove"; f = new Foo(); try { myDict.Add(f, 0.ToString()); myDict.Remove(f); iCountErrors++; Console.WriteLine("Err_7708aqyy Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_08281naws Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnRemoveCompleteCalled) { iCountErrors++; Console.WriteLine("Err_10871aklsj OnRemoveComplete was called"); } else if (!myDict.Contains(f)) { iCountErrors++; Console.WriteLine("Err_2081aslkjs Element was actually removed {0}", myDict.Contains(f)); } //[] Remove where OnRemoveComplete throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnRemoveCompleteThrow = true; expectedExceptionMessage = "OnRemoveComplete"; f = new Foo(); try { myDict.Add(f, 0.ToString()); myDict.Remove(f); iCountErrors++; Console.WriteLine("Err_10981nlskj Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_20981askjs Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.Contains(f)) { iCountErrors++; Console.WriteLine("Err_20909assfd Element was actually removed {0}", myDict.Contains(f)); } /*********************************************************************************************************************** Clear ***********************************************************************************************************************/ //[] Vanilla Clear iCountTestcases++; myDict = new MyDictionaryBase(); f = new Foo(); myDict.Add(f, 0.ToString()); myDict.Clear(); if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.OnClearCompleteCalled) { iCountErrors++; Console.WriteLine("Err_2136sdf OnClearComplete was never called"); } else if (0 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_9494aswa Items were not Cleared"); } //[] Clear where Validate throws iCountTestcases++; myDict = new MyDictionaryBase(); expectedExceptionMessage = "OnValidate"; f = new Foo(); myDict.Add(f, 0.ToString()); myDict.OnValidateThrow = true; myDict.Clear(); if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.OnClearCompleteCalled) { iCountErrors++; Console.WriteLine("Err_6549asff OnClearComplete was not called"); } else if (0 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_4649awajm Items were Cleared"); } //[] Clear where OnClear throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnClearThrow = true; expectedExceptionMessage = "OnClear"; f = new Foo(); try { myDict.Add(f, 0.ToString()); myDict.Clear(); iCountErrors++; Console.WriteLine("Err_9444sjpjnException was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_78941joaException message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnClearCompleteCalled) { iCountErrors++; Console.WriteLine("Err_94944awfuu OnClearComplete was called"); } else if (1 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_6498 Items were not Cleared"); } //[] Clear where OnClearComplete throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnClearCompleteThrow = true; expectedExceptionMessage = "OnClearComplete"; f = new Foo(); try { myDict.Add(f, 0.ToString()); myDict.Clear(); iCountErrors++; Console.WriteLine("Err_64977awad Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_0877asaw Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (0 != myDict.Count) { iCountErrors++; Console.WriteLine("Err_1081lkajs Items were not Cleared"); } /*********************************************************************************************************************** Set that adds an item ***********************************************************************************************************************/ //[] Vanilla Set iCountTestcases++; myDict = new MyDictionaryBase(); f = new Foo(1, "1"); newF = new Foo(2, "2"); myDict.Add(f, 1.ToString()); myDict[newF] = 2.ToString(); if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.OnSetCompleteCalled) { iCountErrors++; Console.WriteLine("Err_1698asdf OnSetComplete was never called"); } else if (!myDict.Contains(f) || !myDict.Contains(newF)) { iCountErrors++; Console.WriteLine("Err_9494safs Item was not Set"); } //[] Set where Validate throws iCountTestcases++; myDict = new MyDictionaryBase(); expectedExceptionMessage = "OnValidate"; f = new Foo(1, "1"); newF = new Foo(2, "2"); try { myDict.Add(f, 1.ToString()); myDict.OnValidateThrow = true; myDict[newF] = 2.ToString(); iCountErrors++; Console.WriteLine("Err_611awwa Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_69498hph Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnSetCalled) { iCountErrors++; Console.WriteLine("Err_94887jio OnSet was called"); } else if (!myDict.Contains(f) || myDict.Contains(newF)) { iCountErrors++; Console.WriteLine("Err_6549ihyopiu Element was actually Set {0}", myDict.Contains(f)); } //[] Set where OnSet throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnSetThrow = true; expectedExceptionMessage = "OnSet"; f = new Foo(1, "1"); newF = new Foo(2, "2"); try { myDict.Add(f, 1.ToString()); myDict[newF] = 2.ToString(); iCountErrors++; Console.WriteLine("Err_61518haiosd Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_196198sdklhsException message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnSetCompleteCalled) { iCountErrors++; Console.WriteLine("Err_6548dasfs OnSetComplete was called"); } else if (!myDict.Contains(f) || myDict.Contains(newF)) { iCountErrors++; Console.WriteLine("Err_2797sah Element was actually Set {0}", myDict.Contains(f)); } //[] Set where OnSetComplete throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnSetCompleteThrow = true; expectedExceptionMessage = "OnSetComplete"; f = new Foo(1, "1"); newF = new Foo(2, "2"); try { myDict.Add(f, 1.ToString()); myDict[newF] = 2.ToString(); iCountErrors++; Console.WriteLine("Err_56498hkashException was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_13168hsaiuh Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.Contains(f) || myDict.Contains(newF)) { iCountErrors++; Console.WriteLine("Err_64198ahihos Element was actually Set {0}", myDict.Contains(f)); } /*********************************************************************************************************************** Set that sets an existing item ***********************************************************************************************************************/ //[] Vanilla Set iCountTestcases++; myDict = new MyDictionaryBase(); f = new Foo(1, "1"); myDict.Add(f, 1.ToString()); myDict[f] = 2.ToString(); if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.OnSetCompleteCalled) { iCountErrors++; Console.WriteLine("Err_1698asdf OnSetComplete was never called"); } else if (!myDict.Contains(f) || myDict[f] != "2") { iCountErrors++; Console.WriteLine("Err_9494safs Item was not Set"); } //[] Set where Validate throws iCountTestcases++; myDict = new MyDictionaryBase(); expectedExceptionMessage = "OnValidate"; f = new Foo(1, "1"); try { myDict.Add(f, 1.ToString()); myDict.OnValidateThrow = true; myDict[f] = 2.ToString(); iCountErrors++; Console.WriteLine("Err_611awwa Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_69498hph Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnSetCalled) { iCountErrors++; Console.WriteLine("Err_94887jio OnSet was called"); } else if (!myDict.Contains(f) || myDict[f] != "1") { iCountErrors++; Console.WriteLine("Err_6549ihyopiu Element was actually Set {0}", myDict.Contains(f)); } //[] Set where OnSet throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnSetThrow = true; expectedExceptionMessage = "OnSet"; f = new Foo(1, "1"); try { myDict.Add(f, 1.ToString()); myDict[f] = 2.ToString(); iCountErrors++; Console.WriteLine("Err_61518haiosd Exception was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_196198sdklhsException message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (myDict.OnSetCompleteCalled) { iCountErrors++; Console.WriteLine("Err_6548dasfs OnSetComplete was called"); } else if (!myDict.Contains(f) || myDict[f] != "1") { iCountErrors++; Console.WriteLine("Err_2797sah Element was actually Set {0}", myDict.Contains(f)); } //[] Set where OnSetComplete throws iCountTestcases++; myDict = new MyDictionaryBase(); myDict.OnSetCompleteThrow = true; expectedExceptionMessage = "OnSetComplete"; f = new Foo(1, "1"); try { myDict.Add(f, 1.ToString()); myDict[f] = 2.ToString(); iCountErrors++; Console.WriteLine("Err_56498hkashException was not thrown"); } catch (Exception e) { if (expectedExceptionMessage != e.Message) { iCountErrors++; Console.WriteLine("Err_13168hsaiuh Exception message was wrong expected '{0}' actual '{1}'", expectedExceptionMessage, e.Message); } } if (myDict.IsError) { iCountErrors++; Console.WriteLine(myDict.ErrorMsg); } else if (!myDict.Contains(f) || myDict[f] != "1") { iCountErrors++; Console.WriteLine("Err_64198ahihos Element was actually Set {0}", myDict.Contains(f)); } /////////////////////////// END TESTS ///////////////////////////// } while (false); } catch (Exception exc_general) { ++iCountErrors; Console.WriteLine(" : Error Err_8888yyy! exc_general==\n" + exc_general.ToString()); } //// Finish Diagnostics if (iCountErrors == 0) { return true; } else { Console.WriteLine("Fail iCountErrors==" + iCountErrors); return false; } } [Fact] public static void ExecuteDictionaryBase_OnMethods() { bool bResult = false; var cbA = new DictionaryBase_OnMethods(); try { bResult = cbA.runTest(); } catch (Exception exc_main) { bResult = false; Console.WriteLine(" : FAiL! Error Err_9999zzz! Uncaught Exception in main(), exc_main==" + exc_main); } Assert.True(bResult); } //DictionaryBase is provided to be used as the base class for strongly typed collections. Lets use one of our own here public class MyDictionaryBase : DictionaryBase { public bool IsError = false; public string ErrorMsg = String.Empty; public bool OnValidateCalled, OnSetCalled, OnSetCompleteCalled, OnInsertCalled, OnInsertCompleteCalled, OnClearCalled, OnClearCompleteCalled, OnRemoveCalled, OnRemoveCompleteCalled; public bool OnValidateThrow, OnSetThrow, OnSetCompleteThrow, OnInsertThrow, OnInsertCompleteThrow, OnClearThrow, OnClearCompleteThrow, OnRemoveThrow, OnRemoveCompleteThrow; public MyDictionaryBase() { OnValidateCalled = false; OnSetCalled = false; OnSetCompleteCalled = false; OnInsertCalled = false; OnInsertCompleteCalled = false; OnClearCalled = false; OnClearCompleteCalled = false; OnRemoveCalled = false; OnRemoveCompleteCalled = false; OnValidateThrow = false; OnSetThrow = false; OnSetCompleteThrow = false; OnInsertThrow = false; OnInsertCompleteThrow = false; OnClearThrow = false; OnClearCompleteThrow = false; OnRemoveThrow = false; OnRemoveCompleteThrow = false; } public void Add(Foo key, string value) { Dictionary.Add(key, value); } public string this[Foo index] { get { return (string)Dictionary[index]; } set { Dictionary[index] = value; } } public Boolean Contains(Foo f) { return Dictionary.Contains(f); } public void Remove(Foo f) { Dictionary.Remove(f); } protected override void OnSet(Object key, Object oldValue, Object newValue) { if (!OnValidateCalled) { IsError = true; ErrorMsg += "Err_0882pxnk OnValidate has not been called\n"; } if (this[(Foo)key] != (string)oldValue) { IsError = true; ErrorMsg += "Err_1204phzn Value was already set\n"; } OnSetCalled = true; if (OnSetThrow) throw new Exception("OnSet"); } protected override void OnInsert(Object key, Object value) { if (!OnValidateCalled) { IsError = true; ErrorMsg += "Err_0834halkh OnValidate has not been called\n"; } if (this[(Foo)key] == (string)value) { IsError = true; ErrorMsg += "Err_2702apqh OnInsert called with a bad index\n"; } OnInsertCalled = true; if (OnInsertThrow) throw new Exception("OnInsert"); } protected override void OnClear() { if (Count == 0 || Dictionary.Count == 0) { //Assumes Clear not called on an empty list IsError = true; ErrorMsg += "Err_2247alkhz List already empty\n"; } OnClearCalled = true; if (OnClearThrow) throw new Exception("OnClear"); } protected override void OnRemove(Object key, Object value) { if (!OnValidateCalled) { IsError = true; ErrorMsg += "Err_3703pyaa OnValidate has not been called\n"; } if (this[(Foo)key] != (string)value) { IsError = true; ErrorMsg += "Err_1708afsw Value was already set\n"; } OnRemoveCalled = true; if (OnRemoveThrow) throw new Exception("OnRemove"); } protected override void OnValidate(Object key, Object value) { OnValidateCalled = true; if (OnValidateThrow) throw new Exception("OnValidate"); } protected override void OnSetComplete(Object key, Object oldValue, Object newValue) { if (!OnSetCalled) { IsError = true; ErrorMsg += "Err_0282pyahn OnSet has not been called\n"; } if (this[(Foo)key] != (string)newValue) { IsError = true; ErrorMsg += "Err_2134pyqt Value has not been set\n"; } OnSetCompleteCalled = true; if (OnSetCompleteThrow) throw new Exception("OnSetComplete"); } protected override void OnInsertComplete(Object key, Object value) { if (!OnInsertCalled) { IsError = true; ErrorMsg += "Err_5607aspyu OnInsert has not been called\n"; } if (this[(Foo)key] != (string)value) { IsError = true; ErrorMsg += "Err_3407ahpqValue has not been set\n"; } OnInsertCompleteCalled = true; if (OnInsertCompleteThrow) throw new Exception("OnInsertComplete"); } protected override void OnClearComplete() { if (!OnClearCalled) { IsError = true; ErrorMsg += "Err_3470sfas OnClear has not been called\n"; } if (Count != 0 || Dictionary.Count != 0) { IsError = true; ErrorMsg += "Err_2507yuznb Value has not been set\n"; } OnClearCompleteCalled = true; if (OnClearCompleteThrow) throw new Exception("OnClearComplete"); } protected override void OnRemoveComplete(Object key, Object value) { if (!OnRemoveCalled) { IsError = true; ErrorMsg += "Err_70782sypz OnRemve has not been called\n"; } if (Contains((Foo)key)) { IsError = true; ErrorMsg += "Err_3097saq Value still exists\n"; } OnRemoveCompleteCalled = true; if (OnRemoveCompleteThrow) throw new Exception("OnRemoveComplete"); } public void ClearTest() { IsError = false; ErrorMsg = String.Empty; OnValidateCalled = false; OnSetCalled = false; OnSetCompleteCalled = false; OnInsertCalled = false; OnInsertCompleteCalled = false; OnClearCalled = false; OnClearCompleteCalled = false; OnRemoveCalled = false; OnRemoveCompleteCalled = false; OnValidateThrow = false; OnSetThrow = false; OnSetCompleteThrow = false; OnInsertThrow = false; OnInsertCompleteThrow = false; OnClearThrow = false; OnClearCompleteThrow = false; OnRemoveThrow = false; OnRemoveCompleteThrow = false; } } public class Foo { private Int32 _iValue; private String _strValue; public Foo() { } public Foo(Int32 i, String str) { _iValue = i; _strValue = str; } public Int32 IValue { get { return _iValue; } set { _iValue = value; } } public String SValue { get { return _strValue; } set { _strValue = value; } } public override Boolean Equals(Object obj) { if (obj == null) return false; if (!(obj is Foo)) return false; if ((((Foo)obj).IValue == _iValue) && (((Foo)obj).SValue == _strValue)) return true; return false; } public override Int32 GetHashCode() { return _iValue; } } }
// 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 Xunit; using System; using System.Xml; using System.Xml.XPath; using XPathTests.Common; namespace XPathTests.FunctionalTests.CoreFunctionLibrary { /// <summary> /// Core Function Library - String Functions /// </summary> public static partial class StringFunctionsTests { /// <summary> /// Verify result. /// string()="context node data" /// </summary> [Fact] public static void StringFunctionsTest241() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1/Para[1]"; var testExpression = @"string()"; var expected = @"Test"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// string(1) = "1" /// </summary> [Fact] public static void StringFunctionsTest242() { var xml = "dummy.xml"; var testExpression = @"string(1)"; var expected = 1d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(-0) = "0" /// </summary> [Fact] public static void StringFunctionsTest243() { var xml = "dummy.xml"; var testExpression = @"string(-0)"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(+0) = "0" /// </summary> [Fact] public static void StringFunctionsTest244() { var xml = "dummy.xml"; var testExpression = @"string(+0)"; Utils.XPathStringTestThrows<System.Xml.XPath.XPathException>(xml, testExpression); } /// <summary> /// Verify result. /// string(number("NotANumber")) = "NaN" /// </summary> [Fact] public static void StringFunctionsTest245() { var xml = "dummy.xml"; var testExpression = @"string(number(""NotANumber""))"; var expected = Double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(true()) = "true" /// </summary> [Fact] public static void StringFunctionsTest246() { var xml = "dummy.xml"; var testExpression = @"string(true())"; var expected = @"true"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(false()) = "false" /// </summary> [Fact] public static void StringFunctionsTest247() { var xml = "dummy.xml"; var testExpression = @"string(false())"; var expected = @"false"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string(child::para) = "1st child node data" /// </summary> [Fact] public static void StringFunctionsTest248() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"string(child::Para)"; var expected = @"Test"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// concat("AA", "BB") = "AABB" /// </summary> [Fact] public static void StringFunctionsTest249() { var xml = "dummy.xml"; var testExpression = @"concat(""AA"", ""BB"")"; var expected = @"AABB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// concat("AA", "BB", "CC") = "AABBCC" /// </summary> [Fact] public static void StringFunctionsTest2410() { var xml = "dummy.xml"; var testExpression = @"concat(""AA"", ""BB"", ""CC"")"; var expected = @"AABBCC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// concat(string(child::*), "BB") = "AABB" /// </summary> [Fact] public static void StringFunctionsTest2411() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"concat(string(child::*), ""BB"")"; var expected = @"TestBB"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// starts-with("AABB", "AA") = true /// </summary> [Fact] public static void StringFunctionsTest2412() { var xml = "dummy.xml"; var testExpression = @"starts-with(""AABB"", ""AA"")"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// starts-with("AABB", "BB") = false /// </summary> [Fact] public static void StringFunctionsTest2413() { var xml = "dummy.xml"; var testExpression = @"starts-with(""AABB"", ""BB"")"; var expected = false; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// starts-with("AABB", string(child::*)) = true /// </summary> [Fact] public static void StringFunctionsTest2414() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"starts-with(""TestBB"", string(child::*))"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// contains("AABBCC", "BB") = true /// </summary> [Fact] public static void StringFunctionsTest2415() { var xml = "dummy.xml"; var testExpression = @"contains(""AABBCC"", ""BB"")"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// contains("AABBCC", "DD") = false /// </summary> [Fact] public static void StringFunctionsTest2416() { var xml = "dummy.xml"; var testExpression = @"contains(""AABBCC"", ""DD"")"; var expected = false; Utils.XPathBooleanTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// contains("AABBCC", string(child::*)) = true /// </summary> [Fact] public static void StringFunctionsTest2417() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"contains(""AATestBB"", string(child::*))"; var expected = true; Utils.XPathBooleanTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// substring-before("AA/BB", "/") = "AA" /// </summary> [Fact] public static void StringFunctionsTest2418() { var xml = "dummy.xml"; var testExpression = @"substring-before(""AA/BB"", ""/"")"; var expected = @"AA"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-before("AA/BB", "D") = "" /// </summary> [Fact] public static void StringFunctionsTest2419() { var xml = "dummy.xml"; var testExpression = @"substring-before(""AA/BB"", ""D"")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-before(string(child::*), "/") = "AA" /// </summary> [Fact] public static void StringFunctionsTest2420() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"substring-before(string(child::*), ""t"")"; var expected = @"Tes"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// substring-after("AA/BB", "/") = "BB" /// </summary> [Fact] public static void StringFunctionsTest2421() { var xml = "dummy.xml"; var testExpression = @"substring-after(""AA/BB"", ""/"")"; var expected = @"BB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-after("AA/BB", "D") != "" /// </summary> [Fact] public static void StringFunctionsTest2422() { var xml = "dummy.xml"; var testExpression = @"substring-after(""AA/BB"", ""D"")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring-after(string(child::*), "/") = "BB" /// </summary> [Fact] public static void StringFunctionsTest2423() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"substring-after(string(child::*), ""T"")"; var expected = @"est"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// substring("ABC", 2) = "BC" /// </summary> [Fact] public static void StringFunctionsTest2424() { var xml = "dummy.xml"; var testExpression = @"substring(""ABC"", 2)"; var expected = @"BC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCD", 2, 2) = "BC" /// </summary> [Fact] public static void StringFunctionsTest2425() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCD"", 2, 2)"; var expected = @"BC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 1.5, 2.6) = "BCD" /// </summary> [Fact] public static void StringFunctionsTest2426() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1.5, 2.6)"; var expected = @"BCD"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 0, 3) = "AB" /// </summary> [Fact] public static void StringFunctionsTest2427() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 0, 3)"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 0 div 0, 3) = "" /// </summary> [Fact] public static void StringFunctionsTest2428() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 0 div 0, 3)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", 1, 0 div 0) = "" /// </summary> [Fact] public static void StringFunctionsTest2429() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1, 0 div 0)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", -42, 1 div 0) = "ABCDE" /// </summary> [Fact] public static void StringFunctionsTest2430() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", -42, 1 div 0)"; var expected = @"ABCDE"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring("ABCDE", -1 div 0, 1 div 0) = "" /// </summary> [Fact] public static void StringFunctionsTest2431() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", -1 div 0, 1 div 0)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// substring(string(child::*), 2) = "BC" /// </summary> [Fact] public static void StringFunctionsTest2432() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"substring(string(child::*), 2)"; var expected = @"est"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// string-length("ABCDE") = 5 /// </summary> [Fact] public static void StringFunctionsTest2433() { var xml = "dummy.xml"; var testExpression = @"string-length(""ABCDE"")"; var expected = 5d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result ( assuming the string-value of the context node has 5 characters). /// string-length() = 5 /// </summary> [Fact] public static void StringFunctionsTest2434() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1/Para[1]"; var testExpression = @"string-length()"; var expected = 4d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// string-length("") = 0 /// </summary> [Fact] public static void StringFunctionsTest2435() { var xml = "dummy.xml"; var testExpression = @"string-length("""")"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// string-length(string(child::*)) = 2 /// </summary> [Fact] public static void StringFunctionsTest2436() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"string-length(string(child::*))"; var expected = 4d; Utils.XPathNumberTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// normalize-space("") = "" /// </summary> [Fact] public static void StringFunctionsTest2473() { var xml = "dummy.xml"; var testExpression = @"normalize-space("""")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" \t\n\r") = "" /// </summary> [Fact] public static void StringFunctionsTest2474() { var xml = "dummy.xml"; var testExpression = "normalize-space(\" \t\n\r\")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" Surrogate-Pair-String ") = "" /// </summary> [Fact] public static void StringFunctionsTest2475() { var xml = "dummy.xml"; var fourCircles = char.ConvertFromUtf32(0x1F01C); var testExpression = "normalize-space(\" " + fourCircles + " \")"; var expected = fourCircles; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" AB") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2437() { var xml = "dummy.xml"; var testExpression = @"normalize-space("" AB"")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("AB ") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2438() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""AB "")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("A B") = "A B" /// </summary> [Fact] public static void StringFunctionsTest2439() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""A B"")"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" AB") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2440() { var xml = "dummy.xml"; var testExpression = @"normalize-space("" AB"")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("AB ") = "AB" /// </summary> [Fact] public static void StringFunctionsTest2441() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""AB "")"; var expected = @"AB"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space("A B") = "A B" /// </summary> [Fact] public static void StringFunctionsTest2442() { var xml = "dummy.xml"; var testExpression = @"normalize-space(""A B"")"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(" A B ") = "A B" /// </summary> [Fact] public static void StringFunctionsTest2443() { var xml = "dummy.xml"; var testExpression = @"normalize-space("" A B "")"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space() = "A B" /// </summary> [Fact] public static void StringFunctionsTest2444() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test4/Para[1]"; var testExpression = @"normalize-space()"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Checks for preceding and trailing whitespaces /// normalize-space(' abc ') /// </summary> [Fact] public static void StringFunctionsTest2445() { var xml = "books.xml"; var testExpression = @"normalize-space(' abc ')"; var expected = @"abc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Checks for preceding and trailing whitespaces (characters other than space) /// normalize-space(' abc ') /// </summary> [Fact] public static void StringFunctionsTest2446() { var xml = "books.xml"; var testExpression = @"normalize-space(' abc ')"; var expected = @"abc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Checks for a sequence of whitespaces between characters /// normalize-space('a bc') /// </summary> [Fact] public static void StringFunctionsTest2447() { var xml = "books.xml"; var testExpression = @"normalize-space('a bc')"; var expected = @"a bc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Checks for a sequence of whitespaces between characters (characters other than space) /// normalize-space('a bc') /// </summary> [Fact] public static void StringFunctionsTest2448() { var xml = "books.xml"; var testExpression = @"normalize-space('a bc')"; var expected = @"a bc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// A single tab should be replaced with a space /// normalize-space('a bc') /// </summary> [Fact] public static void StringFunctionsTest2449() { var xml = "books.xml"; var testExpression = @"normalize-space('a bc')"; var expected = @"a bc"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// normalize-space(string(child::*)) = "A B" /// </summary> [Fact] public static void StringFunctionsTest2450() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test4"; var testExpression = @"normalize-space(string(child::*))"; var expected = @"A B"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// Verify result. /// translate("", "abc", "ABC") = "" /// </summary> [Fact] public static void StringFunctionsTest2472() { var xml = "dummy.xml"; var testExpression = @"translate("""", ""abc"", ""ABC"")"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("unicode", "unicode", "uppercase-unicode") = "uppercase -unicode" /// </summary> [Fact] public static void StringFunctionsTest2476() { var xml = "dummy.xml"; var testExpression = "translate(\"\0x03B1\0x03B2\0x03B3\", \"\0x03B1\0x03B2\0x03B3\", \"\0x0391\0x0392\0x0393\")"; var expected = "\0x0391\0x0392\0x0393"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("surrogate-pairs", "ABC", "") = "surrogate-pairs" /// </summary> [Fact] public static void StringFunctionsTest2477() { var xml = "dummy.xml"; var fourOClock = char.ConvertFromUtf32(0x1F553); var fiveOClock = char.ConvertFromUtf32(0x1F554); var testExpression = @"translate(""" + fourOClock + fiveOClock + @""", ""ABC"", """")"; var expected = fourOClock + fiveOClock; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("abc", "abca", "ABCZ") = "ABC" /// </summary> [Fact] public static void StringFunctionsTest2478() { var xml = "dummy.xml"; var testExpression = @"translate(""abc"", ""abca"", ""ABCZ"")"; var expected = "ABC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("abc", "abc", "ABC") = "ABC" /// </summary> [Fact] public static void StringFunctionsTest2451() { var xml = "dummy.xml"; var testExpression = @"translate(""abc"", ""abc"", ""ABC"")"; var expected = @"ABC"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("aba", "b", "B") = "aBa" /// </summary> [Fact] public static void StringFunctionsTest2452() { var xml = "dummy.xml"; var testExpression = @"translate(""aba"", ""b"", ""B"")"; var expected = @"aBa"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate("--aaa--", "abc-", "ABC") = "AAA" /// </summary> [Fact] public static void StringFunctionsTest2453() { var xml = "dummy.xml"; var testExpression = @"translate(""-aaa-"", ""abc-"", ""ABC"")"; var expected = @"AAA"; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// Verify result. /// translate(string(child::*), "AB", "ab") = "aa" /// </summary> [Fact] public static void StringFunctionsTest2454() { var xml = "xp004.xml"; var startingNodePath = "/Doc/Test1"; var testExpression = @"translate(string(child::*), ""est"", ""EST"")"; var expected = @"TEST"; Utils.XPathStringTest(xml, testExpression, expected, startingNodePath: startingNodePath); } /// <summary> /// string(NaN) /// </summary> [Fact] public static void StringFunctionsTest2455() { var xml = "dummy.xml"; var testExpression = @"string(number(0 div 0))"; var expected = Double.NaN; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(-0) /// </summary> [Fact] public static void StringFunctionsTest2456() { var xml = "dummy.xml"; var testExpression = @"string(-0)"; var expected = 0d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(infinity) /// </summary> [Fact] public static void StringFunctionsTest2457() { var xml = "dummy.xml"; var testExpression = @"string(number(1 div 0))"; var expected = Double.PositiveInfinity; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(-Infinity) /// </summary> [Fact] public static void StringFunctionsTest2458() { var xml = "dummy.xml"; var testExpression = @"string(number(-1 div 0))"; var expected = Double.NegativeInfinity; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// for integers, leading zeros and decimal should be removed /// string(007.00) /// </summary> [Fact] public static void StringFunctionsTest2459() { var xml = "dummy.xml"; var testExpression = @"string(007.00)"; var expected = 7d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// string(-007.00) /// </summary> [Fact] public static void StringFunctionsTest2460() { var xml = "dummy.xml"; var testExpression = @"string(-007.00)"; var expected = -7d; Utils.XPathNumberTest(xml, testExpression, expected); } /// <summary> /// Code coverage: covers the substring() function with in a query /// child::*[substring(name(),0,1)="b"] /// </summary> [Fact] public static void StringFunctionsTest2461() { var xml = "books.xml"; var testExpression = @"child::*[substring(name(),0,1)=""b""]"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Code coverage: covers the substring-after() function with in a query /// child::*[substring-after(name(),"b")="ook"] /// </summary> [Fact] public static void StringFunctionsTest2462() { var xml = "books.xml"; var testExpression = @"child::*[substring-after(name(),""b"")=""ook""]"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Code coverage: covers the normalize-space() function with in a query /// child::*[normalize-space(" book")=name()] /// </summary> [Fact] public static void StringFunctionsTest2463() { var xml = "books.xml"; var testExpression = @"child::*[normalize-space("" book"")=name()]"; var expected = new XPathResult(0); ; Utils.XPathNodesetTest(xml, testExpression, expected); } /// <summary> /// Expected: namespace uri /// string() (namespace node) /// </summary> [Fact] public static void StringFunctionsTest2464() { var xml = "name2.xml"; var startingNodePath = "/ns:store/ns:booksection/namespace::NSbook"; var testExpression = @"string()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://book.htm"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: xml namespace uri /// string() (namespace node = xml) /// </summary> [Fact] public static void StringFunctionsTest2465() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[last()]"; var testExpression = @"string()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://www.w3.org/XML/1998/namespace"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: default namespace uri /// string() (namespace node = default ns) /// </summary> [Fact] public static void StringFunctionsTest2466() { var xml = "name2.xml"; var startingNodePath = "/ns:store/namespace::*[1]"; var testExpression = @"string()"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://default.htm"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager, startingNodePath: startingNodePath); } /// <summary> /// Expected: uri of namespace /// string() (namespace node) /// </summary> [Fact] public static void StringFunctionsTest2467() { var xml = "name2.xml"; var testExpression = @"string(ns:store/ns:booksection/namespace::*)"; var namespaceManager = new XmlNamespaceManager(new NameTable()); namespaceManager.AddNamespace("ns", "http://default.htm"); var expected = @"http://book.htm"; Utils.XPathStringTest(xml, testExpression, expected, namespaceManager: namespaceManager); } /// <summary> /// substring("ABCDE", 1, -1) /// </summary> [Fact] public static void StringFunctionsTest2468() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1, -1)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// substring("ABCDE", 1, -1 div 0) /// </summary> [Fact] public static void StringFunctionsTest2469() { var xml = "dummy.xml"; var testExpression = @"substring(""ABCDE"", 1, -1 div 0)"; var expected = @""; Utils.XPathStringTest(xml, testExpression, expected); } /// <summary> /// string(/bookstore/book/title) /// </summary> [Fact] public static void StringFunctionsTest2471() { var xml = "books.xml"; var testExpression = @"string(/bookstore/book/title)"; var expected = @"Seven Years in Trenton"; Utils.XPathStringTest(xml, testExpression, expected); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace System.Data.OleDb { public sealed class OleDbTransaction : DbTransaction { private readonly OleDbTransaction _parentTransaction; // strong reference to keep parent alive private readonly System.Data.IsolationLevel _isolationLevel; private WeakReference _nestedTransaction; // child transactions private WrappedTransaction _transaction; internal OleDbConnection _parentConnection; private sealed class WrappedTransaction : WrappedIUnknown { private bool _mustComplete; internal WrappedTransaction(UnsafeNativeMethods.ITransactionLocal transaction, int isolevel, out OleDbHResult hr) : base(transaction) { int transactionLevel = 0; RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { hr = transaction.StartTransaction(isolevel, 0, IntPtr.Zero, out transactionLevel); if (0 <= hr) { _mustComplete = true; } } } internal bool MustComplete { get { return _mustComplete; } } internal OleDbHResult Abort() { Debug.Assert(_mustComplete, "transaction already completed"); OleDbHResult hr; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { hr = (OleDbHResult)NativeOledbWrapper.ITransactionAbort(DangerousGetHandle()); _mustComplete = false; } } finally { if (mustRelease) { DangerousRelease(); } } return hr; } internal OleDbHResult Commit() { Debug.Assert(_mustComplete, "transaction already completed"); OleDbHResult hr; bool mustRelease = false; RuntimeHelpers.PrepareConstrainedRegions(); try { DangerousAddRef(ref mustRelease); RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { hr = (OleDbHResult)NativeOledbWrapper.ITransactionCommit(DangerousGetHandle()); if ((0 <= (int)hr) || (OleDbHResult.XACT_E_NOTRANSACTION == hr)) { _mustComplete = false; } } } finally { if (mustRelease) { DangerousRelease(); } } return hr; } protected override bool ReleaseHandle() { if (_mustComplete && (IntPtr.Zero != base.handle)) { OleDbHResult hr = (OleDbHResult)NativeOledbWrapper.ITransactionAbort(base.handle); _mustComplete = false; } return base.ReleaseHandle(); } } internal OleDbTransaction(OleDbConnection connection, OleDbTransaction transaction, IsolationLevel isolevel) { _parentConnection = connection; _parentTransaction = transaction; switch (isolevel) { case IsolationLevel.Unspecified: // OLE DB doesn't support this isolevel on local transactions isolevel = IsolationLevel.ReadCommitted; break; case IsolationLevel.Chaos: case IsolationLevel.ReadUncommitted: case IsolationLevel.ReadCommitted: case IsolationLevel.RepeatableRead: case IsolationLevel.Serializable: case IsolationLevel.Snapshot: break; default: throw ADP.InvalidIsolationLevel(isolevel); } _isolationLevel = isolevel; } public new OleDbConnection Connection { get { return _parentConnection; } } protected override DbConnection DbConnection { get { return Connection; } } public override IsolationLevel IsolationLevel { get { if (null == _transaction) { throw ADP.TransactionZombied(this); } return _isolationLevel; } } internal OleDbTransaction Parent { get { return _parentTransaction; } } public OleDbTransaction Begin(IsolationLevel isolevel) { if (null == _transaction) { throw ADP.TransactionZombied(this); } else if ((null != _nestedTransaction) && _nestedTransaction.IsAlive) { throw ADP.ParallelTransactionsNotSupported(Connection); } // either the connection will be open or this will be a zombie OleDbTransaction transaction = new OleDbTransaction(_parentConnection, this, isolevel); _nestedTransaction = new WeakReference(transaction, false); UnsafeNativeMethods.ITransactionLocal wrapper = null; try { wrapper = (UnsafeNativeMethods.ITransactionLocal)_transaction.ComWrapper(); transaction.BeginInternal(wrapper); } finally { if (null != wrapper) { Marshal.ReleaseComObject(wrapper); } } return transaction; } public OleDbTransaction Begin() { return Begin(IsolationLevel.ReadCommitted); } internal void BeginInternal(UnsafeNativeMethods.ITransactionLocal transaction) { OleDbHResult hr; _transaction = new WrappedTransaction(transaction, (int)_isolationLevel, out hr); if (hr < 0) { _transaction.Dispose(); _transaction = null; ProcessResults(hr); } } public override void Commit() { if (null == _transaction) { throw ADP.TransactionZombied(this); } CommitInternal(); } private void CommitInternal() { if (null == _transaction) { return; } if (null != _nestedTransaction) { OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target; if ((null != transaction) && _nestedTransaction.IsAlive) { transaction.CommitInternal(); } _nestedTransaction = null; } OleDbHResult hr = _transaction.Commit(); if (!_transaction.MustComplete) { _transaction.Dispose(); _transaction = null; DisposeManaged(); } if (hr < 0) { // if an exception is thrown, user can try to commit their transaction again ProcessResults(hr); } } /*public OleDbCommand CreateCommand() { OleDbCommand cmd = Connection.CreateCommand(); cmd.Transaction = this; return cmd; } IDbCommand IDbTransaction.CreateCommand() { return CreateCommand(); }*/ protected override void Dispose(bool disposing) { if (disposing) { DisposeManaged(); RollbackInternal(false); } base.Dispose(disposing); } private void DisposeManaged() { if (null != _parentTransaction) { _parentTransaction._nestedTransaction = null; //_parentTransaction = null; } else if (null != _parentConnection) { _parentConnection.LocalTransaction = null; } _parentConnection = null; } private void ProcessResults(OleDbHResult hr) { Exception e = OleDbConnection.ProcessResults(hr, _parentConnection, this); if (null != e) { throw e; } } public override void Rollback() { if (null == _transaction) { throw ADP.TransactionZombied(this); } DisposeManaged(); RollbackInternal(true); // no recover if this throws an exception } /*protected virtual*/ internal OleDbHResult RollbackInternal(bool exceptionHandling) { OleDbHResult hr = 0; if (null != _transaction) { if (null != _nestedTransaction) { OleDbTransaction transaction = (OleDbTransaction)_nestedTransaction.Target; if ((null != transaction) && _nestedTransaction.IsAlive) { hr = transaction.RollbackInternal(exceptionHandling); if (exceptionHandling && (hr < 0)) { SafeNativeMethods.Wrapper.ClearErrorInfo(); return hr; } } _nestedTransaction = null; } hr = _transaction.Abort(); _transaction.Dispose(); _transaction = null; if (hr < 0) { if (exceptionHandling) { ProcessResults(hr); } else { SafeNativeMethods.Wrapper.ClearErrorInfo(); } } } return hr; } internal static OleDbTransaction TransactionLast(OleDbTransaction head) { if (null != head._nestedTransaction) { OleDbTransaction current = (OleDbTransaction)head._nestedTransaction.Target; if ((null != current) && head._nestedTransaction.IsAlive) { return TransactionLast(current); } } return head; } internal static OleDbTransaction TransactionUpdate(OleDbTransaction transaction) { if ((null != transaction) && (null == transaction._transaction)) { return null; } return transaction; } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #nullable enable using System; using System.IO; using System.Management.Automation; using System.Reflection; using System.Runtime.InteropServices; namespace Microsoft.PowerShell { /// <summary> /// Defines an entry point for the .NET CLI "powershell" app. /// </summary> public sealed class ManagedPSEntry { #if UNIX /// <summary> /// Exception to signify an early startup failure. /// </summary> private sealed class StartupException : Exception { /// <summary> /// Construct a new startup exception instance. /// </summary> /// <param name="callName">The name of the native call that failed.</param> /// <param name="exitCode">The exit code the native call returned.</param> public StartupException(string callName, int exitCode) { CallName = callName; ExitCode = exitCode; } /// <summary> /// The name of the native call that failed. /// </summary> public string CallName { get; } /// <summary> /// The exit code returned by the failed native call. /// </summary> public int ExitCode { get; } } // Environment variable used to short circuit second login check private const string LOGIN_ENV_VAR_NAME = "__PWSH_LOGIN_CHECKED"; private const string LOGIN_ENV_VAR_VALUE = "1"; // Linux p/Invoke constants private const int LINUX_PATH_MAX = 4096; // MacOS p/Invoke constants private const int MACOS_CTL_KERN = 1; private const int MACOS_KERN_ARGMAX = 8; private const int MACOS_KERN_PROCARGS2 = 49; private const int MACOS_PROC_PIDPATHINFO_MAXSIZE = 4096; #endif /// <summary> /// Starts the managed MSH. /// </summary> /// <param name="args"> /// Command line arguments to the managed MSH /// </param> public static int Main(string[] args) { #if UNIX AttemptExecPwshLogin(args); #endif return UnmanagedPSEntry.Start(args, args.Length); } #if UNIX /// <summary> /// Checks whether pwsh has been started as a login shell /// and if so, proceeds with the login process. /// This method will return early if pwsh was not started as a login shell /// and will throw if it detects a native call has failed. /// In the event of success, we use an exec() call, so this method never returns. /// </summary> /// <param name="args">The startup arguments to pwsh.</param> private static void AttemptExecPwshLogin(string[] args) { // If the login environment variable is set, we have already done the login logic and have been exec'd if (Environment.GetEnvironmentVariable(LOGIN_ENV_VAR_NAME) != null) { Environment.SetEnvironmentVariable(LOGIN_ENV_VAR_NAME, null); return; } bool isLinux = Platform.IsLinux; // The first byte (ASCII char) of the name of this process, used to detect '-' for login byte procNameFirstByte; // The path to the executable this process was started from string? pwshPath; // On Linux, we can simply use the /proc filesystem if (isLinux) { // Read the process name byte using (FileStream fs = File.OpenRead("/proc/self/cmdline")) { procNameFirstByte = (byte)fs.ReadByte(); } // Run login detection logic if (!IsLogin(procNameFirstByte, args)) { return; } // Read the symlink to the startup executable IntPtr linkPathPtr = Marshal.AllocHGlobal(LINUX_PATH_MAX); IntPtr bufSize = ReadLink("/proc/self/exe", linkPathPtr, (UIntPtr)LINUX_PATH_MAX); pwshPath = Marshal.PtrToStringAnsi(linkPathPtr, (int)bufSize); Marshal.FreeHGlobal(linkPathPtr); if (pwshPath == null) { throw new ArgumentNullException(nameof(pwshPath)); } // exec pwsh ThrowOnFailure("exec", ExecPwshLogin(args, pwshPath, isMacOS: false)); return; } // At this point, we are on macOS // Set up the mib array and the query for process maximum args size Span<int> mib = stackalloc int[3]; int mibLength = 2; mib[0] = MACOS_CTL_KERN; mib[1] = MACOS_KERN_ARGMAX; int size = IntPtr.Size / 2; int argmax = 0; // Get the process args size unsafe { fixed (int *mibptr = mib) { ThrowOnFailure(nameof(argmax), SysCtl(mibptr, mibLength, &argmax, &size, IntPtr.Zero, 0)); } } // Get the PID so we can query this process' args int pid = GetPid(); // The following logic is based on https://gist.github.com/nonowarn/770696 // Now read the process args into the allocated space IntPtr procargs = Marshal.AllocHGlobal(argmax); IntPtr executablePathPtr = IntPtr.Zero; try { mib[0] = MACOS_CTL_KERN; mib[1] = MACOS_KERN_PROCARGS2; mib[2] = pid; mibLength = 3; unsafe { fixed (int *mibptr = mib) { ThrowOnFailure(nameof(procargs), SysCtl(mibptr, mibLength, procargs.ToPointer(), &argmax, IntPtr.Zero, 0)); } // The memory block we're reading is a series of null-terminated strings // that looks something like this: // // | argc | <int> // | exec_path | ... \0 // | argv[0] | ... \0 // | argv[1] | ... \0 // ... // // We care about argv[0], since that's the name the process was started with. // If argv[0][0] == '-', we have been invoked as login. // Doing this, the buffer we populated also recorded `exec_path`, // which is the path to our executable `pwsh`. // We can reuse this value later to prevent needing to call a .NET API // to generate our exec invocation. // We don't care about argc's value, since argv[0] must always exist. // Skip over argc, but remember where exec_path is for later executablePathPtr = IntPtr.Add(procargs, sizeof(int)); // Skip over exec_path byte *argvPtr = (byte *)executablePathPtr; while (*argvPtr != 0) { argvPtr++; } while (*argvPtr == 0) { argvPtr++; } // First char in argv[0] procNameFirstByte = *argvPtr; } if (!IsLogin(procNameFirstByte, args)) { return; } // Get the pwshPath from exec_path pwshPath = Marshal.PtrToStringAnsi(executablePathPtr); if (pwshPath == null) { throw new ArgumentNullException(nameof(pwshPath)); } // exec pwsh ThrowOnFailure("exec", ExecPwshLogin(args, pwshPath, isMacOS: true)); } finally { Marshal.FreeHGlobal(procargs); } } /// <summary> /// Checks args to see if -Login has been specified. /// </summary> /// <param name="procNameFirstByte">The first byte of the name of the currently running process.</param> /// <param name="args">Arguments passed to the program.</param> /// <returns></returns> private static bool IsLogin( byte procNameFirstByte, string[] args) { // Process name starting with '-' means this is a login shell if (procNameFirstByte == 0x2D) { return true; } // Look at the first parameter to see if it is -Login // NOTE: -Login is only supported as the first parameter to PowerShell return args.Length > 0 && args[0].Length > 1 && args[0][0] == '-' && IsParam(args[0], "login", "LOGIN"); } /// <summary> /// Determines if a given parameter is the one we're looking for. /// Assumes any prefix determines that parameter (true for -l, -c and -f). /// </summary> /// <param name="arg">The argument to check.</param> /// <param name="paramToCheck">The lowercase name of the parameter to check.</param> /// <param name="paramToCheckUpper">The uppercase name of the parameter to check.</param> /// <returns></returns> private static bool IsParam( string arg, string paramToCheck, string paramToCheckUpper) { // Quick fail if the argument is longer than the parameter if (arg.Length > paramToCheck.Length + 1) { return false; } // Check arg chars in order and allow prefixes for (int i = 1; i < arg.Length; i++) { if (arg[i] != paramToCheck[i - 1] && arg[i] != paramToCheckUpper[i - 1]) { return false; } } return true; } /// <summary> /// Create the exec call to /bin/{z}sh -l -c 'exec pwsh "$@"' and run it. /// </summary> /// <param name="args">The argument vector passed to pwsh.</param> /// <param name="isMacOS">True if we are running on macOS.</param> /// <param name="pwshPath">Absolute path to the pwsh executable.</param> /// <returns> /// The exit code of exec if it fails. /// If exec succeeds, this process is overwritten so we never actually return. /// </returns> private static int ExecPwshLogin(string[] args, string pwshPath, bool isMacOS) { // Create input for /bin/sh that execs pwsh int quotedPwshPathLength = GetQuotedPathLength(pwshPath); string pwshInvocation = string.Create( quotedPwshPathLength + 10, // exec '{pwshPath}' "$@" (pwshPath, quotedPwshPathLength), CreatePwshInvocation); // Set up the arguments for '/bin/sh'. // We need to add 5 slots for the '/bin/sh' invocation parts, plus 1 slot for the null terminator at the end var execArgs = new string?[args.Length + 6]; // The command arguments // First argument is the command name. // Even when executing 'zsh', we want to set this to '/bin/sh' // because this tells 'zsh' to run in sh emulation mode (it examines $0) execArgs[0] = "/bin/sh"; execArgs[1] = "-l"; // Login flag execArgs[2] = "-c"; // Command parameter execArgs[3] = pwshInvocation; // Command to execute // The /bin/sh option spec looks like: // sh -c command_string [command_name [argument...]] // We must provide a command_name before arguments, // but this is never used since "$@" takes argv[1] - argv[n] // and the `exec` builtin provides its own argv[0]. // See https://pubs.opengroup.org/onlinepubs/9699919799.2016edition/ // // Since command_name is ignored and we can't use null (it's the terminator) // we use empty string execArgs[4] = string.Empty; // Add the arguments passed to pwsh on the end. args.CopyTo(execArgs, 5); // A null is required by exec. execArgs[execArgs.Length - 1] = null; // We can't use Environment.SetEnvironmentVariable() here. // See https://github.com/dotnet/corefx/issues/40130#issuecomment-519420648. ThrowOnFailure("setenv", SetEnv(LOGIN_ENV_VAR_NAME, LOGIN_ENV_VAR_VALUE, overwrite: true)); // On macOS, sh doesn't support login, so we run /bin/zsh in sh emulation mode. if (isMacOS) { return Exec("/bin/zsh", execArgs); } return Exec("/bin/sh", execArgs); } /// <summary> /// Gets what the length of the given string will be if it's /// quote escaped for /bin/sh. /// </summary> /// <param name="str">The string to quote escape.</param> /// <returns>The length of the string when it's quote escaped.</returns> private static int GetQuotedPathLength(string str) { int length = 2; foreach (char c in str) { length++; if (c == '\'') { length++; } } return length; } /// <summary> /// Implements a SpanAction&lt;T&gt; for string.Create() /// that builds the shell invocation for the login pwsh session. /// </summary> /// <param name="strBuf">The buffer of the string to be created.</param> /// <param name="invocationInfo">Information used to build the required string.</param> private static void CreatePwshInvocation( Span<char> strBuf, (string path, int quotedLength) invocationInfo) { // "exec " const string prefix = "exec "; prefix.AsSpan().CopyTo(strBuf); // The quoted path to pwsh, like "'/opt/microsoft/powershell/7/pwsh'" int i = prefix.Length; Span<char> pathSpan = strBuf.Slice(i, invocationInfo.quotedLength); QuoteAndWriteToSpan(invocationInfo.path, pathSpan); i += invocationInfo.quotedLength; // ' "$@"' the argument vector splat to pass pwsh arguments through const string suffix = " \"$@\""; Span<char> bufSuffix = strBuf.Slice(i); suffix.AsSpan().CopyTo(bufSuffix); } /// <summary> /// Quotes (and sh quote escapes) a string and writes it to the given span. /// </summary> /// <param name="arg">The string to quote.</param> /// <param name="span">The span to write to.</param> private static void QuoteAndWriteToSpan(string arg, Span<char> span) { span[0] = '\''; int i = 0; int j = 1; for (; i < arg.Length; i++, j++) { char c = arg[i]; if (c == '\'') { // /bin/sh quote escaping uses backslashes span[j] = '\\'; j++; } span[j] = c; } span[j] = '\''; } /// <summary> /// If the given exit code is negative, throws a StartupException. /// </summary> /// <param name="call">The native call that was attempted.</param> /// <param name="code">The exit code it returned.</param> private static void ThrowOnFailure(string call, int code) { if (code < 0) { code = Marshal.GetLastWin32Error(); Console.Error.WriteLine($"Call to '{call}' failed with errno {code}"); throw new StartupException(call, code); } } /// <summary> /// The `execv` POSIX syscall we use to exec /bin/sh. /// </summary> /// <param name="path">The path to the executable to exec.</param> /// <param name="args"> /// The arguments to send through to the executable. /// Array must have its final element be null. /// </param> /// <returns> /// An exit code if exec failed, but if successful the calling process will be overwritten. /// </returns> [DllImport("libc", EntryPoint = "execv", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)] private static extern int Exec(string path, string?[] args); /// <summary> /// The `readlink` POSIX syscall we use to read the symlink from /proc/self/exe /// to get the executable path of pwsh on Linux. /// </summary> /// <param name="pathname">The path to the symlink to read.</param> /// <param name="buf">Pointer to a buffer to fill with the result.</param> /// <param name="size">The size of the buffer we have supplied.</param> /// <returns>The number of bytes placed in the buffer.</returns> [DllImport("libc", EntryPoint = "readlink", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)] private static extern IntPtr ReadLink(string pathname, IntPtr buf, UIntPtr size); /// <summary> /// The `getpid` POSIX syscall we use to quickly get the current process PID on macOS. /// </summary> /// <returns>The pid of the current process.</returns> [DllImport("libc", EntryPoint = "getpid", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)] private static extern int GetPid(); /// <summary> /// The `setenv` POSIX syscall used to set an environment variable in the process. /// </summary> /// <param name="name">The name of the environment variable.</param> /// <param name="value">The value of the environment variable.</param> /// <param name="overwrite">If true, will overwrite an existing environment variable of the same name.</param> /// <returns>0 if successful, -1 on error. errno indicates the reason for failure.</returns> [DllImport("libc", EntryPoint = "setenv", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)] private static extern int SetEnv(string name, string value, bool overwrite); /// <summary> /// The `sysctl` BSD sycall used to get system information on macOS. /// </summary> /// <param name="mib">The Management Information Base name, used to query information.</param> /// <param name="mibLength">The length of the MIB name.</param> /// <param name="oldp">The object passed out of sysctl (may be null)</param> /// <param name="oldlenp">The size of the object passed out of sysctl.</param> /// <param name="newp">The object passed in to sysctl.</param> /// <param name="newlenp">The length of the object passed in to sysctl.</param> /// <returns></returns> [DllImport("libc", EntryPoint = "sysctl", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi, SetLastError = true)] private static extern unsafe int SysCtl(int *mib, int mibLength, void *oldp, int *oldlenp, IntPtr newp, int newlenp); #endif } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; namespace Dirigent { /// <summary> /// App status shared among all Dirigent participants. /// </summary> [ProtoBuf.ProtoContract] [DataContract] public class AppState { [Flags] enum FL { Started = 1 << 0, StartFailed = 1 << 1, Running = 1 << 2, Killed = 1 << 3, Dying = 1 << 4, Restarting = 1 << 5, Initialized = 1 << 6, PlanApplied = 1 << 7, //Disabled = 1 << 8, } [ProtoBuf.ProtoMember( 1 )] FL flags; [ProtoBuf.ProtoMember( 2 )] int exitCode; // UTC time of last update, recalculated to local time (as the clock migh differ on different computers) // On Agent, the agent's UTC time of last update // On Master, the UTC time of last update recalculated to master's local time // On Gui, the UTC time of last update recalculated to gui's local time [ProtoBuf.ProtoMember( 3 )] DateTime lastChange = DateTime.UtcNow; [ProtoBuf.ProtoMember( 4 )] int cpu; // percentage of CPU usage [ProtoBuf.ProtoMember( 5 )] int gpu; // percentage of GPU usage [ProtoBuf.ProtoMember( 6 )] int memory; // MBytes of memory allocated [ProtoBuf.ProtoMember( 7 )] string? planName; // in what plan's context the app was started public const int RESTARTS_UNLIMITED = -1; // keep restarting forever public const int RESTARTS_UNITIALIZED = -2; // not yet set, will be set by the AppRestarter on first app restart, based on app's configuration [ProtoBuf.ProtoMember( 8 )] int restartsRemaining = RESTARTS_UNITIALIZED; bool Is( FL value ) { return ( flags & value ) == value; } void Set( FL value, bool toSet ) { if( toSet ) flags |= value; else flags &= ~value; changed(); } /// <summary> /// process was launched successfully /// </summary> public bool Started { get { return Is( FL.Started ); } set { Set( FL.Started, value ); } } /// <summary> /// process was launched but failed to start /// </summary> public bool StartFailed { get { return Is( FL.StartFailed ); } set { Set( FL.StartFailed, value ); } } /// <summary> /// process is currently running /// </summary> public bool Running { get { return Is( FL.Running ); } set { Set( FL.Running, value ); } } /// <summary> /// forced to terminate by KillApp request (not by a KillPlan) /// </summary> public bool Killed { get { return Is( FL.Killed ); } set { Set( FL.Killed, value ); changed(); } } /// <summary> /// Still dying (after termination request) /// </summary> public bool Dying { get { return Is( FL.Dying ); } set { Set( FL.Dying, value ); changed(); } } /// <summary> /// Just being restarted (waiting until dies in order to be lanuched again) /// </summary> public bool Restarting { get { return Is( FL.Restarting ); } set { Set( FL.Restarting, value ); changed(); } } /// <summary> /// Process init condition satisfied; /// /// By default true upon launching but can be immediately reset by a freshly instantiated AppWatcher acting like an InitDetector. /// This is to avoid app to stay in unitialized if an Initdetector-class watcher is not defined /// </summary> public bool Initialized { get { return Is( FL.Initialized ); } set { Set( FL.Initialized, value ); changed(); } } /// <summary> /// Indicates that the app has been attempted to start a part of some plan. /// Just an indication for being able to show the "Planned" state, not affecting any logic. /// Availale to any endpoint receiving app states. NOT USED BY MASTER! /// WARNING: This is trying to mimic the value of Master's AppDef.PlanApplied variable. /// As master does not publish its internal PlanApplied, this is just an approximation. /// BUT (theoretically) might be set also on different occasion when /// starting the app with non-empty planName from some reason! /// </summary> public bool PlanApplied { get { return Is( FL.PlanApplied ); } set { Set( FL.PlanApplied, value ); changed(); } } ///// <summary> ///// Whether the app has been disabled from execution as part of the plan; ///// This is set by the owner ///// </summary> //public bool Disabled //{ // get { return Is( FL.Disabled ); } // set { Set( FL.Disabled, value ); } //} /// <summary> /// process exit code; valid only if is Started && !Running && !Killed /// </summary> public int ExitCode { get { return exitCode; } set { exitCode = value; } } /// <summary> /// Timne of the last change in the application state. /// </summary> public DateTime LastChange { get { return lastChange; } set { lastChange = value; } } /// <summary> /// percentage of CPU usage /// </summary> public int CPU { get { return cpu; } set { cpu = value; } } /// <summary> /// percentage of GPU usage /// </summary> public int GPU { get { return gpu; } set { gpu = value; } } /// <summary> /// MBytes of memory allocated /// </summary> public int Memory { get { return memory; } set { memory = value; } } /// <summary> /// How many restart tries to make before giving up /// </summary> public int RestartsRemaining { get { return restartsRemaining; } set { restartsRemaining = value; } } /// <summary> /// In what plan's context the app was started. Current plan for apps launched directly via LaunchApp. /// </summary> public string? PlanName { get { return planName; } set { planName = value; changed(); } } void changed() { lastChange = DateTime.UtcNow; } public bool IsOffline => DateTime.UtcNow - lastChange > TimeSpan.FromSeconds(3); public static AppState GetDefault( AppDef ad ) { return new AppState() { Initialized = false, Running = false, Started = false, Dying = false, //Disabled = ad.Disabled lastChange = DateTime.MinValue }; } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using System.Text; using System.Xml; using System.Collections.Generic; using System.IO; using Nini.Config; using OpenSim.Framework; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Server.Handlers.Base; using log4net; using OpenMetaverse; namespace OpenSim.Server.Handlers.Asset { public class XInventoryInConnector : ServiceConnector { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; private string m_ConfigName = "InventoryService"; public XInventoryInConnector(IConfigSource config, IHttpServer server, string configName) : base(config, server, configName) { if (configName != String.Empty) m_ConfigName = configName; m_log.DebugFormat("[XInventoryInConnector]: Starting with config name {0}", m_ConfigName); IConfig serverConfig = config.Configs[m_ConfigName]; if (serverConfig == null) throw new Exception(String.Format("No section '{0}' in config file", m_ConfigName)); string inventoryService = serverConfig.GetString("LocalServiceModule", String.Empty); if (inventoryService == String.Empty) throw new Exception("No InventoryService in config file"); Object[] args = new Object[] { config, m_ConfigName }; m_InventoryService = ServerUtils.LoadPlugin<IInventoryService>(inventoryService, args); server.AddStreamHandler(new XInventoryConnectorPostHandler(m_InventoryService)); } } public class XInventoryConnectorPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IInventoryService m_InventoryService; public XInventoryConnectorPostHandler(IInventoryService service) : base("POST", "/xinventory") { m_InventoryService = service; } public override byte[] Handle(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse 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, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); request.Remove("METHOD"); switch (method) { case "CREATEUSERINVENTORY": return HandleCreateUserInventory(request); case "GETINVENTORYSKELETON": return HandleGetInventorySkeleton(request); case "GETUSERINVENTORY": return HandleGetUserInventory(request); case "GETROOTFOLDER": return HandleGetRootFolder(request); case "GETFOLDERFORTYPE": return HandleGetFolderForType(request); case "GETFOLDERCONTENT": return HandleGetFolderContent(request); case "GETFOLDERITEMS": return HandleGetFolderItems(request); case "ADDFOLDER": return HandleAddFolder(request); case "UPDATEFOLDER": return HandleUpdateFolder(request); case "MOVEFOLDER": return HandleMoveFolder(request); case "DELETEFOLDERS": return HandleDeleteFolders(request); case "PURGEFOLDER": return HandlePurgeFolder(request); case "ADDITEM": return HandleAddItem(request); case "UPDATEITEM": return HandleUpdateItem(request); case "MOVEITEMS": return HandleMoveItems(request); case "DELETEITEMS": return HandleDeleteItems(request); case "GETITEM": return HandleGetItem(request); case "GETFOLDER": return HandleGetFolder(request); case "GETACTIVEGESTURES": return HandleGetActiveGestures(request); case "GETASSETPERMISSIONS": return HandleGetAssetPermissions(request); } m_log.DebugFormat("[XINVENTORY HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[XINVENTORY HANDLER]: Exception {0}", e.StackTrace); } return FailureResult(); } private byte[] FailureResult() { return BoolResult(false); } private byte[] SuccessResult() { return BoolResult(true); } private byte[] BoolResult(bool value) { 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(value.ToString())); 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(); } byte[] HandleCreateUserInventory(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); if (m_InventoryService.CreateUserInventory(new UUID(request["PRINCIPAL"].ToString()))) result["RESULT"] = "True"; else result["RESULT"] = "False"; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetInventorySkeleton(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); if (!request.ContainsKey("PRINCIPAL")) return FailureResult(); List<InventoryFolderBase> folders = m_InventoryService.GetInventorySkeleton(new UUID(request["PRINCIPAL"].ToString())); Dictionary<string, object> sfolders = new Dictionary<string, object>(); if (folders != null) { int i = 0; foreach (InventoryFolderBase f in folders) { sfolders["folder_" + i.ToString()] = EncodeFolder(f); i++; } } result["FOLDERS"] = sfolders; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetUserInventory(Dictionary<string, object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryCollection icoll = m_InventoryService.GetUserInventory(principal); if (icoll != null) { Dictionary<string, object> folders = new Dictionary<string, object>(); int i = 0; if (icoll.Folders != null) { foreach (InventoryFolderBase f in icoll.Folders) { folders["folder_" + i.ToString()] = EncodeFolder(f); i++; } result["FOLDERS"] = folders; } if (icoll.Items != null) { i = 0; Dictionary<string, object> items = new Dictionary<string, object>(); foreach (InventoryItemBase it in icoll.Items) { items["item_" + i.ToString()] = EncodeItem(it); i++; } result["ITEMS"] = items; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetRootFolder(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase rfolder = m_InventoryService.GetRootFolder(principal); if (rfolder != null) result["folder"] = EncodeFolder(rfolder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolderForType(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); int type = 0; Int32.TryParse(request["TYPE"].ToString(), out type); InventoryFolderBase folder = m_InventoryService.GetFolderForType(principal, (AssetType)type); if (folder != null) result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolderContent(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID folderID = UUID.Zero; UUID.TryParse(request["FOLDER"].ToString(), out folderID); InventoryCollection icoll = m_InventoryService.GetFolderContent(principal, folderID); if (icoll != null) { Dictionary<string, object> folders = new Dictionary<string, object>(); int i = 0; if (icoll.Folders != null) { foreach (InventoryFolderBase f in icoll.Folders) { folders["folder_" + i.ToString()] = EncodeFolder(f); i++; } result["FOLDERS"] = folders; } if (icoll.Items != null) { i = 0; Dictionary<string, object> items = new Dictionary<string, object>(); foreach (InventoryItemBase it in icoll.Items) { items["item_" + i.ToString()] = EncodeItem(it); i++; } result["ITEMS"] = items; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolderItems(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID folderID = UUID.Zero; UUID.TryParse(request["FOLDER"].ToString(), out folderID); List<InventoryItemBase> items = m_InventoryService.GetFolderItems(principal, folderID); Dictionary<string, object> sitems = new Dictionary<string, object>(); if (items != null) { int i = 0; foreach (InventoryItemBase item in items) { sitems["item_" + i.ToString()] = EncodeItem(item); i++; } } result["ITEMS"] = sitems; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleAddFolder(Dictionary<string,object> request) { InventoryFolderBase folder = BuildFolder(request); if (m_InventoryService.AddFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleUpdateFolder(Dictionary<string,object> request) { InventoryFolderBase folder = BuildFolder(request); if (m_InventoryService.UpdateFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleMoveFolder(Dictionary<string,object> request) { UUID parentID = UUID.Zero; UUID.TryParse(request["ParentID"].ToString(), out parentID); UUID folderID = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out folderID); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); InventoryFolderBase folder = new InventoryFolderBase(folderID, "", principal, parentID); if (m_InventoryService.MoveFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleDeleteFolders(Dictionary<string,object> request) { UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<string> slist = (List<string>)request["FOLDERS"]; List<UUID> uuids = new List<UUID>(); foreach (string s in slist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) uuids.Add(u); } if (m_InventoryService.DeleteFolders(principal, uuids)) return SuccessResult(); else return FailureResult(); } byte[] HandlePurgeFolder(Dictionary<string,object> request) { UUID folderID = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out folderID); InventoryFolderBase folder = new InventoryFolderBase(folderID); if (m_InventoryService.PurgeFolder(folder)) return SuccessResult(); else return FailureResult(); } byte[] HandleAddItem(Dictionary<string,object> request) { InventoryItemBase item = BuildItem(request); if (m_InventoryService.AddItem(item)) return SuccessResult(); else return FailureResult(); } byte[] HandleUpdateItem(Dictionary<string,object> request) { InventoryItemBase item = BuildItem(request); if (m_InventoryService.UpdateItem(item)) return SuccessResult(); else return FailureResult(); } byte[] HandleMoveItems(Dictionary<string,object> request) { List<string> idlist = (List<string>)request["IDLIST"]; List<string> destlist = (List<string>)request["DESTLIST"]; UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<InventoryItemBase> items = new List<InventoryItemBase>(); int n = 0; try { foreach (string s in idlist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) { UUID fid = UUID.Zero; if (UUID.TryParse(destlist[n++], out fid)) { InventoryItemBase item = new InventoryItemBase(u, principal); item.Folder = fid; items.Add(item); } } } } catch (Exception e) { m_log.DebugFormat("[XINVENTORY IN CONNECTOR]: Exception in HandleMoveItems: {0}", e.Message); return FailureResult(); } if (m_InventoryService.MoveItems(principal, items)) return SuccessResult(); else return FailureResult(); } byte[] HandleDeleteItems(Dictionary<string,object> request) { UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<string> slist = (List<string>)request["ITEMS"]; List<UUID> uuids = new List<UUID>(); foreach (string s in slist) { UUID u = UUID.Zero; if (UUID.TryParse(s, out u)) uuids.Add(u); } if (m_InventoryService.DeleteItems(principal, uuids)) return SuccessResult(); else return FailureResult(); } byte[] HandleGetItem(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID id = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out id); InventoryItemBase item = new InventoryItemBase(id); item = m_InventoryService.GetItem(item); if (item != null) result["item"] = EncodeItem(item); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetFolder(Dictionary<string,object> request) { Dictionary<string, object> result = new Dictionary<string, object>(); UUID id = UUID.Zero; UUID.TryParse(request["ID"].ToString(), out id); InventoryFolderBase folder = new InventoryFolderBase(id); folder = m_InventoryService.GetFolder(folder); if (folder != null) result["folder"] = EncodeFolder(folder); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetActiveGestures(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); List<InventoryItemBase> gestures = m_InventoryService.GetActiveGestures(principal); Dictionary<string, object> items = new Dictionary<string, object>(); if (gestures != null) { int i = 0; foreach (InventoryItemBase item in gestures) { items["item_" + i.ToString()] = EncodeItem(item); i++; } } result["ITEMS"] = items; string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] HandleGetAssetPermissions(Dictionary<string,object> request) { Dictionary<string,object> result = new Dictionary<string,object>(); UUID principal = UUID.Zero; UUID.TryParse(request["PRINCIPAL"].ToString(), out principal); UUID assetID = UUID.Zero; UUID.TryParse(request["ASSET"].ToString(), out assetID); int perms = m_InventoryService.GetAssetPermissions(principal, assetID); result["RESULT"] = perms.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[XXX]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } private Dictionary<string, object> EncodeFolder(InventoryFolderBase f) { Dictionary<string, object> ret = new Dictionary<string, object>(); ret["ParentID"] = f.ParentID.ToString(); ret["Type"] = f.Type.ToString(); ret["Version"] = f.Version.ToString(); ret["Name"] = f.Name; ret["Owner"] = f.Owner.ToString(); ret["ID"] = f.ID.ToString(); return ret; } private Dictionary<string, object> EncodeItem(InventoryItemBase item) { Dictionary<string, object> ret = new Dictionary<string, object>(); ret["AssetID"] = item.AssetID.ToString(); ret["AssetType"] = item.AssetType.ToString(); ret["BasePermissions"] = item.BasePermissions.ToString(); ret["CreationDate"] = item.CreationDate.ToString(); if (item.CreatorId != null) ret["CreatorId"] = item.CreatorId.ToString(); else ret["CreatorId"] = String.Empty; if (item.CreatorData != null) ret["CreatorData"] = item.CreatorData; else ret["CreatorData"] = String.Empty; ret["CurrentPermissions"] = item.CurrentPermissions.ToString(); ret["Description"] = item.Description.ToString(); ret["EveryOnePermissions"] = item.EveryOnePermissions.ToString(); ret["Flags"] = item.Flags.ToString(); ret["Folder"] = item.Folder.ToString(); ret["GroupID"] = item.GroupID.ToString(); ret["GroupOwned"] = item.GroupOwned.ToString(); ret["GroupPermissions"] = item.GroupPermissions.ToString(); ret["ID"] = item.ID.ToString(); ret["InvType"] = item.InvType.ToString(); ret["Name"] = item.Name.ToString(); ret["NextPermissions"] = item.NextPermissions.ToString(); ret["Owner"] = item.Owner.ToString(); ret["SalePrice"] = item.SalePrice.ToString(); ret["SaleType"] = item.SaleType.ToString(); return ret; } private InventoryFolderBase BuildFolder(Dictionary<string,object> data) { InventoryFolderBase folder = new InventoryFolderBase(); folder.ParentID = new UUID(data["ParentID"].ToString()); folder.Type = short.Parse(data["Type"].ToString()); folder.Version = ushort.Parse(data["Version"].ToString()); folder.Name = data["Name"].ToString(); folder.Owner = new UUID(data["Owner"].ToString()); folder.ID = new UUID(data["ID"].ToString()); return folder; } private InventoryItemBase BuildItem(Dictionary<string,object> data) { InventoryItemBase item = new InventoryItemBase(); item.AssetID = new UUID(data["AssetID"].ToString()); item.AssetType = int.Parse(data["AssetType"].ToString()); item.Name = data["Name"].ToString(); item.Owner = new UUID(data["Owner"].ToString()); item.ID = new UUID(data["ID"].ToString()); item.InvType = int.Parse(data["InvType"].ToString()); item.Folder = new UUID(data["Folder"].ToString()); item.CreatorId = data["CreatorId"].ToString(); item.CreatorData = data["CreatorData"].ToString(); item.Description = data["Description"].ToString(); item.NextPermissions = uint.Parse(data["NextPermissions"].ToString()); item.CurrentPermissions = uint.Parse(data["CurrentPermissions"].ToString()); item.BasePermissions = uint.Parse(data["BasePermissions"].ToString()); item.EveryOnePermissions = uint.Parse(data["EveryOnePermissions"].ToString()); item.GroupPermissions = uint.Parse(data["GroupPermissions"].ToString()); item.GroupID = new UUID(data["GroupID"].ToString()); item.GroupOwned = bool.Parse(data["GroupOwned"].ToString()); item.SalePrice = int.Parse(data["SalePrice"].ToString()); item.SaleType = byte.Parse(data["SaleType"].ToString()); item.Flags = uint.Parse(data["Flags"].ToString()); item.CreationDate = int.Parse(data["CreationDate"].ToString()); return item; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.ComponentModel; using System.Diagnostics; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.Net.NetworkInformation { public partial class Ping { private static readonly SafeWaitHandle s_nullSafeWaitHandle = new SafeWaitHandle(IntPtr.Zero, true); private static readonly object s_socketInitializationLock = new object(); private static bool s_socketInitialized; private int _sendSize = 0; // Needed to determine what the reply size is for ipv6 in callback. private bool _ipv6 = false; private ManualResetEvent _pingEvent; private RegisteredWaitHandle _registeredWait; private SafeLocalAllocHandle _requestBuffer; private SafeLocalAllocHandle _replyBuffer; private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV4; private Interop.IpHlpApi.SafeCloseIcmpHandle _handlePingV6; private TaskCompletionSource<PingReply> _taskCompletionSource; private PingReply SendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options) { // Since isAsync == false, DoSendPingCore will execute synchronously and return a completed // Task - so no blocking here return DoSendPingCore(address, buffer, timeout, options, isAsync: false).GetAwaiter().GetResult(); } private Task<PingReply> SendPingAsyncCore(IPAddress address, byte[] buffer, int timeout, PingOptions options) { // Since isAsync == true, DoSendPingCore will execute asynchronously and return an active Task return DoSendPingCore(address, buffer, timeout, options, isAsync: true); } // Any exceptions that escape synchronously will be caught by the caller and wrapped in a PingException. // We do not need to or want to capture such exceptions into the returned task. private Task<PingReply> DoSendPingCore(IPAddress address, byte[] buffer, int timeout, PingOptions options, bool isAsync) { TaskCompletionSource<PingReply> tcs = null; if (isAsync) { _taskCompletionSource = tcs = new TaskCompletionSource<PingReply>(); } _ipv6 = (address.AddressFamily == AddressFamily.InterNetworkV6); _sendSize = buffer.Length; // Cache correct handle. InitialiseIcmpHandle(); if (_replyBuffer == null) { _replyBuffer = SafeLocalAllocHandle.LocalAlloc(MaxUdpPacket); } int error; try { if (isAsync) { RegisterWaitHandle(); } SetUnmanagedStructures(buffer); error = SendEcho(address, buffer, timeout, options, isAsync); } catch { Cleanup(isAsync); throw; } if (error == 0) { error = Marshal.GetLastWin32Error(); // Only skip Async IO Pending error value. if (!isAsync || error != Interop.IpHlpApi.ERROR_IO_PENDING) { Cleanup(isAsync); IPStatus status = GetStatusFromCode(error); return Task.FromResult(new PingReply(address, default, status, default, Array.Empty<byte>())); } } if (isAsync) return tcs.Task; Cleanup(isAsync); return Task.FromResult(CreatePingReply()); } private void RegisterWaitHandle() { if (_pingEvent == null) { _pingEvent = new ManualResetEvent(false); } else { _pingEvent.Reset(); } _registeredWait = ThreadPool.RegisterWaitForSingleObject(_pingEvent, (state, _) => ((Ping)state).PingCallback(), this, -1, true); } private void UnregisterWaitHandle() { lock (_lockObject) { if (_registeredWait != null) { // If Unregister returns false, it is sufficient to nullify registeredWait // and let its own finalizer clean up later. _registeredWait.Unregister(null); _registeredWait = null; } } } private SafeWaitHandle GetWaitHandle(bool async) { if (async) { return _pingEvent.GetSafeWaitHandle(); } return s_nullSafeWaitHandle; } private void InitialiseIcmpHandle() { if (!_ipv6 && _handlePingV4 == null) { _handlePingV4 = Interop.IpHlpApi.IcmpCreateFile(); if (_handlePingV4.IsInvalid) { _handlePingV4 = null; throw new Win32Exception(); // Gets last error. } } else if (_ipv6 && _handlePingV6 == null) { _handlePingV6 = Interop.IpHlpApi.Icmp6CreateFile(); if (_handlePingV6.IsInvalid) { _handlePingV6 = null; throw new Win32Exception(); // Gets last error. } } } private int SendEcho(IPAddress address, byte[] buffer, int timeout, PingOptions options, bool isAsync) { Interop.IpHlpApi.IPOptions ipOptions = new Interop.IpHlpApi.IPOptions(options); if (!_ipv6) { return (int)Interop.IpHlpApi.IcmpSendEcho2( _handlePingV4, GetWaitHandle(isAsync), IntPtr.Zero, IntPtr.Zero, #pragma warning disable CS0618 // Address is marked obsolete (uint)address.Address, #pragma warning restore CS0618 _requestBuffer, (ushort)buffer.Length, ref ipOptions, _replyBuffer, MaxUdpPacket, (uint)timeout); } IPEndPoint ep = new IPEndPoint(address, 0); Internals.SocketAddress remoteAddr = IPEndPointExtensions.Serialize(ep); byte[] sourceAddr = new byte[28]; return (int)Interop.IpHlpApi.Icmp6SendEcho2( _handlePingV6, GetWaitHandle(isAsync), IntPtr.Zero, IntPtr.Zero, sourceAddr, remoteAddr.Buffer, _requestBuffer, (ushort)buffer.Length, ref ipOptions, _replyBuffer, MaxUdpPacket, (uint)timeout); } private PingReply CreatePingReply() { SafeLocalAllocHandle buffer = _replyBuffer; // Marshals and constructs new reply. if (_ipv6) { Interop.IpHlpApi.Icmp6EchoReply icmp6Reply = Marshal.PtrToStructure<Interop.IpHlpApi.Icmp6EchoReply>(buffer.DangerousGetHandle()); return CreatePingReplyFromIcmp6EchoReply(icmp6Reply, buffer.DangerousGetHandle(), _sendSize); } Interop.IpHlpApi.IcmpEchoReply icmpReply = Marshal.PtrToStructure<Interop.IpHlpApi.IcmpEchoReply>(buffer.DangerousGetHandle()); return CreatePingReplyFromIcmpEchoReply(icmpReply); } private void Cleanup(bool isAsync) { FreeUnmanagedStructures(); if (isAsync) { UnregisterWaitHandle(); } } partial void InternalDisposeCore() { if (_handlePingV4 != null) { _handlePingV4.Dispose(); _handlePingV4 = null; } if (_handlePingV6 != null) { _handlePingV6.Dispose(); _handlePingV6 = null; } UnregisterWaitHandle(); if (_pingEvent != null) { _pingEvent.Dispose(); _pingEvent = null; } if (_replyBuffer != null) { _replyBuffer.Dispose(); _replyBuffer = null; } } // Private callback invoked when icmpsendecho APIs succeed. private void PingCallback() { TaskCompletionSource<PingReply> tcs = _taskCompletionSource; _taskCompletionSource = null; PingReply reply = null; Exception error = null; bool canceled = false; try { lock (_lockObject) { canceled = _canceled; reply = CreatePingReply(); } } catch (Exception e) { // In case of failure, create a failed event arg. error = new PingException(SR.net_ping, e); } finally { Cleanup(isAsync: true); } // Once we've called Finish, complete the task if (canceled) { tcs.SetCanceled(); } else if (reply != null) { tcs.SetResult(reply); } else { Debug.Assert(error != null); tcs.SetException(error); } } // Copies _requestBuffer into unmanaged memory for async icmpsendecho APIs. private unsafe void SetUnmanagedStructures(byte[] buffer) { _requestBuffer = SafeLocalAllocHandle.LocalAlloc(buffer.Length); byte* dst = (byte*)_requestBuffer.DangerousGetHandle(); for (int i = 0; i < buffer.Length; ++i) { dst[i] = buffer[i]; } } // Releases the unmanaged memory after ping completion. private void FreeUnmanagedStructures() { if (_requestBuffer != null) { _requestBuffer.Dispose(); _requestBuffer = null; } } private static IPStatus GetStatusFromCode(int statusCode) { // Caveat lector: IcmpSendEcho2 doesn't allow us to know for sure if an error code // is an IP Status code or a general win32 error code. This assumes everything under // the base is a win32 error, and everything beyond is an IPStatus. if (statusCode != 0 && statusCode < Interop.IpHlpApi.IP_STATUS_BASE) { throw new Win32Exception(statusCode); } return (IPStatus)statusCode; } private static PingReply CreatePingReplyFromIcmpEchoReply(Interop.IpHlpApi.IcmpEchoReply reply) { const int DontFragmentFlag = 2; IPAddress address = new IPAddress(reply.address); IPStatus ipStatus = GetStatusFromCode((int)reply.status); long rtt; PingOptions options; byte[] buffer; if (ipStatus == IPStatus.Success) { // Only copy the data if we succeed w/ the ping operation. rtt = reply.roundTripTime; options = new PingOptions(reply.options.ttl, (reply.options.flags & DontFragmentFlag) > 0); buffer = new byte[reply.dataSize]; Marshal.Copy(reply.data, buffer, 0, reply.dataSize); } else { rtt = default(long); options = default(PingOptions); buffer = Array.Empty<byte>(); } return new PingReply(address, options, ipStatus, rtt, buffer); } private static PingReply CreatePingReplyFromIcmp6EchoReply(Interop.IpHlpApi.Icmp6EchoReply reply, IntPtr dataPtr, int sendSize) { IPAddress address = new IPAddress(reply.Address.Address, reply.Address.ScopeID); IPStatus ipStatus = GetStatusFromCode((int)reply.Status); long rtt; byte[] buffer; if (ipStatus == IPStatus.Success) { // Only copy the data if we succeed w/ the ping operation. rtt = reply.RoundTripTime; buffer = new byte[sendSize]; Marshal.Copy(dataPtr + 36, buffer, 0, sendSize); } else { rtt = default(long); buffer = Array.Empty<byte>(); } return new PingReply(address, default(PingOptions), ipStatus, rtt, buffer); } static partial void InitializeSockets() { if (!Volatile.Read(ref s_socketInitialized)) { lock (s_socketInitializationLock) { if (!s_socketInitialized) { // Ensure that WSAStartup has been called once per process. // The System.Net.NameResolution contract is responsible with the initialization. Dns.GetHostName(); // Cache some settings locally. s_socketInitialized = true; } } } } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; namespace UMA { /// <summary> /// Utility class for generating texture atlases /// </summary> [Serializable] public class UMAGeneratorCoroutine : WorkerCoroutine { TextureProcessBaseCoroutine textureProcessCoroutine; MaxRectsBinPack packTexture; UMAGeneratorBase umaGenerator; UMAData umaData; Texture[] backUpTexture; bool updateMaterialList; int scaleFactor; MaterialDefinitionComparer comparer = new MaterialDefinitionComparer(); List<UMAData.GeneratedMaterial> generatedMaterials; int rendererCount; List<UMAData.GeneratedMaterial> atlassedMaterials = new List<UMAData.GeneratedMaterial>(20); Dictionary<List<OverlayData>, UMAData.GeneratedMaterial> generatedMaterialLookup; public void Prepare(UMAGeneratorBase _umaGenerator, UMAData _umaData, TextureProcessBaseCoroutine textureProcessCoroutine, bool updateMaterialList, int InitialScaleFactor) { umaGenerator = _umaGenerator; umaData = _umaData; this.textureProcessCoroutine = textureProcessCoroutine; this.updateMaterialList = updateMaterialList; scaleFactor = InitialScaleFactor; } private UMAData.GeneratedMaterial FindOrCreateGeneratedMaterial(UMAMaterial umaMaterial) { if (umaMaterial.materialType == UMAMaterial.MaterialType.Atlas) { foreach (var atlassedMaterial in atlassedMaterials) { if (atlassedMaterial.umaMaterial == umaMaterial) { return atlassedMaterial; } else { if (atlassedMaterial.umaMaterial.Equals(umaMaterial)) { return atlassedMaterial; } } } } var res = new UMAData.GeneratedMaterial(); if (umaMaterial.RequireSeperateRenderer) { res.renderer = rendererCount++; } res.umaMaterial = umaMaterial; res.material = UnityEngine.Object.Instantiate(umaMaterial.material) as Material; res.material.name = umaMaterial.material.name; atlassedMaterials.Add(res); generatedMaterials.Add(res); return res; } protected override void Start() { if (generatedMaterialLookup == null) { generatedMaterialLookup = new Dictionary<List<OverlayData>, UMAData.GeneratedMaterial>(20); } else { generatedMaterialLookup.Clear(); } backUpTexture = umaData.backUpTextures(); umaData.CleanTextures(); generatedMaterials = new List<UMAData.GeneratedMaterial>(20); atlassedMaterials.Clear(); rendererCount = 0; SlotData[] slots = umaData.umaRecipe.slotDataList; for (int i = 0; i < slots.Length; i++) { var slot = slots[i]; if (slot == null) continue; if ((slot.asset.material != null) && (slot.GetOverlay(0) != null)) { if (!slot.asset.material.RequireSeperateRenderer) { // At least one slot that doesn't require a seperate renderer, so we reserve renderer 0 for those. rendererCount = 1; break; } } } for (int i = 0; i < slots.Length; i++) { SlotData slot = slots[i]; if (slot == null) continue; // Let's only add the default overlay if the slot has overlays and NO meshData if ((slot.asset.meshData != null) && (slot.OverlayCount == 0)) { if (umaGenerator.defaultOverlaydata != null) slot.AddOverlay(umaGenerator.defaultOverlaydata); } OverlayData overlay0 = slot.GetOverlay(0); if ((slot.asset.material != null) && (overlay0 != null)) { List<OverlayData> overlayList = slot.GetOverlayList(); UMAData.GeneratedMaterial generatedMaterial; if (!generatedMaterialLookup.TryGetValue(overlayList, out generatedMaterial)) { generatedMaterial = FindOrCreateGeneratedMaterial(slot.asset.material); generatedMaterialLookup.Add(overlayList, generatedMaterial); } int validOverlayCount = 0; for (int j = 0; j < slot.OverlayCount; j++) { var overlay = slot.GetOverlay(j); if (overlay != null) { validOverlayCount++; #if (UNITY_STANDALONE || UNITY_IOS || UNITY_ANDROID || UNITY_PS4 || UNITY_XBOXONE) && !UNITY_2017_3_OR_NEWER //supported platforms for procedural materials if (overlay.isProcedural) overlay.GenerateProceduralTextures(); #endif } } UMAData.MaterialFragment tempMaterialDefinition = new UMAData.MaterialFragment(); tempMaterialDefinition.baseOverlay = new UMAData.textureData(); tempMaterialDefinition.baseOverlay.textureList = overlay0.textureArray; tempMaterialDefinition.baseOverlay.alphaTexture = overlay0.alphaMask; tempMaterialDefinition.baseOverlay.overlayType = overlay0.overlayType; tempMaterialDefinition.umaMaterial = slot.asset.material; tempMaterialDefinition.baseColor = overlay0.colorData.color; tempMaterialDefinition.size = overlay0.pixelCount; tempMaterialDefinition.overlays = new UMAData.textureData[validOverlayCount - 1]; tempMaterialDefinition.overlayColors = new Color32[validOverlayCount - 1]; tempMaterialDefinition.rects = new Rect[validOverlayCount - 1]; tempMaterialDefinition.overlayData = new OverlayData[validOverlayCount]; tempMaterialDefinition.channelMask = new Color[validOverlayCount][]; tempMaterialDefinition.channelAdditiveMask = new Color[validOverlayCount][]; tempMaterialDefinition.overlayData[0] = slot.GetOverlay(0); tempMaterialDefinition.channelMask[0] = slot.GetOverlay(0).colorData.channelMask; tempMaterialDefinition.channelAdditiveMask[0] = slot.GetOverlay(0).colorData.channelAdditiveMask; tempMaterialDefinition.slotData = slot; int overlayID = 0; for (int j = 1; j < slot.OverlayCount; j++) { OverlayData overlay = slot.GetOverlay(j); if (overlay == null) continue; tempMaterialDefinition.rects[overlayID] = overlay.rect; tempMaterialDefinition.overlays[overlayID] = new UMAData.textureData(); tempMaterialDefinition.overlays[overlayID].textureList = overlay.textureArray; tempMaterialDefinition.overlays[overlayID].alphaTexture = overlay.alphaMask; tempMaterialDefinition.overlays[overlayID].overlayType = overlay.overlayType; tempMaterialDefinition.overlayColors[overlayID] = overlay.colorData.color; overlayID++; tempMaterialDefinition.overlayData[overlayID] = overlay; tempMaterialDefinition.channelMask[overlayID] = overlay.colorData.channelMask; tempMaterialDefinition.channelAdditiveMask[overlayID] = overlay.colorData.channelAdditiveMask; } tempMaterialDefinition.overlayList = overlayList; tempMaterialDefinition.isRectShared = false; for (int j = 0; j < generatedMaterial.materialFragments.Count; j++) { if (tempMaterialDefinition.overlayList == generatedMaterial.materialFragments[j].overlayList) { tempMaterialDefinition.isRectShared = true; tempMaterialDefinition.rectFragment = generatedMaterial.materialFragments[j]; break; } } generatedMaterial.materialFragments.Add(tempMaterialDefinition); } } packTexture = new MaxRectsBinPack(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false); } public class MaterialDefinitionComparer : IComparer<UMAData.MaterialFragment> { public int Compare(UMAData.MaterialFragment x, UMAData.MaterialFragment y) { return y.size - x.size; } } protected override IEnumerator workerMethod() { umaData.generatedMaterials.rendererCount = rendererCount; umaData.generatedMaterials.materials = generatedMaterials; GenerateAtlasData(); OptimizeAtlas(); textureProcessCoroutine.Prepare(umaData, umaGenerator); yield return textureProcessCoroutine; CleanBackUpTextures(); UpdateUV(); // HACK - is this the right place? SlotData[] slots = umaData.umaRecipe.slotDataList; for (int i = 0; i < slots.Length; i++) { var slot = slots[i]; if (slot == null) continue; #if (UNITY_STANDALONE || UNITY_IOS || UNITY_ANDROID || UNITY_PS4 || UNITY_XBOXONE) && !UNITY_2017_3_OR_NEWER //supported platforms for procedural materials for (int j = 1; j < slot.OverlayCount; j++) { OverlayData overlay = slot.GetOverlay(j); if ((overlay != null) && (overlay.isProcedural)) overlay.ReleaseProceduralTextures(); } #endif } if (updateMaterialList) { for (int j = 0; j < umaData.rendererCount; j++) { var renderer = umaData.GetRenderer(j); var mats = renderer.sharedMaterials; var newMats = new Material[mats.Length]; var atlasses = umaData.generatedMaterials.materials; int materialIndex = 0; for (int i = 0; i < atlasses.Count; i++) { if (atlasses[i].renderer == j) { UMAUtils.DestroySceneObject(mats[materialIndex]); newMats[materialIndex] = atlasses[i].material; materialIndex++; } } renderer.sharedMaterials = newMats; } } } protected override void Stop() { } private void CleanBackUpTextures() { for (int textureIndex = 0; textureIndex < backUpTexture.Length; textureIndex++) { if (backUpTexture[textureIndex] != null) { Texture tempTexture = backUpTexture[textureIndex]; if (tempTexture is RenderTexture) { RenderTexture tempRenderTexture = tempTexture as RenderTexture; tempRenderTexture.Release(); UMAUtils.DestroySceneObject(tempRenderTexture); tempRenderTexture = null; } else { UMAUtils.DestroySceneObject(tempTexture); } backUpTexture[textureIndex] = null; } } } private void GenerateAtlasData() { float StartScale = 1.0f / (float)scaleFactor; for (int i = 0; i < atlassedMaterials.Count; i++) { var generatedMaterial = atlassedMaterials[i]; generatedMaterial.materialFragments.Sort(comparer); generatedMaterial.resolutionScale = StartScale; generatedMaterial.cropResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution); while (!CalculateRects(generatedMaterial)) { generatedMaterial.resolutionScale = generatedMaterial.resolutionScale * 0.5f; } UpdateSharedRect(generatedMaterial); } } private void UpdateSharedRect(UMAData.GeneratedMaterial generatedMaterial) { for (int i = 0; i < generatedMaterial.materialFragments.Count; i++) { var fragment = generatedMaterial.materialFragments[i]; if (fragment.isRectShared) { fragment.atlasRegion = fragment.rectFragment.atlasRegion; } } } private bool CalculateRects(UMAData.GeneratedMaterial material) { Rect nullRect = new Rect(0, 0, 0, 0); packTexture.Init(umaGenerator.atlasResolution, umaGenerator.atlasResolution, false); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { var tempMaterialDef = material.materialFragments[atlasElementIndex]; if (tempMaterialDef.isRectShared) continue; tempMaterialDef.atlasRegion = packTexture.Insert(Mathf.FloorToInt(tempMaterialDef.baseOverlay.textureList[0].width * material.resolutionScale * tempMaterialDef.slotData.overlayScale), Mathf.FloorToInt(tempMaterialDef.baseOverlay.textureList[0].height * material.resolutionScale * tempMaterialDef.slotData.overlayScale), MaxRectsBinPack.FreeRectChoiceHeuristic.RectBestLongSideFit); if (tempMaterialDef.atlasRegion == nullRect) { if (umaGenerator.fitAtlas) { Debug.LogWarning("Atlas resolution is too small, Textures will be reduced.", umaData.gameObject); return false; } else { Debug.LogError("Atlas resolution is too small, not all textures will fit.", umaData.gameObject); } } } return true; } private void OptimizeAtlas() { for (int atlasIndex = 0; atlasIndex < atlassedMaterials.Count; atlasIndex++) { var material = atlassedMaterials[atlasIndex]; Vector2 usedArea = new Vector2(0, 0); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { if (material.materialFragments[atlasElementIndex].atlasRegion.xMax > usedArea.x) { usedArea.x = material.materialFragments[atlasElementIndex].atlasRegion.xMax; } if (material.materialFragments[atlasElementIndex].atlasRegion.yMax > usedArea.y) { usedArea.y = material.materialFragments[atlasElementIndex].atlasRegion.yMax; } } Vector2 tempResolution = new Vector2(umaGenerator.atlasResolution, umaGenerator.atlasResolution); bool done = false; while (!done) { if (tempResolution.x * 0.5f >= usedArea.x) { tempResolution = new Vector2(tempResolution.x * 0.5f, tempResolution.y); } else { done = true; } } done = false; while (!done) { if (tempResolution.y * 0.5f >= usedArea.y) { tempResolution = new Vector2(tempResolution.x, tempResolution.y * 0.5f); } else { done = true; } } material.cropResolution = tempResolution; } } private void UpdateUV() { UMAData.GeneratedMaterials umaAtlasList = umaData.generatedMaterials; for (int atlasIndex = 0; atlasIndex < umaAtlasList.materials.Count; atlasIndex++) { var material = umaAtlasList.materials[atlasIndex]; if (material.umaMaterial.materialType == UMAMaterial.MaterialType.NoAtlas) continue; Vector2 finalAtlasAspect = new Vector2(umaGenerator.atlasResolution / material.cropResolution.x, umaGenerator.atlasResolution / material.cropResolution.y); for (int atlasElementIndex = 0; atlasElementIndex < material.materialFragments.Count; atlasElementIndex++) { Rect tempRect = material.materialFragments[atlasElementIndex].atlasRegion; tempRect.xMin = tempRect.xMin * finalAtlasAspect.x; tempRect.xMax = tempRect.xMax * finalAtlasAspect.x; tempRect.yMin = tempRect.yMin * finalAtlasAspect.y; tempRect.yMax = tempRect.yMax * finalAtlasAspect.y; material.materialFragments[atlasElementIndex].atlasRegion = tempRect; } } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Web; using System.Web.Mvc; using System.Web.Routing; using System.Web.UI.HtmlControls; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Diagnostics.Trace; using Adxstudio.Xrm.Metadata; using Adxstudio.Xrm.Notes; using Adxstudio.Xrm.Security; using Adxstudio.Xrm.Services.Query; using Adxstudio.Xrm.Web.Mvc.Html; using Adxstudio.Xrm.Web.UI.WebForms; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Portal.Configuration; using Microsoft.Xrm.Portal.Web.UI.CrmEntityFormView; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Metadata; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// Template used when rendering notes. /// </summary> public class NotesControlTemplate : NotesCellTemplate { /// <summary> /// Constructor /// </summary> /// <param name="metadata"></param> /// <param name="contextName"></param> /// <param name="bindings"></param> public NotesControlTemplate(FormXmlCellMetadata metadata, string contextName, IDictionary<string, CellBinding> bindings, bool isTimeline = false) : base(metadata) { ContextName = contextName; Bindings = bindings; IsTimeline = isTimeline; } /// <summary> /// Name of the context the portal binds to /// </summary> protected string ContextName { get; set; } /// <summary> /// Dictionary of the cell bindings /// </summary> protected IDictionary<string, CellBinding> Bindings { get; private set; } /// <summary> /// Flag determining whether this is a notes control or a timeline control /// </summary> protected bool IsTimeline { get; set; } /// <summary> /// Control instantiation /// </summary> /// <param name="container"></param> protected override void InstantiateControlIn(HtmlControl container) { Bindings[Metadata.ControlID + "CrmEntityId"] = new CellBinding { Get = () => null, Set = obj => { var id = obj.ToString(); Guid entityId; if (!Guid.TryParse(id, out entityId)) { return; } var notesHtml = BuildNotesControl(entityId); var notes = new HtmlGenericControl("div") { ID = Metadata.ControlID, InnerHtml = notesHtml.ToString() }; container.Controls.Add(notes); } }; if (!container.Page.IsPostBack) { return; } // On PostBack no databinding occurs so get the id from the viewstate stored on the CrmEntityFormView control. var crmEntityId = Metadata.FormView.CrmEntityId; if (crmEntityId == null) { return; } var notesControlHtml = BuildNotesControl((Guid)crmEntityId); var notesControl = new HtmlGenericControl("div") { ID = Metadata.ControlID, InnerHtml = notesControlHtml.ToString() }; container.Controls.Add(notesControl); } /// <summary> /// Indicates whether entity permissions permit the user to add notes to the target entity. /// </summary> protected virtual bool TryAssertAddNote(Guid regardingId) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Start Assert Add Note Privilege on: {0} {1}", Metadata.TargetEntityName, regardingId)); if (!Metadata.FormView.EnableEntityPermissions) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. Entity Permissions have not been enabled."); return false; } var regarding = new EntityReference(Metadata.TargetEntityName, regardingId); var dataAdapterDependencies = new PortalConfigurationDataAdapterDependencies(); var serviceContext = dataAdapterDependencies.GetServiceContext(); var entityPermissionProvider = new CrmEntityPermissionProvider(); if (!entityPermissionProvider.PermissionsExist) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. Entity Permissions have not been defined. Your request could not be completed."); return false; } var entityType = IsTimeline ? "adx_portalcomment" : "annotation"; var entityMetadata = serviceContext.GetEntityMetadata(regarding.LogicalName, EntityFilters.All); var primaryKeyName = entityMetadata.PrimaryIdAttribute; var entity = serviceContext.CreateQuery(regarding.LogicalName) .First(e => e.GetAttributeValue<Guid>(primaryKeyName) == regarding.Id); var canAppendTo = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.AppendTo, entity, entityMetadata); var canCreate = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Create, entityType, regarding); var canAppend = entityPermissionProvider.TryAssert(serviceContext, CrmEntityPermissionRight.Append, entityType, regarding); if (canCreate & canAppend & canAppendTo) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Add Note Permission Granted: {0} {1}", EntityNamePrivacy.GetEntityName(Metadata.TargetEntityName), regardingId)); return true; } if (!canCreate) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Create notes."); } else if (!canAppendTo) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("Permission Denied. You do not have the appropriate Entity Permissions to Append To {0}.", EntityNamePrivacy.GetEntityName(entity.LogicalName))); } else { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Permission Denied. You do not have the appropriate Entity Permissions to Append notes."); } return false; } /// <summary> /// Creates the HTML to render a listing of notes associated to a given target entity record /// </summary> protected virtual IHtmlString BuildNotesControl(Guid entityId) { var portalContext = PortalCrmConfigurationManager.CreatePortalContext(Metadata.FormView.ContextName); var target = new EntityReference(Metadata.TargetEntityName, entityId); var html = new HtmlHelper(new ViewContext(), new ViewPage()); var settings = IsTimeline ? Metadata.TimelineSettings : Metadata.NotesSettings; var createEnabled = false; var editEnabled = false; var deleteEnabled = false; string addNoteButtonLabel = null; string loadMoreButtonLabel = null; string toolbarButtonLabel = null; string editNoteButtonLabel = null; string deleteNoteButtonLabel = null; string listTitle = null; List<Order> listOrders = null; string notePrivacyLabel = null; string accessDeniedMessage = null; string errorMessage = null; string loadingMessage = null; string emptyMessage = null; string createModalCssClass = null; string createModalTitle = null; string createModalTitleCssClass = null; var createModalSize = BootstrapExtensions.BootstrapModalSize.Default; string createModalPrimaryButtonText = null; string createModalDismissButtonSrText = null; string createModalCloseButtonText = null; string createModalPrimaryButtonCssClass = null; string createModalCloseButtonCssClass = null; string createModalNoteFieldLabel = null; var createModalDisplayPrivacyOptionField = false; string createModalPrivacyOptionFieldLabel = null; var createModalPrivacyOptionFieldDefaultValue = false; var createModalDisplayAttachFile = true; string createModalAttachFileLabel = null; string createModalAttachFileAccept = null; int? createModalNoteFieldColumns = 20; int? createModalNoteFieldRows = 9; string createModalLeftColumnCssClass = null; string createModalRightColumnCssClass = null; string editModalCssClass = null; string editModalTitle = null; string editModalTitleCssClass = null; var editModalSize = BootstrapExtensions.BootstrapModalSize.Default; string editModalPrimaryButtonText = null; string editModalDismissButtonSrText = null; string editModalCloseButtonText = null; string editModalPrimaryButtonCssClass = null; string editModalCloseButtonCssClass = null; string editModalNoteFieldLabel = null; var editModalDisplayPrivacyOptionField = false; string editModalPrivacyOptionFieldLabel = null; var editModalPrivacyOptionFieldDefaultValue = false; var editModalDisplayAttachFile = true; string editModalAttachFileLabel = null; string editModalAttachFileAccept = null; int? editModalNoteFieldColumns = 20; int? editModalNoteFieldRows = 9; string editModalLeftColumnCssClass = null; string editModalRightColumnCssClass = null; var deleteModalSize = BootstrapExtensions.BootstrapModalSize.Default; string deleteModalCssClass = null; string deleteModalTitle = null; string deleteModalTitleCssClass = null; string deleteModalConfirmation = null; string deleteModalPrimaryButtonText = null; string deleteModalDismissButtonSrText = null; string deleteModalCloseButtonText = null; string deleteModalPrimaryButtonCssClass = null; string deleteModalCloseButtonCssClass = null; AnnotationSettings attachmentSettings = null; if (settings != null) { accessDeniedMessage = Localization.GetLocalizedString(settings.AccessDeniedMessage, Metadata.LanguageCode); errorMessage = Localization.GetLocalizedString(settings.ErrorMessage, Metadata.LanguageCode); loadingMessage = Localization.GetLocalizedString(settings.LoadingMessage, Metadata.LanguageCode); emptyMessage = Localization.GetLocalizedString(settings.EmptyMessage, Metadata.LanguageCode); notePrivacyLabel = Localization.GetLocalizedString(settings.NotePrivacyLabel, Metadata.LanguageCode); addNoteButtonLabel = Localization.GetLocalizedString(settings.AddNoteButtonLabel, Metadata.LanguageCode); loadMoreButtonLabel = IsTimeline ? Localization.GetLocalizedString(((JsonConfiguration.TimelineMetadata)settings).LoadMoreButtonLabel, Metadata.LanguageCode) : null; editNoteButtonLabel = Localization.GetLocalizedString(settings.EditNoteButtonLabel, Metadata.LanguageCode); deleteNoteButtonLabel = Localization.GetLocalizedString(settings.DeleteNoteButtonLabel, Metadata.LanguageCode); listTitle = Localization.GetLocalizedString(settings.ListTitle, Metadata.LanguageCode); if (settings.ListOrders != null && settings.ListOrders.Any()) { listOrders = settings.ListOrders; } var createModal = settings.CreateDialog; createModalCssClass = createModal == null ? null : createModal.CssClass; if (createModal != null && createModal.Size != null) { createModalSize = createModal.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Default); } createModalTitle = createModal == null ? null : Localization.GetLocalizedString(createModal.Title, Metadata.LanguageCode); createModalTitleCssClass = createModal == null ? null : createModal.TitleCssClass; createModalPrimaryButtonText = createModal == null ? null : Localization.GetLocalizedString(createModal.PrimaryButtonText, Metadata.LanguageCode); createModalDismissButtonSrText = createModal == null ? null : Localization.GetLocalizedString(createModal.DismissButtonSrText, Metadata.LanguageCode); createModalCloseButtonText = createModal == null ? null : Localization.GetLocalizedString(createModal.CloseButtonText, Metadata.LanguageCode); createModalPrimaryButtonCssClass = createModal == null ? null : createModal.PrimaryButtonCssClass; createModalCloseButtonCssClass = createModal == null ? null : createModal.CloseButtonCssClass; createModalNoteFieldLabel = createModal == null ? null : Localization.GetLocalizedString(createModal.NoteFieldLabel, Metadata.LanguageCode); createModalDisplayPrivacyOptionField = createModal != null && createModal.DisplayPrivacyOptionField.GetValueOrDefault(false); createModalPrivacyOptionFieldLabel = createModal == null ? null : Localization.GetLocalizedString(createModal.PrivacyOptionFieldLabel, Metadata.LanguageCode); createModalPrivacyOptionFieldDefaultValue = createModal != null && createModal.PrivacyOptionFieldDefaultValue.GetValueOrDefault(false); createModalDisplayAttachFile = createModal == null || createModal.DisplayAttachFile.GetValueOrDefault(true); createModalAttachFileLabel = createModal == null ? null : Localization.GetLocalizedString(createModal.AttachFileLabel, Metadata.LanguageCode); createModalAttachFileAccept = createModal == null ? null : Localization.GetLocalizedString(createModal.AttachFileAccept, Metadata.LanguageCode); createModalNoteFieldColumns = createModal == null ? 20 : createModal.NoteFieldColumns.GetValueOrDefault(20); createModalNoteFieldRows = createModal == null ? 9 : createModal.NoteFieldRows.GetValueOrDefault(9); createModalLeftColumnCssClass = createModal == null ? null : createModal.LeftColumnCSSClass; createModalRightColumnCssClass = createModal == null ? null : createModal.RightColumnCSSClass; var editModal = settings.EditDialog; editModalCssClass = editModal == null ? null : editModal.CssClass; if (editModal != null && editModal.Size != null) { editModalSize = editModal.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Default); } editModalTitle = editModal == null ? null : Localization.GetLocalizedString(editModal.Title, Metadata.LanguageCode); editModalTitleCssClass = editModal == null ? null : editModal.TitleCssClass; editModalPrimaryButtonText = editModal == null ? null : Localization.GetLocalizedString(editModal.PrimaryButtonText, Metadata.LanguageCode); editModalDismissButtonSrText = editModal == null ? null : Localization.GetLocalizedString(editModal.DismissButtonSrText, Metadata.LanguageCode); editModalCloseButtonText = editModal == null ? null : Localization.GetLocalizedString(editModal.CloseButtonText, Metadata.LanguageCode); editModalPrimaryButtonCssClass = editModal == null ? null : editModal.PrimaryButtonCssClass; editModalCloseButtonCssClass = editModal == null ? null : editModal.CloseButtonCssClass; editModalNoteFieldLabel = editModal == null ? null : Localization.GetLocalizedString(editModal.NoteFieldLabel, Metadata.LanguageCode); editModalDisplayPrivacyOptionField = editModal != null && editModal.DisplayPrivacyOptionField.GetValueOrDefault(false); editModalPrivacyOptionFieldLabel = editModal == null ? null : Localization.GetLocalizedString(editModal.PrivacyOptionFieldLabel, Metadata.LanguageCode); editModalPrivacyOptionFieldDefaultValue = editModal != null && editModal.PrivacyOptionFieldDefaultValue.GetValueOrDefault(false); editModalDisplayAttachFile = editModal == null || editModal.DisplayAttachFile.GetValueOrDefault(true); editModalAttachFileLabel = editModal == null ? null : Localization.GetLocalizedString(editModal.AttachFileLabel, Metadata.LanguageCode); editModalAttachFileAccept = editModal == null ? null : Localization.GetLocalizedString(editModal.AttachFileAccept, Metadata.LanguageCode); editModalNoteFieldColumns = editModal == null ? 20 : editModal.NoteFieldColumns.GetValueOrDefault(20); editModalNoteFieldRows = editModal == null ? 9 : editModal.NoteFieldRows.GetValueOrDefault(9); editModalLeftColumnCssClass = editModal == null ? null : editModal.LeftColumnCSSClass; editModalRightColumnCssClass = editModal == null ? null : editModal.RightColumnCSSClass; var deleteModal = settings.DeleteDialog; if (deleteModal != null && deleteModal.Size != null) { deleteModalSize = deleteModal.Size.GetValueOrDefault(BootstrapExtensions.BootstrapModalSize.Default); } deleteModalCssClass = deleteModal == null ? null : deleteModal.CssClass; deleteModalTitle = deleteModal == null ? null : Localization.GetLocalizedString(deleteModal.Title, Metadata.LanguageCode); deleteModalTitleCssClass = deleteModal == null ? null : deleteModal.TitleCssClass; deleteModalConfirmation = deleteModal == null ? null : Localization.GetLocalizedString(deleteModal.Confirmation, Metadata.LanguageCode); deleteModalPrimaryButtonText = deleteModal == null ? null : Localization.GetLocalizedString(deleteModal.PrimaryButtonText, Metadata.LanguageCode); deleteModalDismissButtonSrText = deleteModal == null ? null : Localization.GetLocalizedString(deleteModal.DismissButtonSrText, Metadata.LanguageCode); deleteModalCloseButtonText = deleteModal == null ? null : Localization.GetLocalizedString(deleteModal.CloseButtonText, Metadata.LanguageCode); deleteModalPrimaryButtonCssClass = deleteModal == null ? null : deleteModal.PrimaryButtonCssClass; deleteModalCloseButtonCssClass = deleteModal == null ? null : deleteModal.CloseButtonCssClass; createEnabled = settings.CreateEnabled.GetValueOrDefault(false); editEnabled = settings.EditEnabled.GetValueOrDefault(false); deleteEnabled = settings.DeleteEnabled.GetValueOrDefault(false); attachmentSettings = new AnnotationSettings(portalContext.ServiceContext, true, settings.AttachFileLocation.GetValueOrDefault(StorageLocation.CrmDocument), settings.AttachFileAccept, settings.AttachFileRestrictAccept.GetValueOrDefault(false), Localization.GetLocalizedString(settings.AttachFileRestrictErrorMessage, Metadata.LanguageCode), settings.AttachFileMaximumSize.HasValue ? Convert.ToUInt64(settings.AttachFileMaximumSize.Value) << 10 : (ulong?)null, Localization.GetLocalizedString(settings.AttachFileMaximumSizeErrorMessage, Metadata.LanguageCode), IsTimeline ? ((JsonConfiguration.TimelineMetadata)settings).AttachFileAcceptExtensions : string.Empty, isPortalComment: IsTimeline); } var canAddNotes = TryAssertAddNote(entityId); if (createEnabled) { createEnabled = canAddNotes; } if (deleteEnabled) { deleteEnabled = Metadata.FormView.EnableEntityPermissions; } if (editEnabled) { editEnabled = Metadata.FormView.EnableEntityPermissions; } string getServiceUrl = null; string addServiceUrl = null; string updateServiceUrl = null; string deleteServiceUrl = null; string getAttachmentsServiceUrl = null; bool isTimeline; bool useScrollingPagination; string entityLogicalName = null; string textAttributeName = null; if (IsTimeline) { getServiceUrl = BuildControllerActionUrl("GetActivities", "EntityActivity", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); addServiceUrl = BuildControllerActionUrl("AddPortalComment", "EntityActivity", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); updateServiceUrl = null; deleteServiceUrl = null; getAttachmentsServiceUrl = BuildControllerActionUrl("GetAttachments", "EntityActivity", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); useScrollingPagination = true; isTimeline = true; entityLogicalName = "adx_portalcomment"; textAttributeName = "description"; } else { getServiceUrl = BuildControllerActionUrl("GetNotes", "EntityNotes", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); addServiceUrl = BuildControllerActionUrl("AddNote", "EntityNotes", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); updateServiceUrl = BuildControllerActionUrl("UpdateNote", "EntityNotes", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); deleteServiceUrl = BuildControllerActionUrl("DeleteNote", "EntityNotes", new { area = "Portal", __portalScopeId__ = portalContext.Website.Id }); getAttachmentsServiceUrl = null; useScrollingPagination = false; isTimeline = false; entityLogicalName = "annotation"; textAttributeName = "notetext"; } var entityMetadata = portalContext.ServiceContext.GetEntityMetadata(entityLogicalName, EntityFilters.All); var textAttribute = (MemoAttributeMetadata)entityMetadata.Attributes.Where((att) => { return att.LogicalName == textAttributeName; }).First(); var notesHtml = html.Notes(target, getServiceUrl, createEnabled, editEnabled, deleteEnabled, addServiceUrl, updateServiceUrl, deleteServiceUrl, getAttachmentsServiceUrl, Metadata.NotesPageSize ?? 0, listOrders, listTitle, loadingMessage, errorMessage, accessDeniedMessage, emptyMessage, addNoteButtonLabel, loadMoreButtonLabel, toolbarButtonLabel, editNoteButtonLabel, deleteNoteButtonLabel, notePrivacyLabel, createModalSize, createModalCssClass, createModalTitle, createModalDismissButtonSrText, createModalPrimaryButtonText, createModalCloseButtonText, createModalTitleCssClass, createModalPrimaryButtonCssClass, createModalCloseButtonCssClass, createModalNoteFieldLabel, createModalDisplayAttachFile, createModalAttachFileLabel, createModalAttachFileAccept, createModalDisplayPrivacyOptionField, createModalPrivacyOptionFieldLabel, createModalPrivacyOptionFieldDefaultValue, createModalNoteFieldColumns, createModalNoteFieldRows, createModalLeftColumnCssClass, createModalRightColumnCssClass, null, editModalSize, editModalCssClass, editModalTitle, editModalDismissButtonSrText, editModalPrimaryButtonText, editModalCloseButtonText, editModalTitleCssClass, editModalPrimaryButtonCssClass, editModalCloseButtonCssClass, editModalNoteFieldLabel, editModalDisplayAttachFile, editModalAttachFileLabel, editModalAttachFileAccept, editModalDisplayPrivacyOptionField, editModalPrivacyOptionFieldLabel, editModalPrivacyOptionFieldDefaultValue, editModalNoteFieldColumns, editModalNoteFieldRows, editModalLeftColumnCssClass, editModalRightColumnCssClass, null, deleteModalSize, deleteModalCssClass, deleteModalTitle, deleteModalConfirmation, deleteModalDismissButtonSrText, deleteModalPrimaryButtonText, deleteModalCloseButtonText, deleteModalTitleCssClass, deleteModalPrimaryButtonCssClass, deleteModalCloseButtonCssClass, isTimeline: isTimeline, useScrollingPagination: useScrollingPagination, attachmentSettings: attachmentSettings, textMaxLength: textAttribute.MaxLength); return notesHtml; } /// <summary> /// Generates a URL to a controller action /// </summary> protected string BuildControllerActionUrl(string actionName, string controllerName, object routeValues) { var httpContextWrapper = new HttpContextWrapper(HttpContext.Current); var routeData = RouteTable.Routes.GetRouteData(httpContextWrapper); if (routeData == null) { routeData = new RouteData(); } var urlHelper = new UrlHelper(new RequestContext(httpContextWrapper, routeData)); return urlHelper.Action(actionName, controllerName, routeValues); } } }
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Xml; namespace SharpVectors.Net { public class WinAppCacheManager : ICacheManager { private string cacheDir; private string cacheDocPath; private XmlDocument cacheDoc = new XmlDocument(); public WinAppCacheManager() { cacheDir = Path.Combine( SharpVectors.ApplicationContext.ExecutableDirectory.FullName, "cache/"); cacheDocPath = Path.Combine(cacheDir, "cache.xml"); loadDoc(); } public WinAppCacheManager(string cacheDir) { this.cacheDir = Path.Combine( SharpVectors.ApplicationContext.ExecutableDirectory.FullName, cacheDir); cacheDocPath = Path.Combine(cacheDir, "cache.xml"); loadDoc(); } private void loadDoc() { if(File.Exists(cacheDocPath)) { cacheDoc.Load(cacheDocPath); } else { Directory.CreateDirectory(Directory.GetParent(cacheDocPath).FullName); cacheDoc.LoadXml("<cache />"); } } private void saveDoc() { cacheDoc.Save(cacheDocPath); } private XmlElement lastCacheElm; private Uri lastUri; private XmlElement getCacheElm(Uri uri) { if(uri == lastUri && lastCacheElm != null) { return lastCacheElm; } else { string xpath = "/cache/resource[@url='" + uri.ToString() + "']"; XmlNode node = cacheDoc.SelectSingleNode(xpath); if(node != null) { lastCacheElm = node as XmlElement; } else { lastCacheElm = cacheDoc.CreateElement("resource"); cacheDoc.DocumentElement.AppendChild(lastCacheElm); lastCacheElm.SetAttribute("url", uri.ToString()); } lastUri = uri; return lastCacheElm; } } private Uri getLocalPathUri(XmlElement cacheElm) { if(cacheElm.HasAttribute("local-path")) { string path = Path.Combine(cacheDir, cacheElm.GetAttribute("local-path")); if(File.Exists(path)) { path = "file:///" + path.Replace('\\', '/'); return new Uri(path); } else { cacheElm.RemoveAttribute("local-path"); return null; } } else { return null; } } public long Size { get { DirectoryInfo di = new DirectoryInfo(cacheDir); FileInfo[] files = di.GetFiles(); long size = 0; foreach(FileInfo file in files) { size += file.Length; } return size; } } public void Clear() { DirectoryInfo di = new DirectoryInfo(cacheDir); FileInfo[] files = di.GetFiles(); foreach(FileInfo file in files) { try { file.Delete(); } catch{} } cacheDoc = new XmlDocument(); loadDoc(); } public CacheInfo GetCacheInfo(Uri uri) { XmlElement cacheElm = getCacheElm(uri); DateTime expires = DateTime.MinValue; if(cacheElm.HasAttribute("expires")) { expires = DateTime.Parse(cacheElm.GetAttribute("expires")); } DateTime lastModified = DateTime.MinValue; if(cacheElm.HasAttribute("last-modified")) { lastModified = DateTime.Parse(cacheElm.GetAttribute("last-modified")); } Uri cachedUri = getLocalPathUri(cacheElm); return new CacheInfo(expires, cacheElm.GetAttribute("etag"), lastModified, cachedUri, cacheElm.GetAttribute("content-type")); } public void SetCacheInfo(Uri uri, CacheInfo cacheInfo, Stream stream) { XmlElement cacheElm = getCacheElm(uri); if(cacheInfo != null) { if(cacheInfo.ETag != null) { cacheElm.SetAttribute("etag", cacheInfo.ETag); } else { cacheElm.RemoveAttribute("etag"); } if(cacheInfo.ContentType != null) { cacheElm.SetAttribute("content-type", cacheInfo.ContentType); } else { cacheElm.RemoveAttribute("content-type"); } if(cacheInfo.Expires != DateTime.MinValue) { cacheElm.SetAttribute("expires", cacheInfo.Expires.ToString("s")); } else { cacheElm.RemoveAttribute("expires"); } if(cacheInfo.LastModified != DateTime.MinValue) { cacheElm.SetAttribute("last-modified", cacheInfo.LastModified.ToString("s")); } else { cacheElm.RemoveAttribute("last-modified"); } } if(stream != null) { string localPath; if(cacheElm.HasAttribute("local-path")) { localPath = cacheElm.GetAttribute("local-path"); } else { localPath = Guid.NewGuid().ToString() + ".cache"; cacheElm.SetAttribute("local-path", localPath); } stream.Position = 0; int count; byte[] buffer = new byte[4096]; FileStream fs = File.OpenWrite(Path.Combine(cacheDir, localPath)); while((count = stream.Read(buffer, 0, 4096)) > 0) fs.Write(buffer, 0, count); fs.Flush(); fs.Close(); } saveDoc(); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.WindowsAzure.WebSitesExtensions; using Microsoft.WindowsAzure.WebSitesExtensions.Models; namespace Microsoft.WindowsAzure.WebSitesExtensions { /// <summary> /// The websites extensions client manages the web sites deployments, web /// jobs and other extensions. /// </summary> public static partial class ContinuousWebJobOperationsExtensions { /// <summary> /// Delete a continuous job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IContinuousWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).DeleteAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete a continuous job. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IContinuousWebJobOperations operations, string jobName) { return operations.DeleteAsync(jobName, CancellationToken.None); } /// <summary> /// Get a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <returns> /// The get continuous WebJob Operation Response. /// </returns> public static ContinuousWebJobGetResponse Get(this IContinuousWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).GetAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <returns> /// The get continuous WebJob Operation Response. /// </returns> public static Task<ContinuousWebJobGetResponse> GetAsync(this IContinuousWebJobOperations operations, string jobName) { return operations.GetAsync(jobName, CancellationToken.None); } /// <summary> /// Get the settings of a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <returns> /// The continuous WebJob settings operation response. /// </returns> public static ContinuousWebJobSettingsResponse GetSettings(this IContinuousWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).GetSettingsAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Get the settings of a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <returns> /// The continuous WebJob settings operation response. /// </returns> public static Task<ContinuousWebJobSettingsResponse> GetSettingsAsync(this IContinuousWebJobOperations operations, string jobName) { return operations.GetSettingsAsync(jobName, CancellationToken.None); } /// <summary> /// List the continuous web jobs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <returns> /// The list of continuous WebJobs operation response. /// </returns> public static ContinuousWebJobListResponse List(this IContinuousWebJobOperations operations) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).ListAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// List the continuous web jobs. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <returns> /// The list of continuous WebJobs operation response. /// </returns> public static Task<ContinuousWebJobListResponse> ListAsync(this IContinuousWebJobOperations operations) { return operations.ListAsync(CancellationToken.None); } /// <summary> /// Set the settings of a continuous WebJob (will replace the current /// settings of the WebJob). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <param name='settings'> /// Required. The continuous WebJob settings. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse SetSettings(this IContinuousWebJobOperations operations, string jobName, ContinuousWebJobSettingsUpdateParameters settings) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).SetSettingsAsync(jobName, settings); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Set the settings of a continuous WebJob (will replace the current /// settings of the WebJob). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <param name='settings'> /// Required. The continuous WebJob settings. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> SetSettingsAsync(this IContinuousWebJobOperations operations, string jobName, ContinuousWebJobSettingsUpdateParameters settings) { return operations.SetSettingsAsync(jobName, settings, CancellationToken.None); } /// <summary> /// Start a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Start(this IContinuousWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).StartAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Start a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> StartAsync(this IContinuousWebJobOperations operations, string jobName) { return operations.StartAsync(jobName, CancellationToken.None); } /// <summary> /// Stop a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Stop(this IContinuousWebJobOperations operations, string jobName) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).StopAsync(jobName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Stop a continuous WebJob. /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The WebJob name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> StopAsync(this IContinuousWebJobOperations operations, string jobName) { return operations.StopAsync(jobName, CancellationToken.None); } /// <summary> /// Create or replace a continuous WebJob with a script file (.exe, /// .bat, .php, .js...). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <param name='fileName'> /// Required. The file name. /// </param> /// <param name='jobContent'> /// Required. The file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse UploadFile(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).UploadFileAsync(jobName, fileName, jobContent); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or replace a continuous WebJob with a script file (.exe, /// .bat, .php, .js...). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <param name='fileName'> /// Required. The file name. /// </param> /// <param name='jobContent'> /// Required. The file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> UploadFileAsync(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return operations.UploadFileAsync(jobName, fileName, jobContent, CancellationToken.None); } /// <summary> /// Create or replace a continuous WebJob with a zip file (containing /// the WebJob binaries). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <param name='fileName'> /// Required. The zip file name. /// </param> /// <param name='jobContent'> /// Required. The zip file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse UploadZip(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return Task.Factory.StartNew((object s) => { return ((IContinuousWebJobOperations)s).UploadZipAsync(jobName, fileName, jobContent); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create or replace a continuous WebJob with a zip file (containing /// the WebJob binaries). /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.WindowsAzure.WebSitesExtensions.IContinuousWebJobOperations. /// </param> /// <param name='jobName'> /// Required. The continuous WebJob name. /// </param> /// <param name='fileName'> /// Required. The zip file name. /// </param> /// <param name='jobContent'> /// Required. The zip file content. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> UploadZipAsync(this IContinuousWebJobOperations operations, string jobName, string fileName, Stream jobContent) { return operations.UploadZipAsync(jobName, fileName, jobContent, CancellationToken.None); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Globalization; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Insights.Models; namespace Microsoft.Azure.Management.Insights { /// <summary> /// Operations for managing resources sku. /// </summary> internal partial class AntaresSkuOperations { private static readonly Uri BaseUri = new Uri("http://localhost.com"); private static readonly UriTemplate AntaresUriTemplate = new UriTemplate("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/microsoft.web/serverFarms/{serverFarmName}", true); // Verify resourceId is of a supported type internal static bool IsAntaresResourceType(string resourceId) { return AntaresUriTemplate.Match(BaseUri, new Uri(BaseUri, resourceId)) != null; } internal static SkuListResponse ListAntaresSkus() { return new SkuListResponse { StatusCode = HttpStatusCode.OK, Value = new List<SkuDefinition> { new SkuDefinition { Sku = new Sku { Name = "S1", Tier = "Standard" }, Capacity = new Capacity { Minimum = 1, Maximum = 10, Default = 1, ScaleType = SupportedScaleType.Automatic } }, new SkuDefinition { Sku = new Sku { Name = "S2", Tier = "Standard", }, Capacity = new Capacity { Minimum = 1, Maximum = 10, Default = 1, ScaleType = SupportedScaleType.Automatic } }, new SkuDefinition { Sku = new Sku { Name = "S3", Tier = "Standard", }, Capacity = new Capacity { Minimum = 1, Maximum = 10, Default = 1, ScaleType = SupportedScaleType.Automatic } }, new SkuDefinition { Sku = new Sku { Name = "B1", Tier = "Basic", }, Capacity = new Capacity { Minimum = 1, Maximum = 3, Default = 1, ScaleType = SupportedScaleType.Manual } }, new SkuDefinition { Sku = new Sku { Name = "B2", Tier = "Basic", }, Capacity = new Capacity { Minimum = 1, Maximum = 3, Default = 1, ScaleType = SupportedScaleType.Manual } }, new SkuDefinition { Sku = new Sku { Name = "B3", Tier = "Basic", }, Capacity = new Capacity { Minimum = 1, Maximum = 3, Default = 1, ScaleType = SupportedScaleType.Manual } }, new SkuDefinition { Sku = new Sku { Name = "D1", Tier = "Shared", }, Capacity = new Capacity { ScaleType = SupportedScaleType.None } }, new SkuDefinition { Sku = new Sku { Name = "F1", Tier = "Free", }, Capacity = new Capacity { ScaleType = SupportedScaleType.None } }, new SkuDefinition { Sku = new Sku { Name = "P1", Tier = "Premium" }, Capacity = new Capacity { Minimum = 1, Maximum = 20, Default = 1, ScaleType = SupportedScaleType.Automatic } }, new SkuDefinition { Sku = new Sku { Name = "P2", Tier = "Premium" }, Capacity = new Capacity { Minimum = 1, Maximum = 20, Default = 1, ScaleType = SupportedScaleType.Automatic } }, new SkuDefinition { Sku = new Sku { Name = "P3", Tier = "Premium" }, Capacity = new Capacity { Minimum = 1, Maximum = 20, Default = 1, ScaleType = SupportedScaleType.Automatic } } } }; } internal async static Task<SkuGetResponse> GetAntaresCurrentSku(SkuOperations skuOperations, string resourceId, string apiVersion, CancellationToken cancellationToken) { AntaresSkuGetResponse response = await skuOperations.GetAntaresCurrentSkuInternalAsync(resourceId, apiVersion, cancellationToken); return new SkuGetResponse { Properties = new SkuGetProperties { Sku = new CurrentSku { Name = AntaresSkuOperations.GetAnatresSkuName(response.Properties.CurrentWorkerSize, response.Properties.Sku), Tier = response.Properties.Sku, Capacity = response.Properties.CurrentNumberOfWorkers } } }; } internal static Task<SkuUpdateResponse> UpdateAntaresCurrentSkuAsync( SkuOperations skuOperations, string resourceId, SkuUpdateParameters parameters, string apiVersion, CancellationToken cancellationToken) { AntaresSkuUpdateRequest antaresUpdateParameters = new AntaresSkuUpdateRequest { WorkerSize = AntaresSkuOperations.GetAntaresWorkerSize(parameters.Sku.Name), Sku = parameters.Sku.Tier, NumberOfWorkers = parameters.Sku.Capacity }; return skuOperations.UpdateAntaresCurrentSkuInternalAsync(resourceId, antaresUpdateParameters, apiVersion, cancellationToken); } private static int GetAntaresWorkerSize(string skuName) { switch (skuName) { case "S1": case "B1": case "D1": case "F1": case "P1": return 0; case "S2": case "B2": case "P2": return 1; case "S3": case "B3": case "P3": return 2; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Invalid SKU Name: {0}", skuName)); } } private static string GetAnatresSkuName(int workerSize, string tier) { switch (workerSize) { case 0: switch (tier) { case "Standard": return "S1"; case "Basic": return "B1"; case "Shared": return "D1"; case "Free": return "F1"; case "Premium": return "P1"; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize)); } case 1: switch (tier) { case "Standard": return "S2"; case "Basic": return "B2"; case "Premium": return "P2"; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize)); } case 2: switch (tier) { case "Standard": return "S3"; case "Basic": return "B3"; case "Premium": return "P3"; default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize)); } default: throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "No SKU for tier {0} and worker size {1}", tier, workerSize)); } } } }
using System.Linq; using Marten.Services; using Marten.Testing.Documents; using Marten.Testing.Harness; using Weasel.Core; using Weasel.Postgresql; using Xunit; namespace Marten.Testing.Bugs { public class Bug_1155_null_duplicate_fields: BugIntegrationContext { [Fact] public void when_enum_is_null_due_to_nullable_type() { StoreOptions(_ => { _.Serializer(new JsonNetSerializer { EnumStorage = EnumStorage.AsInteger }); _.Schema.For<Target>().Duplicate(t => t.NullableColor); }); using (var session = theStore.OpenSession()) { session.Store(new Target { Number = 1, NullableColor = null }); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } [Fact] public void when_enum_is_null_due_to_nesting() { StoreOptions(_ => { _.Serializer(new JsonNetSerializer { EnumStorage = EnumStorage.AsInteger }); _.Schema.For<Target>().Duplicate(t => t.Inner.Color); }); using (var session = theStore.OpenSession()) { session.Store(new Target { Number = 1, Inner = null }); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } [Fact] public void when_string_enum_is_null_due_to_nullable_type() { StoreOptions(_ => { _.Serializer(new JsonNetSerializer { EnumStorage = EnumStorage.AsString }); _.Schema.For<Target>().Duplicate(t => t.NullableColor); }); using (var session = theStore.OpenSession()) { session.Store(new Target { Number = 1, NullableColor = null }); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } [Fact] public void when_string_enum_is_null_due_to_nesting() { StoreOptions(_ => { _.Serializer(new JsonNetSerializer { EnumStorage = EnumStorage.AsString }); _.Schema.For<Target>().Duplicate(t => t.Inner.Color); }); using (var session = theStore.OpenSession()) { session.Store(new Target { Number = 1, Inner = null }); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } [Fact] public void when_field_is_not_null_due_to_nesting() { StoreOptions(_ => _.Schema.For<Target>().Duplicate(t => t.Inner.Number)); using (var session = theStore.OpenSession()) { session.Store(new Target { Number = 1, Inner = new Target { Number = 2 } }); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } [Fact] public void when_field_is_null_due_to_nesting() { StoreOptions(_ => _.Schema.For<Target>().Duplicate(t => t.Inner.Number)); using (var session = theStore.OpenSession()) { session.Store(new Target { Number = 1, Inner = null }); session.SaveChanges(); } using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } [Fact] public void when_bulk_inserting_and_field_is_null_due_to_nesting() { StoreOptions(_ => _.Schema.For<Target>().Duplicate(t => t.Inner.Number)); theStore.BulkInsertDocuments(new[] { new Target { Number = 1, Inner = null } }); using (var session = theStore.OpenSession()) { session.Query<Target>().Where(x => x.Number == 1) .ToArray() .Select(x => x.Number) .ShouldHaveTheSameElementsAs(1); } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // // File: DocumentAutomationPeer.cs // // Description: AutomationPeer associated with flow and fixed documents. // //--------------------------------------------------------------------------- using System.Collections.Generic; // List<T> using System.Security; // SecurityCritical using System.Windows.Documents; // ITextContainer using System.Windows.Interop; // HwndSource using System.Windows.Media; // Visual using MS.Internal; // PointUtil using MS.Internal.Automation; // TextAdaptor using MS.Internal.Documents; // TextContainerHelper namespace System.Windows.Automation.Peers { /// <summary> /// AutomationPeer associated with flow and fixed documents. /// </summary> public class DocumentAutomationPeer : ContentTextAutomationPeer { /// <summary> /// Constructor. /// </summary> /// <param name="owner">Owner of the AutomationPeer.</param> public DocumentAutomationPeer(FrameworkContentElement owner) : base(owner) { if (owner is IServiceProvider) { ITextContainer textContainer = ((IServiceProvider)owner).GetService(typeof(ITextContainer)) as ITextContainer; if (textContainer != null) { _textPattern = new TextAdaptor(this, textContainer); } } } /// <summary> /// Notify the peer that it has been disconnected. /// </summary> internal void OnDisconnected() { if (_textPattern != null) { _textPattern.Dispose(); _textPattern = null; } } /// <summary> /// <see cref="AutomationPeer.GetChildrenCore"/> /// </summary> /// <remarks> /// Since DocumentAutomationPeer gives access to its content through /// TextPattern, this method always returns null. /// </remarks> protected override List<AutomationPeer> GetChildrenCore() { if (_childrenStart != null && _childrenEnd != null) { ITextContainer textContainer = ((IServiceProvider)Owner).GetService(typeof(ITextContainer)) as ITextContainer; return TextContainerHelper.GetAutomationPeersFromRange(_childrenStart, _childrenEnd, textContainer.Start); } return null; } /// <summary> /// <see cref="AutomationPeer.GetAutomationControlTypeCore"/> /// </summary> public override object GetPattern(PatternInterface patternInterface) { object returnValue = null; if (patternInterface == PatternInterface.Text) { if (_textPattern == null) { if (Owner is IServiceProvider) { ITextContainer textContainer = ((IServiceProvider)Owner).GetService(typeof(ITextContainer)) as ITextContainer; if (textContainer != null) { _textPattern = new TextAdaptor(this, textContainer); } } } returnValue = _textPattern; } else { returnValue = base.GetPattern(patternInterface); } return returnValue; } /// <summary> /// <see cref="AutomationPeer.GetAutomationControlTypeCore"/> /// </summary> protected override AutomationControlType GetAutomationControlTypeCore() { return AutomationControlType.Document; } /// <summary> /// <see cref="AutomationPeer.GetClassNameCore"/> /// </summary> /// <returns></returns> protected override string GetClassNameCore() { return "Document"; } /// <summary> /// <see cref="AutomationPeer.IsControlElementCore"/> /// </summary> protected override bool IsControlElementCore() { return true; } /// <summary> /// <see cref="AutomationPeer.GetBoundingRectangleCore"/> /// </summary> /// <SecurityNote> /// Critical - Calls PresentationSource.CriticalFromVisual to get the source for this visual /// TreatAsSafe - The returned PresenationSource object is not exposed and is only used for converting /// co-ordinates to screen space. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override Rect GetBoundingRectangleCore() { UIElement uiScope; Rect boundingRect = CalculateBoundingRect(false, out uiScope); if (boundingRect != Rect.Empty && uiScope != null) { HwndSource hwndSource = PresentationSource.CriticalFromVisual(uiScope) as HwndSource; if (hwndSource != null) { boundingRect = PointUtil.ElementToRoot(boundingRect, uiScope, hwndSource); boundingRect = PointUtil.RootToClient(boundingRect, hwndSource); boundingRect = PointUtil.ClientToScreen(boundingRect, hwndSource); } } return boundingRect; } /// <summary> /// <see cref="AutomationPeer.GetClickablePointCore"/> /// </summary> /// <SecurityNote> /// Critical - Calls PresentationSource.CriticalFromVisual to get the source for this visual /// TreatAsSafe - The returned PresenationSource object is not exposed and is only used for converting /// co-ordinates to screen space. /// </SecurityNote> [SecurityCritical, SecurityTreatAsSafe] protected override Point GetClickablePointCore() { Point point = new Point(); UIElement uiScope; Rect boundingRect = CalculateBoundingRect(true, out uiScope); if (boundingRect != Rect.Empty && uiScope != null) { HwndSource hwndSource = PresentationSource.CriticalFromVisual(uiScope) as HwndSource; if (hwndSource != null) { boundingRect = PointUtil.ElementToRoot(boundingRect, uiScope, hwndSource); boundingRect = PointUtil.RootToClient(boundingRect, hwndSource); boundingRect = PointUtil.ClientToScreen(boundingRect, hwndSource); point = new Point(boundingRect.Left + boundingRect.Width * 0.1, boundingRect.Top + boundingRect.Height * 0.1); } } return point; } /// <summary> /// <see cref="AutomationPeer.IsOffscreenCore"/> /// </summary> protected override bool IsOffscreenCore() { IsOffscreenBehavior behavior = AutomationProperties.GetIsOffscreenBehavior(Owner); switch (behavior) { case IsOffscreenBehavior.Onscreen : return false; case IsOffscreenBehavior.Offscreen : return true; default: { UIElement uiScope; Rect boundingRect = CalculateBoundingRect(true, out uiScope); return (DoubleUtil.AreClose(boundingRect, Rect.Empty) || uiScope == null); } } } /// <summary> /// Gets collection of AutomationPeers for given text range. /// </summary> internal override List<AutomationPeer> GetAutomationPeersFromRange(ITextPointer start, ITextPointer end) { _childrenStart = start.CreatePointer(); _childrenEnd = end.CreatePointer(); ResetChildrenCache(); return GetChildren(); } /// <summary> /// Calculate visible rectangle. /// </summary> private Rect CalculateBoundingRect(bool clipToVisible, out UIElement uiScope) { uiScope = null; Rect boundingRect = Rect.Empty; if (Owner is IServiceProvider) { ITextContainer textContainer = ((IServiceProvider)Owner).GetService(typeof(ITextContainer)) as ITextContainer; ITextView textView = (textContainer != null) ? textContainer.TextView : null; if (textView != null) { // Make sure TextView is updated if (!textView.IsValid) { if (!textView.Validate()) { textView = null; } if (textView != null && !textView.IsValid) { textView = null; } } // Get bounding rect from TextView. if (textView != null) { boundingRect = new Rect(textView.RenderScope.RenderSize); uiScope = textView.RenderScope; // Compute visible portion of the rectangle. if (clipToVisible) { Visual visual = textView.RenderScope; while (visual != null && boundingRect != Rect.Empty) { if (VisualTreeHelper.GetClip(visual) != null) { GeneralTransform transform = textView.RenderScope.TransformToAncestor(visual).Inverse; // Safer version of transform to descendent (doing the inverse ourself), // we want the rect inside of our space. (Which is always rectangular and much nicer to work with) if (transform != null) { Rect clipBounds = VisualTreeHelper.GetClip(visual).Bounds; clipBounds = transform.TransformBounds(clipBounds); boundingRect.Intersect(clipBounds); } else { // No visibility if non-invertable transform exists. boundingRect = Rect.Empty; } } visual = VisualTreeHelper.GetParent(visual) as Visual; } } } } } return boundingRect; } private ITextPointer _childrenStart; private ITextPointer _childrenEnd; private TextAdaptor _textPattern; } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ namespace Microsoft.Graph { using System; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// An <see cref="IHttpProvider"/> implementation using standard .NET libraries. /// </summary> public class SimpleHttpProvider : IHttpProvider { internal readonly HttpClient httpClient; /// <summary> /// Constructs a new <see cref="SimpleHttpProvider"/>. /// </summary> /// <param name="httpClient">Custom http client to be used for making requests</param> /// <param name="serializer">A serializer for serializing and deserializing JSON objects.</param> public SimpleHttpProvider(HttpClient httpClient, ISerializer serializer = null) { // Null authProvider addresses https://github.com/microsoftgraph/msgraph-sdk-dotnet/issues/605. // We're reenabling this functionality that allowed setting a null authprovider. this.httpClient = httpClient ?? GraphClientFactory.Create(authenticationProvider: null); Serializer = serializer ?? new Serializer(); } /// <summary> /// Gets a serializer for serializing and deserializing JSON objects. /// </summary> public ISerializer Serializer { get; private set; } /// <summary> /// Gets or sets the overall request timeout. /// </summary> public TimeSpan OverallTimeout { get => this.httpClient.Timeout; set { try { this.httpClient.Timeout = value; } catch (InvalidOperationException exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.NotAllowed, Message = ErrorConstants.Messages.OverallTimeoutCannotBeSet, }, exception); } } } /// <summary> /// Sends the request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to send.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> public Task<HttpResponseMessage> SendAsync(HttpRequestMessage request) { return this.SendAsync(request, HttpCompletionOption.ResponseContentRead, CancellationToken.None); } /// <summary> /// Sends the request. /// </summary> /// <param name="request">The <see cref="HttpRequestMessage"/> to send.</param> /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="HttpResponseMessage"/>.</returns> public async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { var response = await this.SendRequestAsync(request, completionOption, cancellationToken).ConfigureAwait(false); // check if the response is of a successful nature. if (!response.IsSuccessStatusCode) { using (response) { if (null != response.Content) { await response.Content.LoadIntoBufferAsync().ConfigureAwait(false); } var errorResponse = await this.ConvertErrorResponseAsync(response).ConfigureAwait(false); Error error; if (errorResponse == null || errorResponse.Error == null) { if (response.StatusCode == HttpStatusCode.NotFound) { error = new Error { Code = ErrorConstants.Codes.ItemNotFound }; } else { error = new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.UnexpectedExceptionResponse, }; } } else { error = errorResponse.Error; } if (string.IsNullOrEmpty(error.ThrowSite)) { if (response.Headers.TryGetValues(CoreConstants.Headers.ThrowSiteHeaderName, out var throwSiteValues)) { error.ThrowSite = throwSiteValues.FirstOrDefault(); } } if (string.IsNullOrEmpty(error.ClientRequestId)) { if (response.Headers.TryGetValues(CoreConstants.Headers.ClientRequestId, out var clientRequestId)) { error.ClientRequestId = clientRequestId.FirstOrDefault(); } } if (response.Content?.Headers.ContentType.MediaType == "application/json") { string rawResponseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false); throw new ServiceException(error, response.Headers, response.StatusCode, rawResponseBody); } else { // Pass through the response headers and status code to the ServiceException. // System.Net.HttpStatusCode does not support RFC 6585, Additional HTTP Status Codes. // Throttling status code 429 is in RFC 6586. The status code 429 will be passed through. throw new ServiceException(error, response.Headers, response.StatusCode); } } } return response; } /// <summary> /// Disposes the HttpClient and HttpClientHandler instances. /// </summary> public void Dispose() { httpClient?.Dispose(); } /// <summary> /// Converts the <see cref="HttpRequestException"/> into an <see cref="ErrorResponse"/> object; /// </summary> /// <param name="response">The <see cref="HttpResponseMessage"/> to convert.</param> /// <returns>The <see cref="ErrorResponse"/> object.</returns> private async Task<ErrorResponse> ConvertErrorResponseAsync(HttpResponseMessage response) { try { using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) { return this.Serializer.DeserializeObject<ErrorResponse>(responseStream); } } catch (Exception) { // If there's an exception deserializing the error response return null and throw a generic // ServiceException later. return null; } } private async Task<HttpResponseMessage> SendRequestAsync( HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken) { try { return await this.httpClient.SendAsync(request, completionOption, cancellationToken).ConfigureAwait(false); } catch (TaskCanceledException exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.Timeout, Message = ErrorConstants.Messages.RequestTimedOut, }, exception); } catch (ServiceException) { throw; } catch (Exception exception) { throw new ServiceException( new Error { Code = ErrorConstants.Codes.GeneralException, Message = ErrorConstants.Messages.UnexpectedExceptionOnSend, }, exception); } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Koffee.WebAPI.Areas.HelpPage.ModelDescriptions; using Koffee.WebAPI.Areas.HelpPage.Models; namespace Koffee.WebAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="MetaType.cs" company="CODE Insiders LTD"> // // Copyright 2013-2015 CODE Insiders LTD // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace CodeInsiders.SharpQL { using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Data.OleDb; using System.Data.SqlTypes; using System.IO; using System.Xml; using CodeInsiders.SharpQL.Helpers; using CodeInsiders.SharpQL.Helpers.Internal; using Microsoft.SqlServer.Server; internal sealed class MetaType { internal static readonly MetaType MetaDateTimeOffset = new MetaType( byte.MaxValue, 7, -1, false, false, false, 43, 43, "datetimeoffset", typeof(DateTimeOffset), typeof(DateTimeOffset), SqlDbType.DateTimeOffset, DbType.DateTimeOffset, 1); /// <summary> /// The meta decimal. /// </summary> internal static readonly MetaType MetaDecimal = new MetaType( 38, 4, 17, true, false, false, 108, 108, "decimal", typeof(Decimal), typeof(SqlDecimal), SqlDbType.Decimal, DbType.Decimal, 2); /// <summary> /// The meta image. /// </summary> internal static readonly MetaType MetaImage = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, false, 34, 34, "image", typeof(byte[]), typeof(SqlBinary), SqlDbType.Image, DbType.Binary, 0); /// <summary> /// The meta max n var char. /// </summary> internal static readonly MetaType MetaMaxNVarChar = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, true, 231, 231, "nvarchar", typeof(string), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); /// <summary> /// The meta max var binary. /// </summary> internal static readonly MetaType MetaMaxVarBinary = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, true, 165, 165, "varbinary", typeof(byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); /// <summary> /// The meta max var char. /// </summary> internal static readonly MetaType MetaMaxVarChar = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, true, 167, 167, "varchar", typeof(string), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); /// <summary> /// The meta n text. /// </summary> internal static readonly MetaType MetaNText = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, false, 99, 99, "ntext", typeof(string), typeof(SqlString), SqlDbType.NText, DbType.String, 7); /// <summary> /// The meta n var char. /// </summary> internal static readonly MetaType MetaNVarChar = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 231, 231, "nvarchar", typeof(string), typeof(SqlString), SqlDbType.NVarChar, DbType.String, 7); /// <summary> /// The meta text. /// </summary> internal static readonly MetaType MetaText = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, false, 35, 35, "text", typeof(string), typeof(SqlString), SqlDbType.Text, DbType.AnsiString, 0); /// <summary> /// The meta time. /// </summary> internal static readonly MetaType MetaTime = new MetaType( byte.MaxValue, 7, -1, false, false, false, 41, 41, "time", typeof(TimeSpan), typeof(TimeSpan), SqlDbType.Time, DbType.Time, 1); /// <summary> /// The meta udt. /// </summary> internal static readonly MetaType MetaUdt = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, true, 240, 240, "udt", typeof(object), typeof(object), SqlDbType.Udt, DbType.Object, 0); /// <summary> /// The meta var binary. /// </summary> internal static readonly MetaType MetaVarBinary = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 165, 165, "varbinary", typeof(byte[]), typeof(SqlBinary), SqlDbType.VarBinary, DbType.Binary, 2); /// <summary> /// The meta xml. /// </summary> internal static readonly MetaType MetaXml = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, true, 241, 241, "xml", typeof(string), typeof(SqlXml), SqlDbType.Xml, DbType.Xml, 0); /// <summary> /// The meta big int. /// </summary> private static readonly MetaType MetaBigInt = new MetaType( 19, byte.MaxValue, 8, true, false, false, 127, 38, "bigint", typeof(long), typeof(SqlInt64), SqlDbType.BigInt, DbType.Int64, 0); /// <summary> /// The meta binary. /// </summary> private static readonly MetaType MetaBinary = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 173, 173, "binary", typeof(byte[]), typeof(SqlBinary), SqlDbType.Binary, DbType.Binary, 2); /// <summary> /// The meta bit. /// </summary> private static readonly MetaType MetaBit = new MetaType( byte.MaxValue, byte.MaxValue, 1, true, false, false, 50, 104, "bit", typeof(bool), typeof(SqlBoolean), SqlDbType.Bit, DbType.Boolean, 0); /// <summary> /// The meta char. /// </summary> private static readonly MetaType MetaChar = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 175, 175, "char", typeof(string), typeof(SqlString), SqlDbType.Char, DbType.AnsiStringFixedLength, 7); /// <summary> /// The meta date. /// </summary> private static readonly MetaType MetaDate = new MetaType( byte.MaxValue, byte.MaxValue, 3, true, false, false, 40, 40, "date", typeof(DateTime), typeof(DateTime), SqlDbType.Date, DbType.Date, 0); /// <summary> /// The meta date time. /// </summary> private static readonly MetaType MetaDateTime = new MetaType( 23, 3, 8, true, false, false, 61, 111, "datetime", typeof(DateTime), typeof(SqlDateTime), SqlDbType.DateTime, DbType.DateTime, 0); /// <summary> /// The meta date time 2. /// </summary> private static readonly MetaType MetaDateTime2 = new MetaType( byte.MaxValue, 7, -1, false, false, false, 42, 42, "datetime2", typeof(DateTime), typeof(DateTime), SqlDbType.DateTime2, DbType.DateTime2, 1); /// <summary> /// The meta float. /// </summary> private static readonly MetaType MetaFloat = new MetaType( 15, byte.MaxValue, 8, true, false, false, 62, 109, "float", typeof(double), typeof(SqlDouble), SqlDbType.Float, DbType.Double, 0); /// <summary> /// The meta int. /// </summary> private static readonly MetaType MetaInt = new MetaType( 10, byte.MaxValue, 4, true, false, false, 56, 38, "int", typeof(int), typeof(SqlInt32), SqlDbType.Int, DbType.Int32, 0); /// <summary> /// The meta max udt. /// </summary> private static readonly MetaType MetaMaxUdt = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, true, true, 240, 240, "udt", typeof(object), typeof(object), SqlDbType.Udt, DbType.Object, 0); /// <summary> /// The meta money. /// </summary> private static readonly MetaType MetaMoney = new MetaType( 19, byte.MaxValue, 8, true, false, false, 60, 110, "money", typeof(Decimal), typeof(SqlMoney), SqlDbType.Money, DbType.Currency, 0); /// <summary> /// The meta n char. /// </summary> private static readonly MetaType MetaNChar = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 239, 239, "nchar", typeof(string), typeof(SqlString), SqlDbType.NChar, DbType.StringFixedLength, 7); /// <summary> /// The meta real. /// </summary> private static readonly MetaType MetaReal = new MetaType( 7, byte.MaxValue, 4, true, false, false, 59, 109, "real", typeof(float), typeof(SqlSingle), SqlDbType.Real, DbType.Single, 0); /// <summary> /// The meta sudt. /// </summary> private static readonly MetaType MetaSUDT = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 31, 31, string.Empty, typeof(SqlDataRecord), typeof(SqlDataRecord), SqlDbType.Structured, DbType.Object, 0); /// <summary> /// The meta small date time. /// </summary> private static readonly MetaType MetaSmallDateTime = new MetaType( 16, 0, 4, true, false, false, 58, 111, "smalldatetime", typeof(DateTime), typeof(SqlDateTime), SqlDbType.SmallDateTime, DbType.DateTime, 0); /// <summary> /// The meta small int. /// </summary> private static readonly MetaType MetaSmallInt = new MetaType( 5, byte.MaxValue, 2, true, false, false, 52, 38, "smallint", typeof(short), typeof(SqlInt16), SqlDbType.SmallInt, DbType.Int16, 0); /// <summary> /// The meta small money. /// </summary> private static readonly MetaType MetaSmallMoney = new MetaType( 10, byte.MaxValue, 4, true, false, false, 122, 110, "smallmoney", typeof(Decimal), typeof(SqlMoney), SqlDbType.SmallMoney, DbType.Currency, 0); /// <summary> /// The meta small var binary. /// </summary> private static readonly MetaType MetaSmallVarBinary = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 37, 173, string.Empty, typeof(byte[]), typeof(SqlBinary), (SqlDbType)24, DbType.Binary, 2); /// <summary> /// The meta table. /// </summary> private static readonly MetaType MetaTable = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 243, 243, "table", typeof(IEnumerable<DbDataRecord>), typeof(IEnumerable<DbDataRecord>), SqlDbType.Structured, DbType.Object, 0); /// <summary> /// The meta timestamp. /// </summary> private static readonly MetaType MetaTimestamp = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 173, 173, "timestamp", typeof(byte[]), typeof(SqlBinary), SqlDbType.Timestamp, DbType.Binary, 2); /// <summary> /// The meta tiny int. /// </summary> private static readonly MetaType MetaTinyInt = new MetaType( 3, byte.MaxValue, 1, true, false, false, 48, 38, "tinyint", typeof(byte), typeof(SqlByte), SqlDbType.TinyInt, DbType.Byte, 0); /// <summary> /// The meta unique id. /// </summary> private static readonly MetaType MetaUniqueId = new MetaType( byte.MaxValue, byte.MaxValue, 16, true, false, false, 36, 36, "uniqueidentifier", typeof(Guid), typeof(SqlGuid), SqlDbType.UniqueIdentifier, DbType.Guid, 0); /// <summary> /// The meta var char. /// </summary> private static readonly MetaType MetaVarChar = new MetaType( byte.MaxValue, byte.MaxValue, -1, false, false, false, 167, 167, "varchar", typeof(string), typeof(SqlString), SqlDbType.VarChar, DbType.AnsiString, 7); /// <summary> /// The meta variant. /// </summary> private static readonly MetaType MetaVariant = new MetaType( byte.MaxValue, byte.MaxValue, -1, true, false, false, 98, 98, "sql_variant", typeof(object), typeof(object), SqlDbType.Variant, DbType.Object, 0); internal readonly Type ClassType; internal readonly DbType DbType; internal readonly int FixedLength; internal readonly bool Is100Supported; internal readonly bool Is70Supported; internal readonly bool Is80Supported; internal readonly bool Is90Supported; internal readonly bool IsAnsiType; internal readonly bool IsBinType; internal readonly bool IsCharType; internal readonly bool IsFixed; internal readonly bool IsLong; internal readonly bool IsNCharType; internal readonly bool IsNewKatmaiType; internal readonly bool IsPlp; internal readonly bool IsSizeInCharacters; internal readonly bool IsVarTime; internal readonly byte NullableType; internal readonly byte Precision; internal readonly byte PropBytes; internal readonly byte Scale; internal readonly SqlDbType SqlDbType; internal readonly Type SqlType; internal readonly byte TDSType; internal readonly string TypeName; static MetaType() {} public MetaType( byte precision, byte scale, int fixedLength, bool isFixed, bool isLong, bool isPlp, byte tdsType, byte nullableTdsType, string typeName, Type classType, Type sqlType, SqlDbType sqldbType, DbType dbType, byte propBytes) { this.Precision = precision; this.Scale = scale; this.FixedLength = fixedLength; this.IsFixed = isFixed; this.IsLong = isLong; this.IsPlp = isPlp; this.TDSType = tdsType; this.NullableType = nullableTdsType; this.TypeName = typeName; this.SqlDbType = sqldbType; this.DbType = dbType; this.ClassType = classType; this.SqlType = sqlType; this.PropBytes = propBytes; this.IsAnsiType = _IsAnsiType(sqldbType); this.IsBinType = _IsBinType(sqldbType); this.IsCharType = _IsCharType(sqldbType); this.IsNCharType = _IsNCharType(sqldbType); this.IsSizeInCharacters = _IsSizeInCharacters(sqldbType); this.IsNewKatmaiType = _IsNewKatmaiType(sqldbType); this.IsVarTime = _IsVarTime(sqldbType); this.Is70Supported = _Is70Supported(this.SqlDbType); this.Is80Supported = _Is80Supported(this.SqlDbType); this.Is90Supported = _Is90Supported(this.SqlDbType); this.Is100Supported = _Is100Supported(this.SqlDbType); } public int TypeId { get { return 0; } } public static TdsDateTime FromDateTime(DateTime dateTime, byte cb) { var tdsDateTime = new TdsDateTime(); SqlDateTime sqlDateTime; if (cb == 8) { sqlDateTime = new SqlDateTime(dateTime); tdsDateTime.time = sqlDateTime.TimeTicks; } else { sqlDateTime = new SqlDateTime(dateTime.AddSeconds(30.0)); tdsDateTime.time = sqlDateTime.TimeTicks / SqlDateTime.SQLTicksPerMinute; } tdsDateTime.days = sqlDateTime.DayTicks; return tdsDateTime; } public static DateTime ToDateTime(int sqlDays, int sqlTime, int length) { if (length == 4) { return new SqlDateTime(sqlDays, sqlTime * SqlDateTime.SQLTicksPerMinute).Value; } return new SqlDateTime(sqlDays, sqlTime).Value; } internal static object GetComValueFromSqlVariant(object sqlVal) { object obj = null; if (ADP.IsNull(sqlVal)) { return obj; } if (sqlVal is SqlSingle) { obj = ((SqlSingle)sqlVal).Value; } else if (sqlVal is SqlString) { obj = ((SqlString)sqlVal).Value; } else if (sqlVal is SqlDouble) { obj = ((SqlDouble)sqlVal).Value; } else if (sqlVal is SqlBinary) { obj = ((SqlBinary)sqlVal).Value; } else if (sqlVal is SqlGuid) { obj = ((SqlGuid)sqlVal).Value; } else if (sqlVal is SqlBoolean) { obj = ((SqlBoolean)sqlVal).Value; } else if (sqlVal is SqlByte) { obj = ((SqlByte)sqlVal).Value; } else if (sqlVal is SqlInt16) { obj = ((SqlInt16)sqlVal).Value; } else if (sqlVal is SqlInt32) { obj = ((SqlInt32)sqlVal).Value; } else if (sqlVal is SqlInt64) { obj = ((SqlInt64)sqlVal).Value; } else if (sqlVal is SqlDecimal) { obj = ((SqlDecimal)sqlVal).Value; } else if (sqlVal is SqlDateTime) { obj = ((SqlDateTime)sqlVal).Value; } else if (sqlVal is SqlMoney) { obj = ((SqlMoney)sqlVal).Value; } else if (sqlVal is SqlXml) { obj = ((SqlXml)sqlVal).Value; } return obj; } internal static MetaType GetDefaultMetaType() { return MetaNVarChar; } internal static MetaType GetMaxMetaTypeFromMetaType(MetaType mt) { switch (mt.SqlDbType) { case SqlDbType.VarBinary: case SqlDbType.Binary: return MetaMaxVarBinary; case SqlDbType.VarChar: case SqlDbType.Char: return MetaMaxVarChar; case SqlDbType.Udt: return MetaMaxUdt; case SqlDbType.NChar: case SqlDbType.NVarChar: return MetaMaxNVarChar; default: return mt; } } internal static MetaType GetMetaTypeFromDbType(DbType target) { switch (target) { case DbType.AnsiString: return MetaVarChar; case DbType.Binary: return MetaVarBinary; case DbType.Byte: return MetaTinyInt; case DbType.Boolean: return MetaBit; case DbType.Currency: return MetaMoney; case DbType.Date: case DbType.DateTime: return MetaDateTime; case DbType.Decimal: return MetaDecimal; case DbType.Double: return MetaFloat; case DbType.Guid: return MetaUniqueId; case DbType.Int16: return MetaSmallInt; case DbType.Int32: return MetaInt; case DbType.Int64: return MetaBigInt; case DbType.Object: return MetaVariant; case DbType.Single: return MetaReal; case DbType.String: return MetaNVarChar; case DbType.Time: return MetaDateTime; case DbType.AnsiStringFixedLength: return MetaChar; case DbType.StringFixedLength: return MetaNChar; case DbType.Xml: return MetaXml; case DbType.DateTime2: return MetaDateTime2; case DbType.DateTimeOffset: return MetaDateTimeOffset; default: throw new ArgumentException(string.Format("DbTypeNotSupported {0}", typeof(SqlDbType))); // throw ADP.DbTypeNotSupported(target, typeof(SqlDbType)); } } internal static MetaType GetMetaTypeFromSqlDbType(SqlDbType target, bool isMultiValued) { switch (target) { case SqlDbType.BigInt: return MetaBigInt; case SqlDbType.Binary: return MetaBinary; case SqlDbType.Bit: return MetaBit; case SqlDbType.Char: return MetaChar; case SqlDbType.DateTime: return MetaDateTime; case SqlDbType.Decimal: return MetaDecimal; case SqlDbType.Float: return MetaFloat; case SqlDbType.Image: return MetaImage; case SqlDbType.Int: return MetaInt; case SqlDbType.Money: return MetaMoney; case SqlDbType.NChar: return MetaNChar; case SqlDbType.NText: return MetaNText; case SqlDbType.NVarChar: return MetaNVarChar; case SqlDbType.Real: return MetaReal; case SqlDbType.UniqueIdentifier: return MetaUniqueId; case SqlDbType.SmallDateTime: return MetaSmallDateTime; case SqlDbType.SmallInt: return MetaSmallInt; case SqlDbType.SmallMoney: return MetaSmallMoney; case SqlDbType.Text: return MetaText; case SqlDbType.Timestamp: return MetaTimestamp; case SqlDbType.TinyInt: return MetaTinyInt; case SqlDbType.VarBinary: return MetaVarBinary; case SqlDbType.VarChar: return MetaVarChar; case SqlDbType.Variant: return MetaVariant; case (SqlDbType)24: return MetaSmallVarBinary; case SqlDbType.Xml: return MetaXml; case SqlDbType.Udt: return MetaUdt; case SqlDbType.Structured: if (isMultiValued) { return MetaTable; } return MetaSUDT; case SqlDbType.Date: return MetaDate; case SqlDbType.Time: return MetaTime; case SqlDbType.DateTime2: return MetaDateTime2; case SqlDbType.DateTimeOffset: return MetaDateTimeOffset; default: throw new ArgumentOutOfRangeException("target", target, "Invalid SqlDbType"); } } internal static MetaType GetMetaTypeFromType(Type dataType) { return GetMetaTypeFromValue(dataType, null, false, true); } internal static MetaType GetMetaTypeFromValue(object value, bool streamAllowed = true) { if (value == null) { throw new ArgumentNullException("value"); } return GetMetaTypeFromValue(value.GetType(), value, true, streamAllowed); } internal static object GetNullSqlValue(Type sqlType) { if (sqlType == typeof(SqlSingle)) { return SqlSingle.Null; } if (sqlType == typeof(SqlString)) { return SqlString.Null; } if (sqlType == typeof(SqlDouble)) { return SqlDouble.Null; } if (sqlType == typeof(SqlBinary)) { return SqlBinary.Null; } if (sqlType == typeof(SqlGuid)) { return SqlGuid.Null; } if (sqlType == typeof(SqlBoolean)) { return SqlBoolean.Null; } if (sqlType == typeof(SqlByte)) { return SqlByte.Null; } if (sqlType == typeof(SqlInt16)) { return SqlInt16.Null; } if (sqlType == typeof(SqlInt32)) { return SqlInt32.Null; } if (sqlType == typeof(SqlInt64)) { return SqlInt64.Null; } if (sqlType == typeof(SqlDecimal)) { return SqlDecimal.Null; } if (sqlType == typeof(SqlDateTime)) { return SqlDateTime.Null; } if (sqlType == typeof(SqlMoney)) { return SqlMoney.Null; } if (sqlType == typeof(SqlXml)) { return SqlXml.Null; } if (sqlType == typeof(object)) { return DBNull.Value; } if (sqlType == typeof(IEnumerable<DbDataRecord>)) { return DBNull.Value; } if (sqlType == typeof(DataTable)) { return DBNull.Value; } if (sqlType == typeof(DateTime)) { return DBNull.Value; } if (sqlType == typeof(TimeSpan)) { return DBNull.Value; } if (sqlType == typeof(DateTimeOffset)) { return DBNull.Value; } return DBNull.Value; } internal static MetaType GetSqlDataType(int tdsType, uint userType, int length) { switch (tdsType) { case 231: return MetaNVarChar; case 239: return MetaNChar; case 240: return MetaUdt; case 241: return MetaXml; case 243: return MetaTable; case 165: return MetaVarBinary; case 167: case 39: return MetaVarChar; case 173: case 45: if (80 != (int)userType) { return MetaBinary; } return MetaTimestamp; case 175: case 47: return MetaChar; case 122: return MetaSmallMoney; case sbyte.MaxValue: return MetaBigInt; case 34: return MetaImage; case 35: return MetaText; case 36: return MetaUniqueId; case 37: return MetaSmallVarBinary; case 38: if (4 > length) { if (2 != length) { return MetaTinyInt; } return MetaSmallInt; } if (4 != length) { return MetaBigInt; } return MetaInt; case 40: return MetaDate; case 41: return MetaTime; case 42: return MetaDateTime2; case 43: return MetaDateTimeOffset; case 48: return MetaTinyInt; case 50: case 104: return MetaBit; case 52: return MetaSmallInt; case 56: return MetaInt; case 58: return MetaSmallDateTime; case 59: return MetaReal; case 60: return MetaMoney; case 61: return MetaDateTime; case 62: return MetaFloat; case 98: return MetaVariant; case 99: return MetaNText; case 106: case 108: return MetaDecimal; case 109: if (4 != length) { return MetaFloat; } return MetaReal; case 110: if (4 != length) { return MetaMoney; } return MetaSmallMoney; case 111: if (4 != length) { return MetaDateTime; } return MetaSmallDateTime; default: throw new ArgumentOutOfRangeException("tdsType"); } } internal static SqlDbType GetSqlDbTypeFromOleDbType(short dbType, string typeName) { var sqlDbType = SqlDbType.Variant; switch ((OleDbType)dbType) { case OleDbType.Guid: sqlDbType = SqlDbType.UniqueIdentifier; break; case OleDbType.Binary: case OleDbType.VarBinary: sqlDbType = typeName == "binary" ? SqlDbType.Binary : SqlDbType.VarBinary; break; case OleDbType.Char: case OleDbType.VarChar: sqlDbType = typeName == "char" ? SqlDbType.Char : SqlDbType.VarChar; break; case OleDbType.WChar: case OleDbType.VarWChar: case OleDbType.BSTR: sqlDbType = typeName == "nchar" ? SqlDbType.NChar : SqlDbType.NVarChar; break; case OleDbType.Numeric: case OleDbType.Decimal: sqlDbType = SqlDbType.Decimal; break; case (OleDbType)132: sqlDbType = SqlDbType.Udt; break; case OleDbType.DBDate: sqlDbType = SqlDbType.Date; break; case OleDbType.DBTimeStamp: case OleDbType.Date: case OleDbType.Filetime: switch (typeName) { case "smalldatetime": sqlDbType = SqlDbType.SmallDateTime; break; case "datetime2": sqlDbType = SqlDbType.DateTime2; break; default: sqlDbType = SqlDbType.DateTime; break; } break; case (OleDbType)141: sqlDbType = SqlDbType.Xml; break; case (OleDbType)145: sqlDbType = SqlDbType.Time; break; case (OleDbType)146: sqlDbType = SqlDbType.DateTimeOffset; break; case OleDbType.LongVarChar: sqlDbType = SqlDbType.Text; break; case OleDbType.LongVarWChar: sqlDbType = SqlDbType.NText; break; case OleDbType.LongVarBinary: sqlDbType = SqlDbType.Image; break; case OleDbType.SmallInt: case OleDbType.UnsignedSmallInt: sqlDbType = SqlDbType.SmallInt; break; case OleDbType.Integer: sqlDbType = SqlDbType.Int; break; case OleDbType.Single: sqlDbType = SqlDbType.Real; break; case OleDbType.Double: sqlDbType = SqlDbType.Float; break; case OleDbType.Currency: sqlDbType = typeName == "smallmoney" ? SqlDbType.SmallMoney : SqlDbType.Money; break; case OleDbType.Boolean: sqlDbType = SqlDbType.Bit; break; case OleDbType.Variant: sqlDbType = SqlDbType.Variant; break; case OleDbType.TinyInt: case OleDbType.UnsignedTinyInt: sqlDbType = SqlDbType.TinyInt; break; case OleDbType.BigInt: sqlDbType = SqlDbType.BigInt; break; } return sqlDbType; } internal static object GetSqlValueFromComVariant(object comVal) { object obj = null; if (comVal != null && DBNull.Value != comVal) { if (comVal is float) { obj = new SqlSingle((float)comVal); } else if (comVal is string) { obj = new SqlString((string)comVal); } else if (comVal is double) { obj = new SqlDouble((double)comVal); } else if (comVal is byte[]) { obj = new SqlBinary((byte[])comVal); } else if (comVal is char) { obj = new SqlString(((char)comVal).ToString()); } else if (comVal is char[]) { obj = new SqlChars((char[])comVal); } else if (comVal is Guid) { obj = new SqlGuid((Guid)comVal); } else if (comVal is bool) { obj = new SqlBoolean((bool)comVal); } else if (comVal is byte) { obj = new SqlByte((byte)comVal); } else if (comVal is short) { obj = new SqlInt16((short)comVal); } else if (comVal is int) { obj = new SqlInt32((int)comVal); } else if (comVal is long) { obj = new SqlInt64((long)comVal); } else if (comVal is Decimal) { obj = new SqlDecimal((Decimal)comVal); } else if (comVal is DateTime) { obj = new SqlDateTime((DateTime)comVal); } else if (comVal is XmlReader) { obj = new SqlXml((XmlReader)comVal); } else if (comVal is TimeSpan || comVal is DateTimeOffset) { obj = comVal; } } return obj; } internal static string GetStringFromXml(XmlReader xmlreader) { return new SqlXml(xmlreader).Value; } internal static int GetTimeSizeFromScale(byte scale) { if (scale <= 2) { return 3; } return (int)scale <= 4 ? 4 : 5; } internal static MetaType PromoteStringType(string s) { if (s.Length << 1 > 8000) { return MetaVarChar; } return MetaNVarChar; } internal static bool _IsVarTime(SqlDbType type) { if (type != SqlDbType.Time && type != SqlDbType.DateTime2) { return type == SqlDbType.DateTimeOffset; } return true; } private static MetaType GetMetaTypeFromValue(Type dataType, object value, bool inferLen, bool streamAllowed) { switch (Type.GetTypeCode(dataType)) { case TypeCode.Empty: throw new ArgumentException("Invalid DataType TypeCode.Empty"); case TypeCode.Object: if (dataType == typeof(byte[])) { if (!inferLen || ((byte[])value).Length <= 8000) { return MetaVarBinary; } return MetaImage; } if (dataType == typeof(Guid)) { return MetaUniqueId; } if (dataType == typeof(object)) { return MetaVariant; } if (dataType == typeof(SqlBinary)) { return MetaVarBinary; } if (dataType == typeof(SqlBoolean)) { return MetaBit; } if (dataType == typeof(SqlByte)) { return MetaTinyInt; } if (dataType == typeof(SqlBytes)) { return MetaVarBinary; } if (dataType == typeof(SqlChars)) { return MetaNVarChar; } if (dataType == typeof(SqlDateTime)) { return MetaDateTime; } if (dataType == typeof(SqlDouble)) { return MetaFloat; } if (dataType == typeof(SqlGuid)) { return MetaUniqueId; } if (dataType == typeof(SqlInt16)) { return MetaSmallInt; } if (dataType == typeof(SqlInt32)) { return MetaInt; } if (dataType == typeof(SqlInt64)) { return MetaBigInt; } if (dataType == typeof(SqlMoney)) { return MetaMoney; } if (dataType == typeof(SqlDecimal)) { return MetaDecimal; } if (dataType == typeof(SqlSingle)) { return MetaReal; } if (dataType == typeof(SqlXml)) { return MetaXml; } if (dataType == typeof(SqlString)) { if (!inferLen || ((SqlString)value).IsNull) { return MetaNVarChar; } return PromoteStringType(((SqlString)value).Value); } if (dataType == typeof(IEnumerable<DbDataRecord>) || dataType == typeof(DataTable)) { return MetaTable; } if (dataType == typeof(TimeSpan)) { return MetaTime; } if (dataType == typeof(DateTimeOffset)) { return MetaDateTimeOffset; } if (SqlUdtInfo.TryGetFromType(dataType) != null) { return MetaUdt; } if (streamAllowed) { if (typeof(Stream).IsAssignableFrom(dataType)) { return MetaVarBinary; } if (typeof(TextReader).IsAssignableFrom(dataType)) { return MetaNVarChar; } if (typeof(XmlReader).IsAssignableFrom(dataType)) { return MetaXml; } } throw new ArgumentException(string.Format("Unknown data type {0}", dataType)); // ADP.UnknownDataType(dataType); case TypeCode.DBNull: throw new ArgumentException("Invalid data type TypeCode.DBNull"); // ADP.InvalidDataType(TypeCode.DBNull); case TypeCode.Boolean: return MetaBit; case TypeCode.Char: return MetaNChar; throw new ArgumentException("Invalid data type TypeCode.Char"); // ADP.InvalidDataType(TypeCode.Char); case TypeCode.SByte: throw new ArgumentException("Invalid data type TypeCode.SByte"); // ADP.InvalidDataType(TypeCode.SByte); case TypeCode.Byte: return MetaTinyInt; case TypeCode.Int16: return MetaSmallInt; case TypeCode.UInt16: return MetaSmallInt; // throw new ArgumentException("Invalid data type TypeCode.UInt16)"); case TypeCode.Int32: return MetaInt; case TypeCode.UInt32: return MetaInt; // throw new ArgumentException("Invalid data type TypeCode.UInt32"); case TypeCode.Int64: return MetaBigInt; case TypeCode.UInt64: return MetaBigInt; // throw new ArgumentException("Invalid data type TypeCode.UInt64"); case TypeCode.Single: return MetaReal; case TypeCode.Double: return MetaFloat; case TypeCode.Decimal: return MetaDecimal; case TypeCode.DateTime: return MetaDateTime; case TypeCode.String: if (!inferLen) { return MetaNVarChar; } return PromoteStringType((string)value); default: throw new ArgumentException( string.Format("Unknown DataTypeCode {0}, {1}", dataType, Type.GetTypeCode(dataType))); } } private static bool _Is100Supported(SqlDbType type) { if (!_Is90Supported(type) && SqlDbType.Date != type && (SqlDbType.Time != type && SqlDbType.DateTime2 != type)) { return SqlDbType.DateTimeOffset == type; } return true; } private static bool _Is70Supported(SqlDbType type) { if (type != SqlDbType.BigInt && type > SqlDbType.BigInt) { return type <= SqlDbType.VarChar; } return false; } private static bool _Is80Supported(SqlDbType type) { if (type >= SqlDbType.BigInt) { return type <= SqlDbType.Variant; } return false; } private static bool _Is90Supported(SqlDbType type) { if (!_Is80Supported(type) && SqlDbType.Xml != type) { return SqlDbType.Udt == type; } return true; } private static bool _IsAnsiType(SqlDbType type) { if (type != SqlDbType.Char && type != SqlDbType.VarChar) { return type == SqlDbType.Text; } return true; } private static bool _IsBinType(SqlDbType type) { if (type != SqlDbType.Image && type != SqlDbType.Binary && (type != SqlDbType.VarBinary && type != SqlDbType.Timestamp) && type != SqlDbType.Udt) { return type == (SqlDbType)24; } return true; } private static bool _IsCharType(SqlDbType type) { if (type != SqlDbType.NChar && type != SqlDbType.NVarChar && (type != SqlDbType.NText && type != SqlDbType.Char) && (type != SqlDbType.VarChar && type != SqlDbType.Text)) { return type == SqlDbType.Xml; } return true; } private static bool _IsNCharType(SqlDbType type) { if (type != SqlDbType.NChar && type != SqlDbType.NVarChar && type != SqlDbType.NText) { return type == SqlDbType.Xml; } return true; } private static bool _IsNewKatmaiType(SqlDbType type) { return SqlDbType.Structured == type; } private static bool _IsSizeInCharacters(SqlDbType type) { if (type != SqlDbType.NChar && type != SqlDbType.NVarChar && type != SqlDbType.Xml) { return type == SqlDbType.NText; } return true; } private static class ADP { internal static bool IsNull(object value) { if (value == null || DBNull.Value == value) { return true; } var nullable = value as INullable; if (nullable != null) { return nullable.IsNull; } return false; } } } internal struct TdsDateTime { public int days; public int time; } }
// <copyright file="Processing.cs" company="Public Domain"> // Released into the public domain // </copyright> // This file is part of the C# Packet Capture Analyser application. It is // free and unencumbered software released into the public domain as detailed // in the UNLICENSE file in the top level directory of this distribution namespace PacketCaptureAnalyzer.EthernetFrame.IPPacket.TCPPacket { /// <summary> /// This class provides the TCP packet processing /// </summary> public class Processing { /// <summary> /// The object that provides for the logging of debug information /// </summary> private Analysis.DebugInformation theDebugInformation; /// <summary> /// The object that provides for binary reading from the packet capture /// </summary> private System.IO.BinaryReader theBinaryReader; // TODO Remove these suppressions once the method uses these parameters [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "performLatencyAnalysisProcessing", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "theLatencyAnalysisProcessing", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "performBurstAnalysisProcessing", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "theBurstAnalysisProcessing", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "performTimeAnalysisProcessing", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "theTimeAnalysisProcessing", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "useAlternativeSequenceNumber", Justification = "Parameter not used as method is not fully implemented")] /// <summary> /// Initializes a new instance of the Processing class /// </summary> /// <param name="theDebugInformation">The object that provides for the logging of debug information</param> /// <param name="theBinaryReader">The object that provides for binary reading from the packet capture</param> /// <param name="performLatencyAnalysisProcessing">Boolean flag that indicates whether to perform latency analysis processing for data read from the packet capture</param> /// <param name="theLatencyAnalysisProcessing">The object that provides the latency analysis processing for data read from the packet capture</param> /// <param name="performBurstAnalysisProcessing">Boolean flag that indicates whether to perform burst analysis processing for data read from the packet capture</param> /// <param name="theBurstAnalysisProcessing">The object that provides the burst analysis processing for data read from the packet capture</param> /// <param name="performTimeAnalysisProcessing">Boolean flag that indicates whether to perform time analysis processing for data read from the packet capture</param> /// <param name="theTimeAnalysisProcessing">The object that provides the time analysis processing for data read from the packet capture</param> /// <param name="useAlternativeSequenceNumber">Boolean flag that indicates whether to use the alternative sequence number in the data read from the packet capture, required for legacy recordings</param> public Processing(Analysis.DebugInformation theDebugInformation, System.IO.BinaryReader theBinaryReader, bool performLatencyAnalysisProcessing, Analysis.LatencyAnalysis.Processing theLatencyAnalysisProcessing, bool performBurstAnalysisProcessing, Analysis.BurstAnalysis.Processing theBurstAnalysisProcessing, bool performTimeAnalysisProcessing, Analysis.TimeAnalysis.Processing theTimeAnalysisProcessing, bool useAlternativeSequenceNumber) { this.theDebugInformation = theDebugInformation; this.theBinaryReader = theBinaryReader; } /// <summary> /// Processes a TCP packet /// </summary> /// <param name="thePacketNumber">The number for the packet read from the packet capture</param> /// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param> /// <param name="theIPPacketPayloadLength">The length of the payload of the IP v4/v6 packet</param> /// <returns>Boolean flag that indicates whether the TCP packet could be processed</returns> public bool ProcessTCPPacket(ulong thePacketNumber, double thePacketTimestamp, ushort theIPPacketPayloadLength) { bool theResult = true; ushort theTCPPacketPayloadLength = 0; ushort theTCPPacketSourcePort = 0; ushort theTCPPacketDestinationPort = 0; // Process the TCP packet header theResult = this.ProcessTCPPacketHeader( theIPPacketPayloadLength, out theTCPPacketPayloadLength, out theTCPPacketSourcePort, out theTCPPacketDestinationPort); if (theResult) { // Process the payload of the TCP packet, supplying the length of the payload and the values for the source port and the destination port as returned by the processing of the TCP packet header theResult = this.ProcessTCPPacketPayload( thePacketNumber, thePacketTimestamp, theTCPPacketPayloadLength, theTCPPacketSourcePort, theTCPPacketDestinationPort); } return theResult; } /// <summary> /// Processes a TCP packet header /// </summary> /// <param name="theIPPacketPayloadLength">The length of the payload of the IP v4/v6 packet</param> /// <param name="theTCPPacketPayloadLength">The length of the payload of the TCP packet</param> /// <param name="theTCPPacketSourcePort">The source port for the TCP packet</param> /// <param name="theTCPPacketDestinationPort">The destination port for the TCP packet</param> /// <returns>Boolean flag that indicates whether the TCP packet header could be processed</returns> private bool ProcessTCPPacketHeader(ushort theIPPacketPayloadLength, out ushort theTCPPacketPayloadLength, out ushort theTCPPacketSourcePort, out ushort theTCPPacketDestinationPort) { bool theResult = true; // Provide a default value for the output parameter for the length of the payload of the TCP packet theTCPPacketPayloadLength = 0; // Provide default values for the output parameters for source port and destination port theTCPPacketSourcePort = 0; theTCPPacketDestinationPort = 0; // Read the values for the TCP packet header from the packet capture // Set up the output parameter for source port using the value read from the TCP packet header theTCPPacketSourcePort = (ushort)System.Net.IPAddress.NetworkToHostOrder(this.theBinaryReader.ReadInt16()); // Set up the output parameter for destination port using the value read from the TCP packet header theTCPPacketDestinationPort = (ushort)System.Net.IPAddress.NetworkToHostOrder(this.theBinaryReader.ReadInt16()); // Just read off the bytes for the TCP packet header sequence number from the packet capture so we can move on this.theBinaryReader.ReadUInt32(); // Just read off the bytes for the TCP packet header acknowledgment number from the packet capture so we can move on this.theBinaryReader.ReadUInt32(); // Read off and store the the TCP packet header length, reserved fields and NS flag for use below byte theDataOffsetAndReservedAndNSFlag = this.theBinaryReader.ReadByte(); // Just read off the bytes for the TCP packet header flags from the packet capture so we can move on this.theBinaryReader.ReadByte(); // Just read off the bytes for the TCP packet header window size from the packet capture so we can move on this.theBinaryReader.ReadUInt16(); // Just read off the bytes for the TCP packet header checksum from the packet capture so we can move on this.theBinaryReader.ReadUInt16(); // Just read off the bytes for the TCP packet header urgent pointer from the packet capture so we can move on this.theBinaryReader.ReadUInt16(); // Determine the length of the TCP packet header // Need to first extract the length value from the combined TCP packet header length, reserved fields and NS flag field // We want the higher four bits from the combined TCP packet header length, reserved fields and NS flag field (as it's in a big endian representation) so do a bitwise OR with 0xF0 (i.e. 11110000 in binary) and shift down by four bits // The extracted length value is the length of the TCP packet header in 32-bit words so multiply by four to get the actual length in bytes of the TCP packet header ushort theTCPPacketHeaderLength = (ushort)(((theDataOffsetAndReservedAndNSFlag & 0xF0) >> 4) * 4); // Validate the TCP packet header theResult = this.ValidateTCPPacketHeader( theTCPPacketHeaderLength); if (theResult) { // Set up the output parameter for the length of the payload of the TCP packet, which is the total length of the TCP packet minus the length of the TCP packet header just calculated theTCPPacketPayloadLength = (ushort)(theIPPacketPayloadLength - theTCPPacketHeaderLength); if (theTCPPacketHeaderLength > Constants.HeaderMinimumLength) { // The TCP packet contains a header length which is greater than the minimum and so contains extra Options bytes at the end (e.g. timestamps from the capture application) // Just read off these remaining Options bytes of the TCP packet header from the packet capture so we can move on this.theBinaryReader.ReadBytes( theTCPPacketHeaderLength - Constants.HeaderMinimumLength); } } else { theTCPPacketPayloadLength = 0; } return theResult; } // TODO Remove these suppressions once the method uses these parameters [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "thePacketNumber", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "thePacketTimestamp", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "theTCPPacketSourcePort", Justification = "Parameter not used as method is not fully implemented")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "theTCPPacketDestinationPort", Justification = "Parameter not used as method is not fully implemented")] /// <summary> /// Processes the payload of the TCP packet /// </summary> /// <param name="thePacketNumber">The number for the packet read from the packet capture</param> /// <param name="thePacketTimestamp">The timestamp for the packet read from the packet capture</param> /// <param name="theTCPPacketPayloadLength">The length of the payload of the TCP packet</param> /// <param name="theTCPPacketSourcePort">The source port for the TCP packet</param> /// <param name="theTCPPacketDestinationPort">The destination port for the TCP packet</param> /// <returns>Boolean flag that indicates whether the payload of the TCP packet could be processed</returns> private bool ProcessTCPPacketPayload(ulong thePacketNumber, double thePacketTimestamp, ushort theTCPPacketPayloadLength, ushort theTCPPacketSourcePort, ushort theTCPPacketDestinationPort) { bool theResult = true; // Only process this TCP packet if the payload has a non-zero payload length i.e. it actually includes data so is not part of the three-way handshake or a plain acknowledgement if (theTCPPacketPayloadLength > 0) { // Change this logic statement to allow identification and processing of specific messages within the TCP packet if (false) { // TODO Put code here to identify and process specific messages within the TCP packet } else { // Just read off the remaining bytes of the TCP packet from the packet capture so we can move on // The remaining length is the supplied length of the TCP packet payload this.theBinaryReader.ReadBytes( theTCPPacketPayloadLength); } } return theResult; } /// <summary> /// Validates the TCP packet header /// </summary> /// <param name="theTCPPacketHeaderLength">The length of the TCP packet header</param> /// <returns>Boolean flag that indicates whether the TCP packet header is valid</returns> private bool ValidateTCPPacketHeader(ushort theTCPPacketHeaderLength) { bool theResult = true; if (theTCPPacketHeaderLength > Constants.HeaderMaximumLength || theTCPPacketHeaderLength < Constants.HeaderMinimumLength) { this.theDebugInformation.WriteErrorEvent( "The TCP packet contains a header length " + theTCPPacketHeaderLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + " which is outside the range " + Constants.HeaderMinimumLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + " to " + Constants.HeaderMaximumLength.ToString(System.Globalization.CultureInfo.CurrentCulture) + "!!!"); theResult = false; } return theResult; } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) Under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You Under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed Under the License is distributed on an "AS Is" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations Under the License. ==================================================================== */ namespace NPOI.HSSF.UserModel { using System; /// <summary> /// A client anchor Is attached to an excel worksheet. It anchors against a /// top-left and buttom-right cell. /// @author Glen Stampoultzis (glens at apache.org) /// </summary> internal class HSSFClientAnchor : HSSFAnchor, NPOI.SS.UserModel.IClientAnchor { int col1; int row1; int col2; int row2; int anchorType; /// <summary> /// Creates a new client anchor and defaults all the anchor positions to 0. /// </summary> public HSSFClientAnchor() { } /// <summary> /// Creates a new client anchor and Sets the top-left and bottom-right /// coordinates of the anchor. /// </summary> /// <param name="dx1">the x coordinate within the first cell.</param> /// <param name="dy1">the y coordinate within the first cell.</param> /// <param name="dx2">the x coordinate within the second cell.</param> /// <param name="dy2">the y coordinate within the second cell.</param> /// <param name="col1">the column (0 based) of the first cell.</param> /// <param name="row1">the row (0 based) of the first cell.</param> /// <param name="col2">the column (0 based) of the second cell.</param> /// <param name="row2">the row (0 based) of the second cell.</param> public HSSFClientAnchor(int dx1, int dy1, int dx2, int dy2, int col1, int row1, int col2, int row2) : base(dx1, dy1, dx2, dy2) { CheckRange(dx1, 0, 1023, "dx1"); CheckRange(dx2, 0, 1023, "dx2"); CheckRange(dy1, 0, 255, "dy1"); CheckRange(dy2, 0, 255, "dy2"); CheckRange(col1, 0, 255, "col1"); CheckRange(col2, 0, 255, "col2"); CheckRange(row1, 0, 255 * 256, "row1"); CheckRange(row2, 0, 255 * 256, "row2"); this.col1 = col1; this.row1 = row1; this.col2 = col2; this.row2 = row2; } /// <summary> /// Calculates the height of a client anchor in points. /// </summary> /// <param name="sheet">the sheet the anchor will be attached to</param> /// <returns>the shape height.</returns> public float GetAnchorHeightInPoints(NPOI.SS.UserModel.ISheet sheet) { int y1 = Dy1; int y2 = Dy2; int row1 = Math.Min(Row1, Row2); int row2 = Math.Max(Row1, Row2); float points = 0; if (row1 == row2) { points = ((y2 - y1) / 256.0f) * GetRowHeightInPoints(sheet, row2); } else { points += ((256.0f - y1) / 256.0f) * GetRowHeightInPoints(sheet, row1); for (int i = row1 + 1; i < row2; i++) { points += GetRowHeightInPoints(sheet, i); } points += (y2 / 256.0f) * GetRowHeightInPoints(sheet, row2); } return points; } /// <summary> /// Gets the row height in points. /// </summary> /// <param name="sheet">The sheet.</param> /// <param name="rowNum">The row num.</param> /// <returns></returns> private float GetRowHeightInPoints(NPOI.SS.UserModel.ISheet sheet, int rowNum) { NPOI.SS.UserModel.IRow row = sheet.GetRow(rowNum); if (row == null) return sheet.DefaultRowHeightInPoints; else return row.HeightInPoints; } /// <summary> /// Gets or sets the col1. /// </summary> /// <value>The col1.</value> public int Col1 { get { return col1; } set { CheckRange(value, 0, 255, "col1"); this.col1 = value; } } /// <summary> /// Gets or sets the col2. /// </summary> /// <value>The col2.</value> public int Col2 { get { return col2; } set { CheckRange(value, 0, 255, "col2"); this.col2 = value; } } /// <summary> /// Gets or sets the row1. /// </summary> /// <value>The row1.</value> public int Row1 { get { return row1; } set { CheckRange(value, 0, 256 * 256, "row1"); this.row1 = value; } } /// <summary> /// Gets or sets the row2. /// </summary> /// <value>The row2.</value> public int Row2 { get { return row2; } set { CheckRange(value, 0, 256 * 256, "row2"); this.row2 = value; } } /// <summary> /// Sets the top-left and bottom-right /// coordinates of the anchor /// </summary> /// <param name="col1">the column (0 based) of the first cell.</param> /// <param name="row1"> the row (0 based) of the first cell.</param> /// <param name="x1">the x coordinate within the first cell.</param> /// <param name="y1">the y coordinate within the first cell.</param> /// <param name="col2">the column (0 based) of the second cell.</param> /// <param name="row2">the row (0 based) of the second cell.</param> /// <param name="x2">the x coordinate within the second cell.</param> /// <param name="y2">the y coordinate within the second cell.</param> public void SetAnchor(short col1, int row1, int x1, int y1, short col2, int row2, int x2, int y2) { CheckRange(x1, 0, 1023, "dx1"); CheckRange(x2, 0, 1023, "dx2"); CheckRange(y1, 0, 255, "dy1"); CheckRange(y2, 0, 255, "dy2"); CheckRange(col1, 0, 255, "col1"); CheckRange(col2, 0, 255, "col2"); CheckRange(row1, 0, 255 * 256, "row1"); CheckRange(row2, 0, 255 * 256, "row2"); this.col1 = col1; this.row1 = row1; this.Dx1 = x1; this.Dy1 = y1; this.col2 = col2; this.row2 = row2; this.Dx2 = x2; this.Dy2 = y2; } /// <summary> /// Gets a value indicating whether this instance is horizontally flipped. /// </summary> /// <value> /// <c>true</c> if the anchor goes from right to left; otherwise, <c>false</c>. /// </value> public override bool IsHorizontallyFlipped { get { if (col1 == col2) return Dx1 > Dx2; else return col1 > col2; } } /// <summary> /// Gets a value indicating whether this instance is vertically flipped. /// </summary> /// <value> /// <c>true</c> if the anchor goes from bottom to top.; otherwise, <c>false</c>. /// </value> public override bool IsVerticallyFlipped { get { if (row1 == row2) return Dy1 > Dy2; else return row1 > row2; } } /// <summary> /// Gets the anchor type /// 0 = Move and size with Cells, 2 = Move but don't size with cells, 3 = Don't move or size with cells. /// </summary> /// <value>The type of the anchor.</value> public int AnchorType { get{return anchorType;} set { this.anchorType = value; } } /// <summary> /// Checks the range. /// </summary> /// <param name="value">The value.</param> /// <param name="minRange">The min range.</param> /// <param name="maxRange">The max range.</param> /// <param name="varName">Name of the variable.</param> private void CheckRange(int value, int minRange, int maxRange, String varName) { if (value < minRange || value > maxRange) throw new ArgumentException(varName + " must be between " + minRange + " and " + maxRange); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Linq; using NetGore; using NetGore.IO; namespace DemoGame { /// <summary> /// Defines a value used to determine the chance that an ItemTemplate will be created. /// </summary> [Serializable] [TypeConverter(typeof(ItemChanceTypeConverter))] public struct ItemChance : IComparable<ItemChance>, IConvertible, IFormattable, IComparable<int>, IEquatable<int> { #region Non-Templated Code static readonly SafeRandom _random = new SafeRandom(); /// <summary> /// Creates an ItemChance from a percent value. /// </summary> /// <param name="percent">The chance, in percentage, to assign to this ItemChance, where 0.0f is 0% and 1.0f /// is a 100% chance. Must be between 0.0f and 1.0f.</param> /// <returns></returns> public static ItemChance FromPercent(float percent) { int tmpValue = (int)Math.Round(percent.Clamp(0f, 1f) * MaxValue); // Ensure there were no rounding errors tmpValue = tmpValue.Clamp(MinValue, MaxValue); return new ItemChance(tmpValue); } /// <summary> /// Performs a test against the ItemChance. /// </summary> /// <returns>True if the test passed; otherwise false.</returns> public bool Test() { var randValue = _random.Next(MinValue + 1, MaxValue + 1); return randValue <= _value; } #endregion /// <summary> /// Gets the chance of this <see cref="ItemChance"/> as a percent in the range of 0.0f to 1.0f. /// </summary> public float Percentage { get { return (float)_value / MaxValue; } } /// <summary> /// Represents the largest possible value of ItemChance. This field is constant. /// </summary> public const int MaxValue = ushort.MaxValue; /// <summary> /// Represents the smallest possible value of ItemChance. This field is constant. /// </summary> public const int MinValue = ushort.MinValue; /// <summary> /// The underlying value. This contains the actual value of the struct instance. /// </summary> readonly ushort _value; /// <summary> /// Initializes a new instance of the <see cref="ItemChance"/> struct. /// </summary> /// <param name="value">Value to assign to the new ItemChance.</param> /// <exception cref="ArgumentOutOfRangeException"><c>value</c> is out of range.</exception> public ItemChance(int value) { if (value < MinValue || value > MaxValue) throw new ArgumentOutOfRangeException("value"); _value = (ushort)value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="other">Another object to compare to.</param> /// <returns> /// True if <paramref name="other"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public bool Equals(ItemChance other) { return other._value == _value; } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">Another object to compare to.</param> /// <returns> /// True if <paramref name="obj"/> and this instance are the same type and represent the same value; otherwise, false. /// </returns> public override bool Equals(object obj) { return obj is ItemChance && this == (ItemChance)obj; } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns> /// A 32-bit signed integer that is the hash code for this instance. /// </returns> public override int GetHashCode() { return _value.GetHashCode(); } /// <summary> /// Gets the raw internal value of this ItemChance. /// </summary> /// <returns>The raw internal value.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] public ushort GetRawValue() { return _value; } /// <summary> /// Reads an ItemChance from an IValueReader. /// </summary> /// <param name="reader">IValueReader to read from.</param> /// <param name="name">Unique name of the value to read.</param> /// <returns>The ItemChance read from the IValueReader.</returns> public static ItemChance Read(IValueReader reader, string name) { var value = reader.ReadUShort(name); return new ItemChance(value); } /// <summary> /// Reads an ItemChance from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="i">The index of the field to find.</param> /// <returns>The ItemChance read from the <see cref="IDataRecord"/>.</returns> public static ItemChance Read(IDataRecord reader, int i) { var value = reader.GetValue(i); if (value is ushort) return new ItemChance((ushort)value); var convertedValue = Convert.ToUInt16(value); return new ItemChance(convertedValue); } /// <summary> /// Reads an ItemChance from an <see cref="IDataRecord"/>. /// </summary> /// <param name="reader"><see cref="IDataRecord"/> to get the value from.</param> /// <param name="name">The name of the field to find.</param> /// <returns>The ItemChance read from the <see cref="IDataRecord"/>.</returns> public static ItemChance Read(IDataRecord reader, string name) { return Read(reader, reader.GetOrdinal(name)); } /// <summary> /// Reads an ItemChance from a BitStream. /// </summary> /// <param name="bitStream">BitStream to read from.</param> /// <returns>The ItemChance read from the BitStream.</returns> public static ItemChance Read(BitStream bitStream) { var value = bitStream.ReadUShort(); return new ItemChance(value); } /// <summary> /// Converts the numeric value of this instance to its equivalent string representation. /// </summary> /// <returns>The string representation of the value of this instance, consisting of a sequence /// of digits ranging from 0 to 9, without leading zeroes.</returns> public override string ToString() { return _value.ToString(); } /// <summary> /// Writes the ItemChance to an IValueWriter. /// </summary> /// <param name="writer">IValueWriter to write to.</param> /// <param name="name">Unique name of the ItemChance that will be used to distinguish it /// from other values when reading.</param> public void Write(IValueWriter writer, string name) { writer.Write(name, _value); } /// <summary> /// Writes the ItemChance to an IValueWriter. /// </summary> /// <param name="bitStream">BitStream to write to.</param> public void Write(BitStream bitStream) { bitStream.Write(_value); } #region IComparable<int> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(int other) { return _value.CompareTo(other); } #endregion #region IComparable<ItemChance> Members /// <summary> /// Compares the current object with another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has the following meanings: /// Value /// Meaning /// Less than zero /// This object is less than the <paramref name="other"/> parameter. /// Zero /// This object is equal to <paramref name="other"/>. /// Greater than zero /// This object is greater than <paramref name="other"/>. /// </returns> public int CompareTo(ItemChance other) { return _value.CompareTo(other._value); } #endregion #region IConvertible Members /// <summary> /// Returns the <see cref="T:System.TypeCode"/> for this instance. /// </summary> /// <returns> /// The enumerated constant that is the <see cref="T:System.TypeCode"/> of the class or value type that implements this interface. /// </returns> public TypeCode GetTypeCode() { return _value.GetTypeCode(); } /// <summary> /// Converts the value of this instance to an equivalent Boolean value using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation /// that supplies culture-specific formatting information.</param> /// <returns> /// A Boolean value equivalent to the value of this instance. /// </returns> bool IConvertible.ToBoolean(IFormatProvider provider) { return ((IConvertible)_value).ToBoolean(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit unsigned integer equivalent to the value of this instance. /// </returns> byte IConvertible.ToByte(IFormatProvider provider) { return ((IConvertible)_value).ToByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent Unicode character using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A Unicode character equivalent to the value of this instance. /// </returns> char IConvertible.ToChar(IFormatProvider provider) { return ((IConvertible)_value).ToChar(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.DateTime"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.DateTime"/> instance equivalent to the value of this instance. /// </returns> DateTime IConvertible.ToDateTime(IFormatProvider provider) { return ((IConvertible)_value).ToDateTime(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.Decimal"/> number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A <see cref="T:System.Decimal"/> number equivalent to the value of this instance. /// </returns> decimal IConvertible.ToDecimal(IFormatProvider provider) { return ((IConvertible)_value).ToDecimal(provider); } /// <summary> /// Converts the value of this instance to an equivalent double-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A double-precision floating-point number equivalent to the value of this instance. /// </returns> double IConvertible.ToDouble(IFormatProvider provider) { return ((IConvertible)_value).ToDouble(provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit signed integer equivalent to the value of this instance. /// </returns> short IConvertible.ToInt16(IFormatProvider provider) { return ((IConvertible)_value).ToInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit signed integer equivalent to the value of this instance. /// </returns> int IConvertible.ToInt32(IFormatProvider provider) { return ((IConvertible)_value).ToInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit signed integer equivalent to the value of this instance. /// </returns> long IConvertible.ToInt64(IFormatProvider provider) { return ((IConvertible)_value).ToInt64(provider); } /// <summary> /// Converts the value of this instance to an equivalent 8-bit signed integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 8-bit signed integer equivalent to the value of this instance. /// </returns> sbyte IConvertible.ToSByte(IFormatProvider provider) { return ((IConvertible)_value).ToSByte(provider); } /// <summary> /// Converts the value of this instance to an equivalent single-precision floating-point number using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information. </param> /// <returns> /// A single-precision floating-point number equivalent to the value of this instance. /// </returns> float IConvertible.ToSingle(IFormatProvider provider) { return ((IConvertible)_value).ToSingle(provider); } /// <summary> /// Converts the value of this instance to an equivalent <see cref="T:System.String"/> using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// A <see cref="T:System.String"/> instance equivalent to the value of this instance. /// </returns> public string ToString(IFormatProvider provider) { return ((IConvertible)_value).ToString(provider); } /// <summary> /// Converts the value of this instance to an <see cref="T:System.Object"/> of the specified <see cref="T:System.Type"/> that has an equivalent value, using the specified culture-specific formatting information. /// </summary> /// <param name="conversionType">The <see cref="T:System.Type"/> to which the value of this instance is converted.</param> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An <see cref="T:System.Object"/> instance of type <paramref name="conversionType"/> whose value is equivalent to the value of this instance. /// </returns> object IConvertible.ToType(Type conversionType, IFormatProvider provider) { return ((IConvertible)_value).ToType(conversionType, provider); } /// <summary> /// Converts the value of this instance to an equivalent 16-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 16-bit unsigned integer equivalent to the value of this instance. /// </returns> ushort IConvertible.ToUInt16(IFormatProvider provider) { return ((IConvertible)_value).ToUInt16(provider); } /// <summary> /// Converts the value of this instance to an equivalent 32-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 32-bit unsigned integer equivalent to the value of this instance. /// </returns> uint IConvertible.ToUInt32(IFormatProvider provider) { return ((IConvertible)_value).ToUInt32(provider); } /// <summary> /// Converts the value of this instance to an equivalent 64-bit unsigned integer using the specified culture-specific formatting information. /// </summary> /// <param name="provider">An <see cref="T:System.IFormatProvider"/> interface implementation that supplies /// culture-specific formatting information.</param> /// <returns> /// An 64-bit unsigned integer equivalent to the value of this instance. /// </returns> ulong IConvertible.ToUInt64(IFormatProvider provider) { return ((IConvertible)_value).ToUInt64(provider); } #endregion #region IEquatable<int> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name="other"/> parameter; otherwise, false. /// </returns> public bool Equals(int other) { return _value.Equals(other); } #endregion #region IFormattable Members /// <summary> /// Formats the value of the current instance using the specified format. /// </summary> /// <param name="format">The <see cref="T:System.String"/> specifying the format to use. /// -or- /// null to use the default format defined for the type of the <see cref="T:System.IFormattable"/> implementation. /// </param> /// <param name="formatProvider">The <see cref="T:System.IFormatProvider"/> to use to format the value. /// -or- /// null to obtain the numeric format information from the current locale setting of the operating system. /// </param> /// <returns> /// A <see cref="T:System.String"/> containing the value of the current instance in the specified format. /// </returns> public string ToString(string format, IFormatProvider formatProvider) { return _value.ToString(format, formatProvider); } #endregion /// <summary> /// Implements operator ++. /// </summary> /// <param name="l">The ItemChance to increment.</param> /// <returns>The incremented ItemChance.</returns> public static ItemChance operator ++(ItemChance l) { return new ItemChance(l._value + 1); } /// <summary> /// Implements operator --. /// </summary> /// <param name="l">The ItemChance to decrement.</param> /// <returns>The decremented ItemChance.</returns> public static ItemChance operator --(ItemChance l) { return new ItemChance(l._value - 1); } /// <summary> /// Implements operator +. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side plus the right side.</returns> public static ItemChance operator +(ItemChance left, ItemChance right) { return new ItemChance(left._value + right._value); } /// <summary> /// Implements operator -. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>Result of the left side minus the right side.</returns> public static ItemChance operator -(ItemChance left, ItemChance right) { return new ItemChance(left._value - right._value); } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(ItemChance left, int right) { return left._value == right; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(ItemChance left, int right) { return left._value != right; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(int left, ItemChance right) { return left == right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(int left, ItemChance right) { return left != right._value; } /// <summary> /// Casts a ItemChance to an Int32. /// </summary> /// <param name="ItemChance">ItemChance to cast.</param> /// <returns>The Int32.</returns> public static explicit operator int(ItemChance ItemChance) { return ItemChance._value; } /// <summary> /// Casts an Int32 to a ItemChance. /// </summary> /// <param name="value">Int32 to cast.</param> /// <returns>The ItemChance.</returns> public static explicit operator ItemChance(int value) { return new ItemChance(value); } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(int left, ItemChance right) { return left > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(int left, ItemChance right) { return left < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(ItemChance left, ItemChance right) { return left._value > right._value; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(ItemChance left, ItemChance right) { return left._value < right._value; } /// <summary> /// Implements the operator &gt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than the right.</returns> public static bool operator >(ItemChance left, int right) { return left._value > right; } /// <summary> /// Implements the operator &lt;. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than the left.</returns> public static bool operator <(ItemChance left, int right) { return left._value < right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(int left, ItemChance right) { return left >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(int left, ItemChance right) { return left <= right._value; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(ItemChance left, int right) { return left._value >= right; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(ItemChance left, int right) { return left._value <= right; } /// <summary> /// Implements the operator &gt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the left argument is greater than or equal to the right.</returns> public static bool operator >=(ItemChance left, ItemChance right) { return left._value >= right._value; } /// <summary> /// Implements the operator &lt;=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the right argument is greater than or equal to the left.</returns> public static bool operator <=(ItemChance left, ItemChance right) { return left._value <= right._value; } /// <summary> /// Implements operator !=. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are not equal.</returns> public static bool operator !=(ItemChance left, ItemChance right) { return left._value != right._value; } /// <summary> /// Implements operator ==. /// </summary> /// <param name="left">Left side argument.</param> /// <param name="right">Right side argument.</param> /// <returns>If the two arguments are equal.</returns> public static bool operator ==(ItemChance left, ItemChance right) { return left._value == right._value; } } /// <summary> /// Adds extensions to some data I/O objects for performing Read and Write operations for the ItemChance. /// All of the operations are implemented in the ItemChance struct. These extensions are provided /// purely for the convenience of accessing all the I/O operations from the same place. /// </summary> public static class ItemChanceReadWriteExtensions { /// <summary> /// Gets the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ItemChance. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <returns>The value at the given <paramref name="key"/> parsed as a ItemChance.</returns> public static ItemChance AsItemChance<T>(this IDictionary<T, string> dict, T key) { return Parser.Invariant.ParseItemChance(dict[key]); } /// <summary> /// Tries to get the value in the <paramref name="dict"/> entry at the given <paramref name="key"/> as type ItemChance. /// </summary> /// <typeparam name="T">The key Type.</typeparam> /// <param name="dict">The IDictionary.</param> /// <param name="key">The key for the value to get.</param> /// <param name="defaultValue">The value to use if the value at the <paramref name="key"/> could not be parsed.</param> /// <returns>The value at the given <paramref name="key"/> parsed as an int, or the /// <paramref name="defaultValue"/> if the <paramref name="key"/> did not exist in the <paramref name="dict"/> /// or the value at the given <paramref name="key"/> could not be parsed.</returns> public static ItemChance AsItemChance<T>(this IDictionary<T, string> dict, T key, ItemChance defaultValue) { string value; if (!dict.TryGetValue(key, out value)) return defaultValue; ItemChance parsed; if (!Parser.Invariant.TryParse(value, out parsed)) return defaultValue; return parsed; } /// <summary> /// Reads the ItemChance from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the ItemChance from.</param> /// <param name="i">The field index to read.</param> /// <returns>The ItemChance read from the <see cref="IDataRecord"/>.</returns> public static ItemChance GetItemChance(this IDataRecord r, int i) { return ItemChance.Read(r, i); } /// <summary> /// Reads the ItemChance from an <see cref="IDataRecord"/>. /// </summary> /// <param name="r"><see cref="IDataRecord"/> to read the ItemChance from.</param> /// <param name="name">The name of the field to read the value from.</param> /// <returns>The ItemChance read from the <see cref="IDataRecord"/>.</returns> public static ItemChance GetItemChance(this IDataRecord r, string name) { return ItemChance.Read(r, name); } /// <summary> /// Parses the ItemChance from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <returns>The ItemChance parsed from the string.</returns> public static ItemChance ParseItemChance(this Parser parser, string value) { return new ItemChance(parser.ParseUShort(value)); } /// <summary> /// Reads the ItemChance from a BitStream. /// </summary> /// <param name="bitStream">BitStream to read the ItemChance from.</param> /// <returns>The ItemChance read from the BitStream.</returns> public static ItemChance ReadItemChance(this BitStream bitStream) { return ItemChance.Read(bitStream); } /// <summary> /// Reads the ItemChance from an IValueReader. /// </summary> /// <param name="valueReader">IValueReader to read the ItemChance from.</param> /// <param name="name">The unique name of the value to read.</param> /// <returns>The ItemChance read from the IValueReader.</returns> public static ItemChance ReadItemChance(this IValueReader valueReader, string name) { return ItemChance.Read(valueReader, name); } /// <summary> /// Tries to parse the ItemChance from a string. /// </summary> /// <param name="parser">The Parser to use.</param> /// <param name="value">The string to parse.</param> /// <param name="outValue">If this method returns true, contains the parsed ItemChance.</param> /// <returns>True if the parsing was successfully; otherwise false.</returns> public static bool TryParse(this Parser parser, string value, out ItemChance outValue) { ushort tmp; var ret = parser.TryParse(value, out tmp); outValue = new ItemChance(tmp); return ret; } /// <summary> /// Writes a ItemChance to a BitStream. /// </summary> /// <param name="bitStream">BitStream to write to.</param> /// <param name="value">ItemChance to write.</param> public static void Write(this BitStream bitStream, ItemChance value) { value.Write(bitStream); } /// <summary> /// Writes a ItemChance to a IValueWriter. /// </summary> /// <param name="valueWriter">IValueWriter to write to.</param> /// <param name="name">Unique name of the ItemChance that will be used to distinguish it /// from other values when reading.</param> /// <param name="value">ItemChance to write.</param> public static void Write(this IValueWriter valueWriter, string name, ItemChance value) { value.Write(valueWriter, name); } } }
// 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.ComponentModel; using System.Collections.Generic; using System.Threading; namespace System.Data { internal struct IndexField { public readonly DataColumn Column; public readonly bool IsDescending; // false = Asc; true = Desc what is default value for this? internal IndexField(DataColumn column, bool isDescending) { Debug.Assert(column != null, "null column"); Column = column; IsDescending = isDescending; } public static bool operator ==(IndexField if1, IndexField if2) => if1.Column == if2.Column && if1.IsDescending == if2.IsDescending; public static bool operator !=(IndexField if1, IndexField if2) => !(if1 == if2); // must override Equals if == operator is defined public override bool Equals(object obj) => obj is IndexField ? this == (IndexField)obj : false; // must override GetHashCode if Equals is redefined public override int GetHashCode() => Column.GetHashCode() ^ IsDescending.GetHashCode(); } internal sealed class Index { private sealed class IndexTree : RBTree<int> { private readonly Index _index; internal IndexTree(Index index) : base(TreeAccessMethod.KEY_SEARCH_AND_INDEX) { _index = index; } protected override int CompareNode(int record1, int record2) => _index.CompareRecords(record1, record2); protected override int CompareSateliteTreeNode(int record1, int record2) => _index.CompareDuplicateRecords(record1, record2); } // these constants are used to update a DataRow when the record and Row are known, but don't match private const int DoNotReplaceCompareRecord = 0; private const int ReplaceNewRecordForCompare = 1; private const int ReplaceOldRecordForCompare = 2; private readonly DataTable _table; internal readonly IndexField[] _indexFields; /// <summary>Allow a user implemented comparision of two DataRow</summary> /// <remarks>User must use correct DataRowVersion in comparison or index corruption will happen</remarks> private readonly System.Comparison<DataRow> _comparison; private readonly DataViewRowState _recordStates; private WeakReference _rowFilter; private IndexTree _records; private int _recordCount; private int _refCount; private Listeners<DataViewListener> _listeners; private bool _suspendEvents; private readonly bool _isSharable; private readonly bool _hasRemoteAggregate; internal const int MaskBits = unchecked(0x7FFFFFFF); private static int s_objectTypeCount; // Bid counter private readonly int _objectID = Interlocked.Increment(ref s_objectTypeCount); public Index(DataTable table, IndexField[] indexFields, DataViewRowState recordStates, IFilter rowFilter) : this(table, indexFields, null, recordStates, rowFilter) { } public Index(DataTable table, System.Comparison<DataRow> comparison, DataViewRowState recordStates, IFilter rowFilter) : this(table, GetAllFields(table.Columns), comparison, recordStates, rowFilter) { } // for the delegate methods, we don't know what the dependent columns are - so all columns are dependent private static IndexField[] GetAllFields(DataColumnCollection columns) { IndexField[] fields = new IndexField[columns.Count]; for (int i = 0; i < fields.Length; ++i) { fields[i] = new IndexField(columns[i], false); } return fields; } private Index(DataTable table, IndexField[] indexFields, System.Comparison<DataRow> comparison, DataViewRowState recordStates, IFilter rowFilter) { DataCommonEventSource.Log.Trace("<ds.Index.Index|API> {0}, table={1}, recordStates={2}", ObjectID, (table != null) ? table.ObjectID : 0, recordStates); Debug.Assert(indexFields != null); Debug.Assert(null != table, "null table"); if ((recordStates & (~(DataViewRowState.CurrentRows | DataViewRowState.OriginalRows))) != 0) { throw ExceptionBuilder.RecordStateRange(); } _table = table; _listeners = new Listeners<DataViewListener>(ObjectID, listener => null != listener); _indexFields = indexFields; _recordStates = recordStates; _comparison = comparison; DataColumnCollection columns = table.Columns; _isSharable = (rowFilter == null) && (comparison == null); // a filter or comparison make an index unsharable if (null != rowFilter) { _rowFilter = new WeakReference(rowFilter); DataExpression expr = (rowFilter as DataExpression); if (null != expr) { _hasRemoteAggregate = expr.HasRemoteAggregate(); } } InitRecords(rowFilter); // do not AddRef in ctor, every caller should be responsible to AddRef it // if caller does not AddRef, it is expected to be a one-time read operation because the index won't be maintained on writes } public bool Equal(IndexField[] indexDesc, DataViewRowState recordStates, IFilter rowFilter) { if (!_isSharable || _indexFields.Length != indexDesc.Length || _recordStates != recordStates || null != rowFilter) { return false; } for (int loop = 0; loop < _indexFields.Length; loop++) { if (_indexFields[loop].Column != indexDesc[loop].Column || _indexFields[loop].IsDescending != indexDesc[loop].IsDescending) { return false; } } return true; } internal bool HasRemoteAggregate => _hasRemoteAggregate; internal int ObjectID => _objectID; public DataViewRowState RecordStates => _recordStates; public IFilter RowFilter => (IFilter)((null != _rowFilter) ? _rowFilter.Target : null); public int GetRecord(int recordIndex) { Debug.Assert(recordIndex >= 0 && recordIndex < _recordCount, "recordIndex out of range"); return _records[recordIndex]; } public bool HasDuplicates => _records.HasDuplicates; public int RecordCount => _recordCount; public bool IsSharable => _isSharable; private bool AcceptRecord(int record) => AcceptRecord(record, RowFilter); private bool AcceptRecord(int record, IFilter filter) { DataCommonEventSource.Log.Trace("<ds.Index.AcceptRecord|API> {0}, record={1}", ObjectID, record); if (filter == null) { return true; } DataRow row = _table._recordManager[record]; if (row == null) { return true; } DataRowVersion version = DataRowVersion.Default; if (row._oldRecord == record) { version = DataRowVersion.Original; } else if (row._newRecord == record) { version = DataRowVersion.Current; } else if (row._tempRecord == record) { version = DataRowVersion.Proposed; } return filter.Invoke(row, version); } /// <remarks>Only call from inside a lock(this)</remarks> internal void ListChangedAdd(DataViewListener listener) => _listeners.Add(listener); /// <remarks>Only call from inside a lock(this)</remarks> internal void ListChangedRemove(DataViewListener listener) => _listeners.Remove(listener); public int RefCount => _refCount; public void AddRef() { DataCommonEventSource.Log.Trace("<ds.Index.AddRef|API> {0}", ObjectID); _table._indexesLock.EnterWriteLock(); try { Debug.Assert(0 <= _refCount, "AddRef on disposed index"); Debug.Assert(null != _records, "null records"); if (_refCount == 0) { _table.ShadowIndexCopy(); _table._indexes.Add(this); } _refCount++; } finally { _table._indexesLock.ExitWriteLock(); } } public int RemoveRef() { DataCommonEventSource.Log.Trace("<ds.Index.RemoveRef|API> {0}", ObjectID); int count; _table._indexesLock.EnterWriteLock(); try { count = --_refCount; if (_refCount <= 0) { _table.ShadowIndexCopy(); _table._indexes.Remove(this); } } finally { _table._indexesLock.ExitWriteLock(); } return count; } private void ApplyChangeAction(int record, int action, int changeRecord) { if (action != 0) { if (action > 0) { if (AcceptRecord(record)) { InsertRecord(record, true); } } else if ((null != _comparison) && (-1 != record)) { // when removing a record, the DataRow has already been updated to the newer record // depending on changeRecord, either the new or old record needs be backdated to record // for Comparison<DataRow> to operate correctly DeleteRecord(GetIndex(record, changeRecord)); } else { // unnecessary codepath other than keeping original code path for redbits DeleteRecord(GetIndex(record)); } } } public bool CheckUnique() { #if DEBUG Debug.Assert(_records.CheckUnique(_records.root) != HasDuplicates, "CheckUnique difference"); #endif return !HasDuplicates; } // only used for main tree compare, not satalite tree private int CompareRecords(int record1, int record2) { if (null != _comparison) { return CompareDataRows(record1, record2); } if (0 < _indexFields.Length) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.Compare(record1, record2); if (c != 0) { return (_indexFields[i].IsDescending ? -c : c); } } return 0; } else { Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. return _table.Rows.IndexOf(_table._recordManager[record1]).CompareTo(_table.Rows.IndexOf(_table._recordManager[record2])); } } private int CompareDataRows(int record1, int record2) { _table._recordManager.VerifyRecord(record1, _table._recordManager[record1]); _table._recordManager.VerifyRecord(record2, _table._recordManager[record2]); return _comparison(_table._recordManager[record1], _table._recordManager[record2]); } // PS: same as previous CompareRecords, except it compares row state if needed // only used for satalite tree compare private int CompareDuplicateRecords(int record1, int record2) { #if DEBUG if (null != _comparison) { Debug.Assert(0 == CompareDataRows(record1, record2), "duplicate record not a duplicate by user function"); } else if (record1 != record2) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.Compare(record1, record2); Debug.Assert(0 == c, "duplicate record not a duplicate"); } } #endif Debug.Assert(null != _table._recordManager[record1], "record1 no datarow"); Debug.Assert(null != _table._recordManager[record2], "record2 no datarow"); if (null == _table._recordManager[record1]) { return ((null == _table._recordManager[record2]) ? 0 : -1); } else if (null == _table._recordManager[record2]) { return 1; } // Need to use compare because subtraction will wrap // to positive for very large neg numbers, etc. int diff = _table._recordManager[record1].rowID.CompareTo(_table._recordManager[record2].rowID); // if they're two records in the same row, we need to be able to distinguish them. if ((diff == 0) && (record1 != record2)) { diff = ((int)_table._recordManager[record1].GetRecordState(record1)).CompareTo((int)_table._recordManager[record2].GetRecordState(record2)); } return diff; } private int CompareRecordToKey(int record1, object[] vals) { for (int i = 0; i < _indexFields.Length; i++) { int c = _indexFields[i].Column.CompareValueTo(record1, vals[i]); if (c != 0) { return (_indexFields[i].IsDescending ? -c : c); } } return 0; } // DeleteRecordFromIndex deletes the given record from index and does not fire any Event. IT SHOULD NOT FIRE EVENT public void DeleteRecordFromIndex(int recordIndex) { // this is for expression use, to maintain expression columns's sort , filter etc. do not fire event DeleteRecord(recordIndex, false); } // old and existing DeleteRecord behavior, we can not use this for silently deleting private void DeleteRecord(int recordIndex) { DeleteRecord(recordIndex, true); } private void DeleteRecord(int recordIndex, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.Index.DeleteRecord|INFO> {0}, recordIndex={1}, fireEvent={2}", ObjectID, recordIndex, fireEvent); if (recordIndex >= 0) { _recordCount--; int record = _records.DeleteByIndex(recordIndex); MaintainDataView(ListChangedType.ItemDeleted, record, !fireEvent); if (fireEvent) { OnListChanged(ListChangedType.ItemDeleted, recordIndex); } } } // this improves performance by allowing DataView to iterating instead of computing for records over index // this will also allow Linq over DataSet to enumerate over the index // avoid boxing by returning RBTreeEnumerator (a struct) instead of IEnumerator<int> public RBTree<int>.RBTreeEnumerator GetEnumerator(int startIndex) => new IndexTree.RBTreeEnumerator(_records, startIndex); // What it actually does is find the index in the records[] that // this record inhabits, and if it doesn't, suggests what index it would // inhabit while setting the high bit. public int GetIndex(int record) => _records.GetIndexByKey(record); /// <summary> /// When searching by value for a specific record, the DataRow may require backdating to reflect the appropriate state /// otherwise on Delete of a DataRow in the Added state, would result in the <see cref="System.Comparison&lt;DataRow&gt;"/> where the row /// reflection record would be in the Detatched instead of Added state. /// </summary> private int GetIndex(int record, int changeRecord) { Debug.Assert(null != _comparison, "missing comparison"); int index; DataRow row = _table._recordManager[record]; int a = row._newRecord; int b = row._oldRecord; try { switch (changeRecord) { case ReplaceNewRecordForCompare: row._newRecord = record; break; case ReplaceOldRecordForCompare: row._oldRecord = record; break; } _table._recordManager.VerifyRecord(record, row); index = _records.GetIndexByKey(record); } finally { switch (changeRecord) { case ReplaceNewRecordForCompare: Debug.Assert(record == row._newRecord, "newRecord has change during GetIndex"); row._newRecord = a; break; case ReplaceOldRecordForCompare: Debug.Assert(record == row._oldRecord, "oldRecord has change during GetIndex"); row._oldRecord = b; break; } #if DEBUG if (-1 != a) { _table._recordManager.VerifyRecord(a, row); } #endif } return index; } public object[] GetUniqueKeyValues() { if (_indexFields == null || _indexFields.Length == 0) { return Array.Empty<object>(); } List<object[]> list = new List<object[]>(); GetUniqueKeyValues(list, _records.root); return list.ToArray(); } /// <summary> /// Find index of maintree node that matches key in record /// </summary> public int FindRecord(int record) { int nodeId = _records.Search(record); if (nodeId != IndexTree.NIL) return _records.GetIndexByNode(nodeId); //always returns the First record index else return -1; } public int FindRecordByKey(object key) { int nodeId = FindNodeByKey(key); if (IndexTree.NIL != nodeId) { return _records.GetIndexByNode(nodeId); } return -1; // return -1 to user indicating record not found } public int FindRecordByKey(object[] key) { int nodeId = FindNodeByKeys(key); if (IndexTree.NIL != nodeId) { return _records.GetIndexByNode(nodeId); } return -1; // return -1 to user indicating record not found } private int FindNodeByKey(object originalKey) { int x, c; if (_indexFields.Length != 1) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, 1); } x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist DataColumn column = _indexFields[0].Column; object key = column.ConvertValue(originalKey); x = _records.root; if (_indexFields[0].IsDescending) { while (IndexTree.NIL != x) { c = column.CompareValueTo(_records.Key(x), key); if (c == 0) { break; } if (c < 0) { x = _records.Left(x); } // < for decsending else { x = _records.Right(x); } } } else { while (IndexTree.NIL != x) { c = column.CompareValueTo(_records.Key(x), key); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } // > for ascending else { x = _records.Right(x); } } } } return x; } private int FindNodeByKeys(object[] originalKey) { int x, c; c = ((null != originalKey) ? originalKey.Length : 0); if ((0 == c) || (_indexFields.Length != c)) { throw ExceptionBuilder.IndexKeyLength(_indexFields.Length, c); } x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist // copy array to avoid changing original object[] key = new object[originalKey.Length]; for (int i = 0; i < originalKey.Length; ++i) { key[i] = _indexFields[i].Column.ConvertValue(originalKey[i]); } x = _records.root; while (IndexTree.NIL != x) { c = CompareRecordToKey(_records.Key(x), key); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } else { x = _records.Right(x); } } } return x; } private int FindNodeByKeyRecord(int record) { int x, c; x = _records.root; if (IndexTree.NIL != x) { // otherwise storage may not exist x = _records.root; while (IndexTree.NIL != x) { c = CompareRecords(_records.Key(x), record); if (c == 0) { break; } if (c > 0) { x = _records.Left(x); } else { x = _records.Right(x); } } } return x; } internal delegate int ComparisonBySelector<TKey, TRow>(TKey key, TRow row) where TRow : DataRow; /// <summary>This method exists for LinqDataView to keep a level of abstraction away from the RBTree</summary> internal Range FindRecords<TKey, TRow>(ComparisonBySelector<TKey, TRow> comparison, TKey key) where TRow : DataRow { int x = _records.root; while (IndexTree.NIL != x) { int c = comparison(key, (TRow)_table._recordManager[_records.Key(x)]); if (c == 0) { break; } if (c < 0) { x = _records.Left(x); } else { x = _records.Right(x); } } return GetRangeFromNode(x); } private Range GetRangeFromNode(int nodeId) { // fill range with the min and max indexes of matching record (i.e min and max of satelite tree) // min index is the index of the node in main tree, and max is the min + size of satelite tree-1 if (IndexTree.NIL == nodeId) { return new Range(); } int recordIndex = _records.GetIndexByNode(nodeId); if (_records.Next(nodeId) == IndexTree.NIL) return new Range(recordIndex, recordIndex); int span = _records.SubTreeSize(_records.Next(nodeId)); return new Range(recordIndex, recordIndex + span - 1); } public Range FindRecords(object key) { int nodeId = FindNodeByKey(key); // main tree node associated with key return GetRangeFromNode(nodeId); } public Range FindRecords(object[] key) { int nodeId = FindNodeByKeys(key); // main tree node associated with key return GetRangeFromNode(nodeId); } internal void FireResetEvent() { DataCommonEventSource.Log.Trace("<ds.Index.FireResetEvent|API> {0}", ObjectID); if (DoListChanged) { OnListChanged(DataView.s_resetEventArgs); } } private int GetChangeAction(DataViewRowState oldState, DataViewRowState newState) { int oldIncluded = ((int)_recordStates & (int)oldState) == 0 ? 0 : 1; int newIncluded = ((int)_recordStates & (int)newState) == 0 ? 0 : 1; return newIncluded - oldIncluded; } /// <summary>Determine if the record that needs backdating is the newRecord or oldRecord or neither</summary> private static int GetReplaceAction(DataViewRowState oldState) { return ((0 != (DataViewRowState.CurrentRows & oldState)) ? ReplaceNewRecordForCompare : // Added/ModifiedCurrent/Unchanged ((0 != (DataViewRowState.OriginalRows & oldState)) ? ReplaceOldRecordForCompare : // Deleted/ModififedOriginal DoNotReplaceCompareRecord)); // None } public DataRow GetRow(int i) => _table._recordManager[GetRecord(i)]; public DataRow[] GetRows(object[] values) => GetRows(FindRecords(values)); public DataRow[] GetRows(Range range) { DataRow[] newRows = _table.NewRowArray(range.Count); if (0 < newRows.Length) { RBTree<int>.RBTreeEnumerator iterator = GetEnumerator(range.Min); for (int i = 0; i < newRows.Length && iterator.MoveNext(); i++) { newRows[i] = _table._recordManager[iterator.Current]; } } return newRows; } private void InitRecords(IFilter filter) { DataViewRowState states = _recordStates; // this improves performance when the is no filter, like with the default view (creating after rows added) // we know the records are in the correct order, just append to end, duplicates not possible bool append = (0 == _indexFields.Length); _records = new IndexTree(this); _recordCount = 0; // this improves performance by iterating of the index instead of computing record by index foreach (DataRow b in _table.Rows) { int record = -1; if (b._oldRecord == b._newRecord) { if ((states & DataViewRowState.Unchanged) != 0) { record = b._oldRecord; } } else if (b._oldRecord == -1) { if ((states & DataViewRowState.Added) != 0) { record = b._newRecord; } } else if (b._newRecord == -1) { if ((states & DataViewRowState.Deleted) != 0) { record = b._oldRecord; } } else { if ((states & DataViewRowState.ModifiedCurrent) != 0) { record = b._newRecord; } else if ((states & DataViewRowState.ModifiedOriginal) != 0) { record = b._oldRecord; } } if (record != -1 && AcceptRecord(record, filter)) { _records.InsertAt(-1, record, append); _recordCount++; } } } // InsertRecordToIndex inserts the given record to index and does not fire any Event. IT SHOULD NOT FIRE EVENT // I added this since I can not use existing InsertRecord which is not silent operation // it returns the position that record is inserted public int InsertRecordToIndex(int record) { int pos = -1; if (AcceptRecord(record)) { pos = InsertRecord(record, false); } return pos; } // existing functionality, it calls the overlaod with fireEvent== true, so it still fires the event private int InsertRecord(int record, bool fireEvent) { DataCommonEventSource.Log.Trace("<ds.Index.InsertRecord|INFO> {0}, record={1}, fireEvent={2}", ObjectID, record, fireEvent); // this improves performance when the is no filter, like with the default view (creating before rows added) // we know can append when the new record is the last row in table, normal insertion pattern bool append = false; if ((0 == _indexFields.Length) && (null != _table)) { DataRow row = _table._recordManager[record]; append = (_table.Rows.IndexOf(row) + 1 == _table.Rows.Count); } int nodeId = _records.InsertAt(-1, record, append); _recordCount++; MaintainDataView(ListChangedType.ItemAdded, record, !fireEvent); if (fireEvent) { if (DoListChanged) { OnListChanged(ListChangedType.ItemAdded, _records.GetIndexByNode(nodeId)); } return 0; } else { return _records.GetIndexByNode(nodeId); } } // Search for specified key public bool IsKeyInIndex(object key) { int x_id = FindNodeByKey(key); return (IndexTree.NIL != x_id); } public bool IsKeyInIndex(object[] key) { int x_id = FindNodeByKeys(key); return (IndexTree.NIL != x_id); } public bool IsKeyRecordInIndex(int record) { int x_id = FindNodeByKeyRecord(record); return (IndexTree.NIL != x_id); } private bool DoListChanged => (!_suspendEvents && _listeners.HasListeners && !_table.AreIndexEventsSuspended); private void OnListChanged(ListChangedType changedType, int newIndex, int oldIndex) { if (DoListChanged) { OnListChanged(new ListChangedEventArgs(changedType, newIndex, oldIndex)); } } private void OnListChanged(ListChangedType changedType, int index) { if (DoListChanged) { OnListChanged(new ListChangedEventArgs(changedType, index)); } } private void OnListChanged(ListChangedEventArgs e) { DataCommonEventSource.Log.Trace("<ds.Index.OnListChanged|INFO> {0}", ObjectID); Debug.Assert(DoListChanged, "supposed to check DoListChanged before calling to delay create ListChangedEventArgs"); _listeners.Notify(e, false, false, delegate (DataViewListener listener, ListChangedEventArgs args, bool arg2, bool arg3) { listener.IndexListChanged(args); }); } private void MaintainDataView(ListChangedType changedType, int record, bool trackAddRemove) { Debug.Assert(-1 <= record, "bad record#"); _listeners.Notify(changedType, ((0 <= record) ? _table._recordManager[record] : null), trackAddRemove, delegate (DataViewListener listener, ListChangedType type, DataRow row, bool track) { listener.MaintainDataView(changedType, row, track); }); } public void Reset() { DataCommonEventSource.Log.Trace("<ds.Index.Reset|API> {0}", ObjectID); InitRecords(RowFilter); MaintainDataView(ListChangedType.Reset, -1, false); FireResetEvent(); } public void RecordChanged(int record) { DataCommonEventSource.Log.Trace("<ds.Index.RecordChanged|API> {0}, record={1}", ObjectID, record); if (DoListChanged) { int index = GetIndex(record); if (index >= 0) { OnListChanged(ListChangedType.ItemChanged, index); } } } // new RecordChanged which takes oldIndex and newIndex and fires _onListChanged public void RecordChanged(int oldIndex, int newIndex) { DataCommonEventSource.Log.Trace("<ds.Index.RecordChanged|API> {0}, oldIndex={1}, newIndex={2}", ObjectID, oldIndex, newIndex); if (oldIndex > -1 || newIndex > -1) { // no need to fire if it was not and will not be in index: this check means at least one version should be in index if (oldIndex == newIndex) { OnListChanged(ListChangedType.ItemChanged, newIndex, oldIndex); } else if (oldIndex == -1) { // it is added OnListChanged(ListChangedType.ItemAdded, newIndex, oldIndex); } else if (newIndex == -1) { OnListChanged(ListChangedType.ItemDeleted, oldIndex); } else { OnListChanged(ListChangedType.ItemMoved, newIndex, oldIndex); } } } public void RecordStateChanged(int record, DataViewRowState oldState, DataViewRowState newState) { DataCommonEventSource.Log.Trace("<ds.Index.RecordStateChanged|API> {0}, record={1}, oldState={2}, newState={3}", ObjectID, record, oldState, newState); int action = GetChangeAction(oldState, newState); ApplyChangeAction(record, action, GetReplaceAction(oldState)); } public void RecordStateChanged(int oldRecord, DataViewRowState oldOldState, DataViewRowState oldNewState, int newRecord, DataViewRowState newOldState, DataViewRowState newNewState) { DataCommonEventSource.Log.Trace("<ds.Index.RecordStateChanged|API> {0}, oldRecord={1}, oldOldState={2}, oldNewState={3}, newRecord={4}, newOldState={5}, newNewState={6}", ObjectID, oldRecord, oldOldState, oldNewState, newRecord, newOldState, newNewState); Debug.Assert((-1 == oldRecord) || (-1 == newRecord) || _table._recordManager[oldRecord] == _table._recordManager[newRecord], "not the same DataRow when updating oldRecord and newRecord"); int oldAction = GetChangeAction(oldOldState, oldNewState); int newAction = GetChangeAction(newOldState, newNewState); if (oldAction == -1 && newAction == 1 && AcceptRecord(newRecord)) { int oldRecordIndex; if ((null != _comparison) && oldAction < 0) { // when oldRecord is being removed, allow GetIndexByKey updating the DataRow for Comparison<DataRow> oldRecordIndex = GetIndex(oldRecord, GetReplaceAction(oldOldState)); } else { oldRecordIndex = GetIndex(oldRecord); } if ((null == _comparison) && oldRecordIndex != -1 && CompareRecords(oldRecord, newRecord) == 0) { _records.UpdateNodeKey(oldRecord, newRecord); //change in place, as Both records have same key value int commonIndexLocation = GetIndex(newRecord); OnListChanged(ListChangedType.ItemChanged, commonIndexLocation, commonIndexLocation); } else { _suspendEvents = true; if (oldRecordIndex != -1) { _records.DeleteByIndex(oldRecordIndex); // DeleteByIndex doesn't require searching by key _recordCount--; } _records.Insert(newRecord); _recordCount++; _suspendEvents = false; int newRecordIndex = GetIndex(newRecord); if (oldRecordIndex == newRecordIndex) { // if the position is the same OnListChanged(ListChangedType.ItemChanged, newRecordIndex, oldRecordIndex); // be carefull remove oldrecord index if needed } else { if (oldRecordIndex == -1) { MaintainDataView(ListChangedType.ItemAdded, newRecord, false); OnListChanged(ListChangedType.ItemAdded, GetIndex(newRecord)); // oldLocation would be -1 } else { OnListChanged(ListChangedType.ItemMoved, newRecordIndex, oldRecordIndex); } } } } else { ApplyChangeAction(oldRecord, oldAction, GetReplaceAction(oldOldState)); ApplyChangeAction(newRecord, newAction, GetReplaceAction(newOldState)); } } internal DataTable Table => _table; private void GetUniqueKeyValues(List<object[]> list, int curNodeId) { if (curNodeId != IndexTree.NIL) { GetUniqueKeyValues(list, _records.Left(curNodeId)); int record = _records.Key(curNodeId); object[] element = new object[_indexFields.Length]; // number of columns in PK for (int j = 0; j < element.Length; ++j) { element[j] = _indexFields[j].Column[record]; } list.Add(element); GetUniqueKeyValues(list, _records.Right(curNodeId)); } } internal static int IndexOfReference<T>(List<T> list, T item) where T : class { if (null != list) { for (int i = 0; i < list.Count; ++i) { if (ReferenceEquals(list[i], item)) { return i; } } } return -1; } internal static bool ContainsReference<T>(List<T> list, T item) where T : class { return (0 <= IndexOfReference(list, item)); } } internal sealed class Listeners<TElem> where TElem : class { private readonly List<TElem> _listeners; private readonly Func<TElem, bool> _filter; private readonly int _objectID; private int _listenerReaderCount; /// <summary>Wish this was defined in mscorlib.dll instead of System.Core.dll</summary> internal delegate void Action<T1, T2, T3, T4>(T1 arg1, T2 arg2, T3 arg3, T4 arg4); /// <summary>Wish this was defined in mscorlib.dll instead of System.Core.dll</summary> internal delegate TResult Func<T1, TResult>(T1 arg1); internal Listeners(int ObjectID, Func<TElem, bool> notifyFilter) { _listeners = new List<TElem>(); _filter = notifyFilter; _objectID = ObjectID; _listenerReaderCount = 0; } internal bool HasListeners => (0 < _listeners.Count); /// <remarks>Only call from inside a lock</remarks> internal void Add(TElem listener) { Debug.Assert(null != listener, "null listener"); Debug.Assert(!Index.ContainsReference(_listeners, listener), "already contains reference"); _listeners.Add(listener); } internal int IndexOfReference(TElem listener) { return Index.IndexOfReference(_listeners, listener); } /// <remarks>Only call from inside a lock</remarks> internal void Remove(TElem listener) { Debug.Assert(null != listener, "null listener"); int index = IndexOfReference(listener); Debug.Assert(0 <= index, "listeners don't contain listener"); _listeners[index] = null; if (0 == _listenerReaderCount) { _listeners.RemoveAt(index); _listeners.TrimExcess(); } } /// <summary> /// Write operation which means user must control multi-thread and we can assume single thread /// </summary> internal void Notify<T1, T2, T3>(T1 arg1, T2 arg2, T3 arg3, Action<TElem, T1, T2, T3> action) { Debug.Assert(null != action, "no action"); Debug.Assert(0 <= _listenerReaderCount, "negative _listEventCount"); int count = _listeners.Count; if (0 < count) { int nullIndex = -1; // protect against listeners shrinking via Remove _listenerReaderCount++; try { // protect against listeners growing via Add since new listeners will already have the Notify in progress for (int i = 0; i < count; ++i) { // protect against listener being set to null (instead of being removed) TElem listener = _listeners[i]; if (_filter(listener)) { // perform the action on each listener // some actions may throw an exception blocking remaning listeners from being notified (just like events) action(listener, arg1, arg2, arg3); } else { _listeners[i] = null; nullIndex = i; } } } finally { _listenerReaderCount--; } if (0 == _listenerReaderCount) { RemoveNullListeners(nullIndex); } } } private void RemoveNullListeners(int nullIndex) { Debug.Assert((-1 == nullIndex) || (null == _listeners[nullIndex]), "non-null listener"); Debug.Assert(0 == _listenerReaderCount, "0 < _listenerReaderCount"); for (int i = nullIndex; 0 <= i; --i) { if (null == _listeners[i]) { _listeners.RemoveAt(i); } } } } }
using System; using System.ComponentModel.Composition; using System.Linq; using EnvDTE; using Microsoft.VisualStudio.Shell.Interop; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(IVsPackageManagerFactory))] public class VsPackageManagerFactory : IVsPackageManagerFactory { private readonly IPackageRepositoryFactory _repositoryFactory; private readonly ISolutionManager _solutionManager; private readonly IFileSystemProvider _fileSystemProvider; private readonly IRepositorySettings _repositorySettings; private readonly IVsPackageSourceProvider _packageSourceProvider; private readonly VsPackageInstallerEvents _packageEvents; private readonly IPackageRepository _activePackageSourceRepository; private readonly IVsFrameworkMultiTargeting _frameworkMultiTargeting; private RepositoryInfo _repositoryInfo; private readonly IMachineWideSettings _machineWideSettings; [ImportingConstructor] public VsPackageManagerFactory(ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IMachineWideSettings machineWideSettings) : this(solutionManager, repositoryFactory, packageSourceProvider, fileSystemProvider, repositorySettings, packageEvents, activePackageSourceRepository, ServiceLocator.GetGlobalService<SVsFrameworkMultiTargeting, IVsFrameworkMultiTargeting>(), machineWideSettings) { } public VsPackageManagerFactory(ISolutionManager solutionManager, IPackageRepositoryFactory repositoryFactory, IVsPackageSourceProvider packageSourceProvider, IFileSystemProvider fileSystemProvider, IRepositorySettings repositorySettings, VsPackageInstallerEvents packageEvents, IPackageRepository activePackageSourceRepository, IVsFrameworkMultiTargeting frameworkMultiTargeting, IMachineWideSettings machineWideSettings) { if (solutionManager == null) { throw new ArgumentNullException("solutionManager"); } if (repositoryFactory == null) { throw new ArgumentNullException("repositoryFactory"); } if (packageSourceProvider == null) { throw new ArgumentNullException("packageSourceProvider"); } if (fileSystemProvider == null) { throw new ArgumentNullException("fileSystemProvider"); } if (repositorySettings == null) { throw new ArgumentNullException("repositorySettings"); } if (packageEvents == null) { throw new ArgumentNullException("packageEvents"); } if (activePackageSourceRepository == null) { throw new ArgumentNullException("activePackageSourceRepository"); } _fileSystemProvider = fileSystemProvider; _repositorySettings = repositorySettings; _solutionManager = solutionManager; _repositoryFactory = repositoryFactory; _packageSourceProvider = packageSourceProvider; _packageEvents = packageEvents; _activePackageSourceRepository = activePackageSourceRepository; _frameworkMultiTargeting = frameworkMultiTargeting; _machineWideSettings = machineWideSettings; _solutionManager.SolutionClosing += (sender, e) => { _repositoryInfo = null; }; } /// <summary> /// Creates an VsPackageManagerInstance that uses the Active Repository (the repository selected in the console drop down) and uses a fallback repository for dependencies. /// </summary> public IVsPackageManager CreatePackageManager() { return CreatePackageManager(_activePackageSourceRepository, useFallbackForDependencies: true); } // TODO: fallback repository is removed. Update the documentation. /// <summary> /// Creates a VsPackageManager that is used to manage install packages. /// The local repository is used as the primary source, and other active sources are /// used as fall back repository. When all needed packages are available in the local /// repository, which is the normal case, this package manager will not need to query /// any remote sources at all. Other active sources are /// used as fall back repository so that it still works even if user has used /// install-package -IgnoreDependencies. /// </summary> /// <returns>The VsPackageManager created.</returns> public IVsPackageManager CreatePackageManagerToManageInstalledPackages() { RepositoryInfo info = GetRepositoryInfo(); var aggregateRepository = _packageSourceProvider.CreateAggregateRepository( _repositoryFactory, ignoreFailingRepositories: true); aggregateRepository.ResolveDependenciesVertically = true; return CreatePackageManager(aggregateRepository, useFallbackForDependencies: false); } public IVsPackageManager CreatePackageManager(IPackageRepository repository, bool useFallbackForDependencies) { RepositoryInfo info = GetRepositoryInfo(); var packageManager = new VsPackageManager(_solutionManager, repository, _fileSystemProvider, info.FileSystem, info.Repository, // We ensure DeleteOnRestartManager is initialized with a PhysicalFileSystem so the // .deleteme marker files that get created don't get checked into version control new DeleteOnRestartManager(() => new PhysicalFileSystem(info.FileSystem.Root)), _packageEvents, _frameworkMultiTargeting); packageManager.DependencyVersion = GetDependencyVersion(); return packageManager; } public IVsPackageManager CreatePackageManagerWithAllPackageSources() { return CreatePackageManagerWithAllPackageSources(_activePackageSourceRepository); } internal IVsPackageManager CreatePackageManagerWithAllPackageSources(IPackageRepository repository) { if (IsAggregateRepository(repository)) { return CreatePackageManager(repository, false); } var priorityRepository = _packageSourceProvider.CreatePriorityPackageRepository(_repositoryFactory, repository); return CreatePackageManager(priorityRepository, useFallbackForDependencies: false); } // TODO: fallback repository is removed. Update the documentation. /// <summary> /// Creates a FallbackRepository with an aggregate repository that also contains the primaryRepository. /// </summary> internal IPackageRepository CreateFallbackRepository(IPackageRepository primaryRepository) { if (IsAggregateRepository(primaryRepository)) { // If we're using the aggregate repository, we don't need to create a fall back repo. return primaryRepository; } var aggregateRepository = _packageSourceProvider.CreateAggregateRepository(_repositoryFactory, ignoreFailingRepositories: true); aggregateRepository.ResolveDependenciesVertically = true; return aggregateRepository; } private static bool IsAggregateRepository(IPackageRepository repository) { if (repository is AggregateRepository) { // This test should be ok as long as any aggregate repository that we encounter here means the true Aggregate repository // of all repositories in the package source. // Since the repository created here comes from the UI, this holds true. return true; } var vsPackageSourceRepository = repository as VsPackageSourceRepository; if (vsPackageSourceRepository != null) { return IsAggregateRepository(vsPackageSourceRepository.GetActiveRepository()); } return false; } private RepositoryInfo GetRepositoryInfo() { // Update the path if it needs updating string path = _repositorySettings.RepositoryPath; string configFolderPath = _repositorySettings.ConfigFolderPath; if (_repositoryInfo == null || !_repositoryInfo.Path.Equals(path, StringComparison.OrdinalIgnoreCase) || !_repositoryInfo.ConfigFolderPath.Equals(configFolderPath, StringComparison.OrdinalIgnoreCase) || _solutionManager.IsSourceControlBound != _repositoryInfo.IsSourceControlBound) { IFileSystem fileSystem = _fileSystemProvider.GetFileSystem(path); IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath); // this file system is used to access the repositories.config file. We want to use Source Control-bound // file system to access it even if the 'disableSourceControlIntegration' setting is set. IFileSystem storeFileSystem = _fileSystemProvider.GetFileSystem(path, ignoreSourceControlSetting: true); ISharedPackageRepository repository = new SharedPackageRepository( new DefaultPackagePathResolver(fileSystem), fileSystem, storeFileSystem, configSettingsFileSystem); var settings = Settings.LoadDefaultSettings( configSettingsFileSystem, configFileName: null, machineWideSettings: _machineWideSettings); repository.PackageSaveMode = CalculatePackageSaveMode(settings); _repositoryInfo = new RepositoryInfo(path, configFolderPath, fileSystem, repository); } return _repositoryInfo; } /// <summary> /// Returns the user specified DependencyVersion in nuget.config. /// </summary> /// <returns>The user specified DependencyVersion value in nuget.config.</returns> private DependencyVersion GetDependencyVersion() { string configFolderPath = _repositorySettings.ConfigFolderPath; IFileSystem configSettingsFileSystem = GetConfigSettingsFileSystem(configFolderPath); var settings = Settings.LoadDefaultSettings( configSettingsFileSystem, configFileName: null, machineWideSettings: _machineWideSettings); string dependencyVersionValue = settings.GetConfigValue("DependencyVersion"); DependencyVersion dependencyVersion; if (Enum.TryParse(dependencyVersionValue, ignoreCase: true, result:out dependencyVersion)) { return dependencyVersion; } else { return DependencyVersion.Lowest; } } private PackageSaveModes CalculatePackageSaveMode(ISettings settings) { PackageSaveModes retValue = PackageSaveModes.None; if (settings != null) { string packageSaveModeValue = settings.GetConfigValue("PackageSaveMode"); // TODO: remove following block of code when shipping NuGet version post 2.8 if (string.IsNullOrEmpty(packageSaveModeValue)) { packageSaveModeValue = settings.GetConfigValue("SaveOnExpand"); } // end of block of code to remove when shipping NuGet version post 2.8 if (!string.IsNullOrEmpty(packageSaveModeValue)) { foreach (var v in packageSaveModeValue.Split(';')) { if (v.Equals(PackageSaveModes.Nupkg.ToString(), StringComparison.OrdinalIgnoreCase)) { retValue |= PackageSaveModes.Nupkg; } else if (v.Equals(PackageSaveModes.Nuspec.ToString(), StringComparison.OrdinalIgnoreCase)) { retValue |= PackageSaveModes.Nuspec; } } } } if (retValue == PackageSaveModes.None) { retValue = PackageSaveModes.Nupkg; } return retValue; } protected internal virtual IFileSystem GetConfigSettingsFileSystem(string configFolderPath) { return new SolutionFolderFileSystem(ServiceLocator.GetInstance<DTE>().Solution, VsConstants.NuGetSolutionSettingsFolder, configFolderPath); } private class RepositoryInfo { public RepositoryInfo(string path, string configFolderPath, IFileSystem fileSystem, ISharedPackageRepository repository) { Path = path; FileSystem = fileSystem; Repository = repository; ConfigFolderPath = configFolderPath; } public bool IsSourceControlBound { get { return FileSystem is ISourceControlFileSystem; } } public IFileSystem FileSystem { get; private set; } public string Path { get; private set; } public string ConfigFolderPath { get; private set; } public ISharedPackageRepository Repository { get; private set; } } } }
using Newtonsoft.Json; 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; namespace EmpMan.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; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; [System.Serializable] public class tk2dSpriteColliderIsland { public bool connected = true; public Vector2[] points; public bool IsValid() { if (connected) { return points.Length >= 3; } else { return points.Length >= 2; } } public void CopyFrom(tk2dSpriteColliderIsland src) { connected = src.connected; points = new Vector2[src.points.Length]; for (int i = 0; i < points.Length; ++i) points[i] = src.points[i]; } public bool CompareTo(tk2dSpriteColliderIsland src) { if (connected != src.connected) return false; if (points.Length != src.points.Length) return false; for (int i = 0; i < points.Length; ++i) if (points[i] != src.points[i]) return false; return true; } } [System.Serializable] public class tk2dSpriteCollectionDefinition { public enum Anchor { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight, Custom } public enum Pad { Default, BlackZeroAlpha, Extend, TileXY, } public enum ColliderType { UserDefined, // don't try to create or destroy anything ForceNone, // nothing will be created, if something exists, it will be destroyed BoxTrimmed, // box, trimmed to cover visible region BoxCustom, // box, with custom values provided by user Polygon, // polygon, can be concave } public enum PolygonColliderCap { None, FrontAndBack, Front, Back, } public enum ColliderColor { Default, // default unity color scheme Red, White, Black } public enum Source { Sprite, SpriteSheet, Font } public string name = ""; public bool disableTrimming = false; public bool additive = false; public Vector3 scale = new Vector3(1,1,1); public Texture2D texture = null; [System.NonSerialized] public Texture2D thumbnailTexture; public int materialId = 0; public Anchor anchor = Anchor.MiddleCenter; public float anchorX, anchorY; public Object overrideMesh; public bool doubleSidedSprite = false; public bool customSpriteGeometry = false; public tk2dSpriteColliderIsland[] geometryIslands = new tk2dSpriteColliderIsland[0]; public bool dice = false; public int diceUnitX = 64; public int diceUnitY = 0; public Pad pad = Pad.Default; public int extraPadding = 0; // default public Source source = Source.Sprite; public bool fromSpriteSheet = false; public bool hasSpriteSheetId = false; public int spriteSheetId = 0; public int spriteSheetX = 0, spriteSheetY = 0; public bool extractRegion = false; public int regionX, regionY, regionW, regionH; public int regionId; public ColliderType colliderType = ColliderType.UserDefined; public Vector2 boxColliderMin, boxColliderMax; public tk2dSpriteColliderIsland[] polyColliderIslands; public PolygonColliderCap polyColliderCap = PolygonColliderCap.None; public bool colliderConvex = false; public bool colliderSmoothSphereCollisions = false; public ColliderColor colliderColor = ColliderColor.Default; public void CopyFrom(tk2dSpriteCollectionDefinition src) { name = src.name; disableTrimming = src.disableTrimming; additive = src.additive; scale = src.scale; texture = src.texture; materialId = src.materialId; anchor = src.anchor; anchorX = src.anchorX; anchorY = src.anchorY; overrideMesh = src.overrideMesh; doubleSidedSprite = src.doubleSidedSprite; customSpriteGeometry = src.customSpriteGeometry; geometryIslands = src.geometryIslands; dice = src.dice; diceUnitX = src.diceUnitX; diceUnitY = src.diceUnitY; pad = src.pad; source = src.source; fromSpriteSheet = src.fromSpriteSheet; hasSpriteSheetId = src.hasSpriteSheetId; spriteSheetX = src.spriteSheetX; spriteSheetY = src.spriteSheetY; spriteSheetId = src.spriteSheetId; extractRegion = src.extractRegion; regionX = src.regionX; regionY = src.regionY; regionW = src.regionW; regionH = src.regionH; regionId = src.regionId; colliderType = src.colliderType; boxColliderMin = src.boxColliderMin; boxColliderMax = src.boxColliderMax; polyColliderCap = src.polyColliderCap; colliderColor = src.colliderColor; colliderConvex = src.colliderConvex; colliderSmoothSphereCollisions = src.colliderSmoothSphereCollisions; extraPadding = src.extraPadding; if (src.polyColliderIslands != null) { polyColliderIslands = new tk2dSpriteColliderIsland[src.polyColliderIslands.Length]; for (int i = 0; i < polyColliderIslands.Length; ++i) { polyColliderIslands[i] = new tk2dSpriteColliderIsland(); polyColliderIslands[i].CopyFrom(src.polyColliderIslands[i]); } } else { polyColliderIslands = new tk2dSpriteColliderIsland[0]; } if (src.geometryIslands != null) { geometryIslands = new tk2dSpriteColliderIsland[src.geometryIslands.Length]; for (int i = 0; i < geometryIslands.Length; ++i) { geometryIslands[i] = new tk2dSpriteColliderIsland(); geometryIslands[i].CopyFrom(src.geometryIslands[i]); } } else { geometryIslands = new tk2dSpriteColliderIsland[0]; } } public void Clear() { // Reinitialize var tmpVar = new tk2dSpriteCollectionDefinition(); CopyFrom(tmpVar); } public bool CompareTo(tk2dSpriteCollectionDefinition src) { if (name != src.name) return false; if (additive != src.additive) return false; if (scale != src.scale) return false; if (texture != src.texture) return false; if (materialId != src.materialId) return false; if (anchor != src.anchor) return false; if (anchorX != src.anchorX) return false; if (anchorY != src.anchorY) return false; if (overrideMesh != src.overrideMesh) return false; if (dice != src.dice) return false; if (diceUnitX != src.diceUnitX) return false; if (diceUnitY != src.diceUnitY) return false; if (pad != src.pad) return false; if (extraPadding != src.extraPadding) return false; if (doubleSidedSprite != src.doubleSidedSprite) return false; if (customSpriteGeometry != src.customSpriteGeometry) return false; if (geometryIslands != src.geometryIslands) return false; if (geometryIslands != null && src.geometryIslands != null) { if (geometryIslands.Length != src.geometryIslands.Length) return false; for (int i = 0; i < geometryIslands.Length; ++i) if (!geometryIslands[i].CompareTo(src.geometryIslands[i])) return false; } if (source != src.source) return false; if (fromSpriteSheet != src.fromSpriteSheet) return false; if (hasSpriteSheetId != src.hasSpriteSheetId) return false; if (spriteSheetId != src.spriteSheetId) return false; if (spriteSheetX != src.spriteSheetX) return false; if (spriteSheetY != src.spriteSheetY) return false; if (extractRegion != src.extractRegion) return false; if (regionX != src.regionX) return false; if (regionY != src.regionY) return false; if (regionW != src.regionW) return false; if (regionH != src.regionH) return false; if (regionId != src.regionId) return false; if (colliderType != src.colliderType) return false; if (boxColliderMin != src.boxColliderMin) return false; if (boxColliderMax != src.boxColliderMax) return false; if (polyColliderIslands != src.polyColliderIslands) return false; if (polyColliderIslands != null && src.polyColliderIslands != null) { if (polyColliderIslands.Length != src.polyColliderIslands.Length) return false; for (int i = 0; i < polyColliderIslands.Length; ++i) if (!polyColliderIslands[i].CompareTo(src.polyColliderIslands[i])) return false; } if (polyColliderCap != src.polyColliderCap) return false; if (colliderColor != src.colliderColor) return false; if (colliderSmoothSphereCollisions != src.colliderSmoothSphereCollisions) return false; if (colliderConvex != src.colliderConvex) return false; return true; } } [System.Serializable] public class tk2dSpriteCollectionDefault { public bool additive = false; public Vector3 scale = new Vector3(1,1,1); public tk2dSpriteCollectionDefinition.Anchor anchor = tk2dSpriteCollectionDefinition.Anchor.MiddleCenter; public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default; public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; } [System.Serializable] public class tk2dSpriteSheetSource { public enum Anchor { UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight, } public enum SplitMethod { UniformDivision, } public Texture2D texture; public int tilesX, tilesY; public int numTiles = 0; public Anchor anchor = Anchor.MiddleCenter; public tk2dSpriteCollectionDefinition.Pad pad = tk2dSpriteCollectionDefinition.Pad.Default; public Vector3 scale = new Vector3(1,1,1); public bool additive = false; // version 1 public bool active = false; public int tileWidth, tileHeight; public int tileMarginX, tileMarginY; public int tileSpacingX, tileSpacingY; public SplitMethod splitMethod = SplitMethod.UniformDivision; public int version = 0; public const int CURRENT_VERSION = 1; public tk2dSpriteCollectionDefinition.ColliderType colliderType = tk2dSpriteCollectionDefinition.ColliderType.UserDefined; public void CopyFrom(tk2dSpriteSheetSource src) { texture = src.texture; tilesX = src.tilesX; tilesY = src.tilesY; numTiles = src.numTiles; anchor = src.anchor; pad = src.pad; scale = src.scale; colliderType = src.colliderType; version = src.version; active = src.active; tileWidth = src.tileWidth; tileHeight = src.tileHeight; tileSpacingX = src.tileSpacingX; tileSpacingY = src.tileSpacingY; tileMarginX = src.tileMarginX; tileMarginY = src.tileMarginY; splitMethod = src.splitMethod; } public bool CompareTo(tk2dSpriteSheetSource src) { if (texture != src.texture) return false; if (tilesX != src.tilesX) return false; if (tilesY != src.tilesY) return false; if (numTiles != src.numTiles) return false; if (anchor != src.anchor) return false; if (pad != src.pad) return false; if (scale != src.scale) return false; if (colliderType != src.colliderType) return false; if (version != src.version) return false; if (active != src.active) return false; if (tileWidth != src.tileWidth) return false; if (tileHeight != src.tileHeight) return false; if (tileSpacingX != src.tileSpacingX) return false; if (tileSpacingY != src.tileSpacingY) return false; if (tileMarginX != src.tileMarginX) return false; if (tileMarginY != src.tileMarginY) return false; if (splitMethod != src.splitMethod) return false; return true; } public string Name { get { return texture != null?texture.name:"New Sprite Sheet"; } } } [System.Serializable] public class tk2dSpriteCollectionFont { public bool active = false; public Object bmFont; public Texture2D texture; public bool dupeCaps = false; // duplicate lowercase into uc, or vice-versa, depending on which exists public bool flipTextureY = false; public int charPadX = 0; public tk2dFontData data; public tk2dFont editorData; public int materialId; public bool useGradient = false; public Texture2D gradientTexture = null; public int gradientCount = 1; public void CopyFrom(tk2dSpriteCollectionFont src) { active = src.active; bmFont = src.bmFont; texture = src.texture; dupeCaps = src.dupeCaps; flipTextureY = src.flipTextureY; charPadX = src.charPadX; data = src.data; editorData = src.editorData; materialId = src.materialId; gradientCount = src.gradientCount; gradientTexture = src.gradientTexture; useGradient = src.useGradient; } public string Name { get { if (bmFont == null || texture == null) return "Empty"; else { if (data == null) return bmFont.name + " (Inactive)"; else return bmFont.name; } } } public bool InUse { get { return active && bmFont != null && texture != null && data != null && editorData != null; } } } [System.Serializable] public class tk2dSpriteCollectionPlatform { public string name = ""; public tk2dSpriteCollection spriteCollection = null; public bool Valid { get { return name.Length > 0 && spriteCollection != null; } } public void CopyFrom(tk2dSpriteCollectionPlatform source) { name = source.name; spriteCollection = source.spriteCollection; } } [AddComponentMenu("2D Toolkit/Backend/tk2dSpriteCollection")] public class tk2dSpriteCollection : MonoBehaviour { public const int CURRENT_VERSION = 3; public enum NormalGenerationMode { None, NormalsOnly, NormalsAndTangents, }; // Deprecated fields [SerializeField] private tk2dSpriteCollectionDefinition[] textures; [SerializeField] private Texture2D[] textureRefs; public Texture2D[] DoNotUse__TextureRefs { get { return textureRefs; } set { textureRefs = value; } } // Don't use this for anything. Except maybe in tk2dSpriteCollectionBuilderDeprecated... // new method public tk2dSpriteSheetSource[] spriteSheets; public tk2dSpriteCollectionFont[] fonts; public tk2dSpriteCollectionDefault defaults; // platforms public List<tk2dSpriteCollectionPlatform> platforms = new List<tk2dSpriteCollectionPlatform>(); public bool managedSpriteCollection = false; // true when generated and managed by system, eg. platform specific data public bool HasPlatformData { get { return platforms.Count > 1; } } public bool loadable = false; public int maxTextureSize = 1024; public bool forceTextureSize = false; public int forcedTextureWidth = 1024; public int forcedTextureHeight = 1024; public enum TextureCompression { Uncompressed, Reduced16Bit, Compressed, Dithered16Bit_Alpha, Dithered16Bit_NoAlpha, } public TextureCompression textureCompression = TextureCompression.Uncompressed; public int atlasWidth, atlasHeight; public bool forceSquareAtlas = false; public float atlasWastage; public bool allowMultipleAtlases = false; public tk2dSpriteCollectionDefinition[] textureParams; public tk2dSpriteCollectionData spriteCollection; public bool premultipliedAlpha = false; public Material[] altMaterials; public Material[] atlasMaterials; public Texture2D[] atlasTextures; public bool useTk2dCamera = false; public int targetHeight = 640; public float targetOrthoSize = 1.0f; public float globalScale = 1.0f; // Texture settings [SerializeField] private bool pixelPerfectPointSampled = false; // obsolete public FilterMode filterMode = FilterMode.Bilinear; public TextureWrapMode wrapMode = TextureWrapMode.Clamp; public bool userDefinedTextureSettings = false; public bool mipmapEnabled = false; public int anisoLevel = 1; public float physicsDepth = 0.1f; public bool disableTrimming = false; public NormalGenerationMode normalGenerationMode = NormalGenerationMode.None; public int padAmount = -1; // default public bool autoUpdate = true; public float editorDisplayScale = 1.0f; public int version = 0; public string assetName = ""; // Fix up upgraded data structures public void Upgrade() { if (version == CURRENT_VERSION) return; Debug.Log("SpriteCollection '" + this.name + "' - Upgraded from version " + version.ToString()); if (version == 0) { if (pixelPerfectPointSampled) filterMode = FilterMode.Point; else filterMode = FilterMode.Bilinear; // don't bother messing about with user settings // on old atlases userDefinedTextureSettings = true; } if (version < 3) { if (textureRefs != null && textureParams != null && textureRefs.Length == textureParams.Length) { for (int i = 0; i < textureRefs.Length; ++i) textureParams[i].texture = textureRefs[i]; textureRefs = null; } } version = CURRENT_VERSION; #if UNITY_EDITOR UnityEditor.EditorUtility.SetDirty(this); #endif } }
namespace ExceptionReporting.MVP.Views { public partial class ExceptionReportView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ExceptionReportView)); this.listviewAssemblies = new System.Windows.Forms.ListView(); this.tabControl = new System.Windows.Forms.TabControl(); this.tabGeneral = new System.Windows.Forms.TabPage(); this.picGeneral = new System.Windows.Forms.PictureBox(); this.txtExceptionMessage = new System.Windows.Forms.TextBox(); this.lblExplanation = new System.Windows.Forms.Label(); this.txtUserExplanation = new System.Windows.Forms.TextBox(); this.lblDate = new System.Windows.Forms.Label(); this.txtDate = new System.Windows.Forms.TextBox(); this.lblTime = new System.Windows.Forms.Label(); this.txtTime = new System.Windows.Forms.TextBox(); this.lblApplication = new System.Windows.Forms.Label(); this.txtApplicationName = new System.Windows.Forms.TextBox(); this.lblVersion = new System.Windows.Forms.Label(); this.txtVersion = new System.Windows.Forms.TextBox(); this.tabExceptions = new System.Windows.Forms.TabPage(); this.tabAssemblies = new System.Windows.Forms.TabPage(); this.tabSysInfo = new System.Windows.Forms.TabPage(); this.treeEnvironment = new System.Windows.Forms.TreeView(); this.btnSave = new System.Windows.Forms.Button(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.btnEmail = new System.Windows.Forms.Button(); this.lblProgressMessage = new System.Windows.Forms.Label(); this.btnCopy = new System.Windows.Forms.Button(); this.btnDetailToggle = new System.Windows.Forms.Button(); this.txtExceptionMessageLarge = new System.Windows.Forms.TextBox(); this.btnClose = new System.Windows.Forms.Button(); this.lessDetailPanel = new System.Windows.Forms.Panel(); this.lessDetail_optionsPanel = new System.Windows.Forms.Panel(); this.lblContactCompany = new System.Windows.Forms.Label(); this.btnSimpleEmail = new System.Windows.Forms.Button(); this.btnSimpleDetailToggle = new System.Windows.Forms.Button(); this.btnSimpleCopy = new System.Windows.Forms.Button(); this.txtExceptionMessageLarge2 = new System.Windows.Forms.TextBox(); this.lessDetail_alertIcon = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.tabControl.SuspendLayout(); this.tabGeneral.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picGeneral)).BeginInit(); this.tabAssemblies.SuspendLayout(); this.tabSysInfo.SuspendLayout(); this.lessDetailPanel.SuspendLayout(); this.lessDetail_optionsPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.lessDetail_alertIcon)).BeginInit(); this.SuspendLayout(); // // listviewAssemblies // resources.ApplyResources(this.listviewAssemblies, "listviewAssemblies"); this.listviewAssemblies.Activation = System.Windows.Forms.ItemActivation.OneClick; this.listviewAssemblies.FullRowSelect = true; this.listviewAssemblies.HotTracking = true; this.listviewAssemblies.HoverSelection = true; this.listviewAssemblies.Name = "listviewAssemblies"; this.listviewAssemblies.UseCompatibleStateImageBehavior = false; this.listviewAssemblies.View = System.Windows.Forms.View.Details; // // tabControl // resources.ApplyResources(this.tabControl, "tabControl"); this.tabControl.Controls.Add(this.tabGeneral); this.tabControl.Controls.Add(this.tabExceptions); this.tabControl.Controls.Add(this.tabAssemblies); this.tabControl.Controls.Add(this.tabSysInfo); this.tabControl.HotTrack = true; this.tabControl.Multiline = true; this.tabControl.Name = "tabControl"; this.tabControl.SelectedIndex = 0; // // tabGeneral // resources.ApplyResources(this.tabGeneral, "tabGeneral"); this.tabGeneral.Controls.Add(this.picGeneral); this.tabGeneral.Controls.Add(this.txtExceptionMessage); this.tabGeneral.Controls.Add(this.lblExplanation); this.tabGeneral.Controls.Add(this.txtUserExplanation); this.tabGeneral.Controls.Add(this.lblDate); this.tabGeneral.Controls.Add(this.txtDate); this.tabGeneral.Controls.Add(this.lblTime); this.tabGeneral.Controls.Add(this.txtTime); this.tabGeneral.Controls.Add(this.lblApplication); this.tabGeneral.Controls.Add(this.txtApplicationName); this.tabGeneral.Controls.Add(this.lblVersion); this.tabGeneral.Controls.Add(this.txtVersion); this.tabGeneral.Name = "tabGeneral"; this.tabGeneral.UseVisualStyleBackColor = true; // // picGeneral // resources.ApplyResources(this.picGeneral, "picGeneral"); this.picGeneral.Name = "picGeneral"; this.picGeneral.TabStop = false; // // txtExceptionMessage // resources.ApplyResources(this.txtExceptionMessage, "txtExceptionMessage"); this.txtExceptionMessage.BackColor = System.Drawing.Color.White; this.txtExceptionMessage.Name = "txtExceptionMessage"; this.txtExceptionMessage.ReadOnly = true; // // lblExplanation // resources.ApplyResources(this.lblExplanation, "lblExplanation"); this.lblExplanation.Name = "lblExplanation"; // // txtUserExplanation // resources.ApplyResources(this.txtUserExplanation, "txtUserExplanation"); this.txtUserExplanation.BackColor = System.Drawing.Color.Cornsilk; this.txtUserExplanation.Name = "txtUserExplanation"; // // lblDate // resources.ApplyResources(this.lblDate, "lblDate"); this.lblDate.Name = "lblDate"; // // txtDate // resources.ApplyResources(this.txtDate, "txtDate"); this.txtDate.BackColor = System.Drawing.Color.Snow; this.txtDate.Name = "txtDate"; this.txtDate.ReadOnly = true; // // lblTime // resources.ApplyResources(this.lblTime, "lblTime"); this.lblTime.Name = "lblTime"; // // txtTime // resources.ApplyResources(this.txtTime, "txtTime"); this.txtTime.BackColor = System.Drawing.Color.Snow; this.txtTime.Name = "txtTime"; this.txtTime.ReadOnly = true; // // lblApplication // resources.ApplyResources(this.lblApplication, "lblApplication"); this.lblApplication.Name = "lblApplication"; // // txtApplicationName // resources.ApplyResources(this.txtApplicationName, "txtApplicationName"); this.txtApplicationName.BackColor = System.Drawing.Color.Snow; this.txtApplicationName.Name = "txtApplicationName"; this.txtApplicationName.ReadOnly = true; // // lblVersion // resources.ApplyResources(this.lblVersion, "lblVersion"); this.lblVersion.Name = "lblVersion"; // // txtVersion // resources.ApplyResources(this.txtVersion, "txtVersion"); this.txtVersion.BackColor = System.Drawing.Color.Snow; this.txtVersion.Name = "txtVersion"; this.txtVersion.ReadOnly = true; // // tabExceptions // resources.ApplyResources(this.tabExceptions, "tabExceptions"); this.tabExceptions.Name = "tabExceptions"; this.tabExceptions.UseVisualStyleBackColor = true; // // tabAssemblies // resources.ApplyResources(this.tabAssemblies, "tabAssemblies"); this.tabAssemblies.Controls.Add(this.listviewAssemblies); this.tabAssemblies.Name = "tabAssemblies"; this.tabAssemblies.UseVisualStyleBackColor = true; // // tabSysInfo // resources.ApplyResources(this.tabSysInfo, "tabSysInfo"); this.tabSysInfo.Controls.Add(this.treeEnvironment); this.tabSysInfo.Name = "tabSysInfo"; this.tabSysInfo.UseVisualStyleBackColor = true; // // treeEnvironment // resources.ApplyResources(this.treeEnvironment, "treeEnvironment"); this.treeEnvironment.BackColor = System.Drawing.SystemColors.Window; this.treeEnvironment.HotTracking = true; this.treeEnvironment.Name = "treeEnvironment"; // // btnSave // resources.ApplyResources(this.btnSave, "btnSave"); this.btnSave.Name = "btnSave"; // // progressBar // resources.ApplyResources(this.progressBar, "progressBar"); this.progressBar.Name = "progressBar"; this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Marquee; // // btnEmail // resources.ApplyResources(this.btnEmail, "btnEmail"); this.btnEmail.Name = "btnEmail"; // // lblProgressMessage // resources.ApplyResources(this.lblProgressMessage, "lblProgressMessage"); this.lblProgressMessage.BackColor = System.Drawing.Color.Transparent; this.lblProgressMessage.Name = "lblProgressMessage"; // // btnCopy // resources.ApplyResources(this.btnCopy, "btnCopy"); this.btnCopy.Name = "btnCopy"; // // btnDetailToggle // resources.ApplyResources(this.btnDetailToggle, "btnDetailToggle"); this.btnDetailToggle.Name = "btnDetailToggle"; // // txtExceptionMessageLarge // resources.ApplyResources(this.txtExceptionMessageLarge, "txtExceptionMessageLarge"); this.txtExceptionMessageLarge.BackColor = System.Drawing.Color.White; this.txtExceptionMessageLarge.Name = "txtExceptionMessageLarge"; this.txtExceptionMessageLarge.ReadOnly = true; // // btnClose // resources.ApplyResources(this.btnClose, "btnClose"); this.btnClose.Name = "btnClose"; // // lessDetailPanel // resources.ApplyResources(this.lessDetailPanel, "lessDetailPanel"); this.lessDetailPanel.BackColor = System.Drawing.Color.White; this.lessDetailPanel.Controls.Add(this.lessDetail_optionsPanel); this.lessDetailPanel.Controls.Add(this.txtExceptionMessageLarge2); this.lessDetailPanel.Controls.Add(this.lessDetail_alertIcon); this.lessDetailPanel.Controls.Add(this.label1); this.lessDetailPanel.Name = "lessDetailPanel"; // // lessDetail_optionsPanel // resources.ApplyResources(this.lessDetail_optionsPanel, "lessDetail_optionsPanel"); this.lessDetail_optionsPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(236)))), ((int)(((byte)(240)))), ((int)(((byte)(245))))); this.lessDetail_optionsPanel.Controls.Add(this.lblContactCompany); this.lessDetail_optionsPanel.Controls.Add(this.btnSimpleEmail); this.lessDetail_optionsPanel.Controls.Add(this.btnSimpleDetailToggle); this.lessDetail_optionsPanel.Controls.Add(this.btnSimpleCopy); this.lessDetail_optionsPanel.Name = "lessDetail_optionsPanel"; // // lblContactCompany // resources.ApplyResources(this.lblContactCompany, "lblContactCompany"); this.lblContactCompany.ForeColor = System.Drawing.Color.SlateGray; this.lblContactCompany.Name = "lblContactCompany"; // // btnSimpleEmail // resources.ApplyResources(this.btnSimpleEmail, "btnSimpleEmail"); this.btnSimpleEmail.FlatAppearance.BorderSize = 0; this.btnSimpleEmail.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(200)))), ((int)(((byte)(230))))); this.btnSimpleEmail.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(228)))), ((int)(((byte)(255))))); this.btnSimpleEmail.Name = "btnSimpleEmail"; // // btnSimpleDetailToggle // resources.ApplyResources(this.btnSimpleDetailToggle, "btnSimpleDetailToggle"); this.btnSimpleDetailToggle.FlatAppearance.BorderSize = 0; this.btnSimpleDetailToggle.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(200)))), ((int)(((byte)(230))))); this.btnSimpleDetailToggle.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(228)))), ((int)(((byte)(255))))); this.btnSimpleDetailToggle.Name = "btnSimpleDetailToggle"; // // btnSimpleCopy // resources.ApplyResources(this.btnSimpleCopy, "btnSimpleCopy"); this.btnSimpleCopy.FlatAppearance.BorderSize = 0; this.btnSimpleCopy.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(200)))), ((int)(((byte)(230))))); this.btnSimpleCopy.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(210)))), ((int)(((byte)(228)))), ((int)(((byte)(255))))); this.btnSimpleCopy.Name = "btnSimpleCopy"; // // txtExceptionMessageLarge2 // resources.ApplyResources(this.txtExceptionMessageLarge2, "txtExceptionMessageLarge2"); this.txtExceptionMessageLarge2.BackColor = System.Drawing.Color.White; this.txtExceptionMessageLarge2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtExceptionMessageLarge2.Name = "txtExceptionMessageLarge2"; this.txtExceptionMessageLarge2.ReadOnly = true; // // lessDetail_alertIcon // resources.ApplyResources(this.lessDetail_alertIcon, "lessDetail_alertIcon"); this.lessDetail_alertIcon.Name = "lessDetail_alertIcon"; this.lessDetail_alertIcon.TabStop = false; // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // ExceptionReportView // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.lessDetailPanel); this.Controls.Add(this.btnClose); this.Controls.Add(this.btnDetailToggle); this.Controls.Add(this.tabControl); this.Controls.Add(this.btnSave); this.Controls.Add(this.progressBar); this.Controls.Add(this.btnEmail); this.Controls.Add(this.lblProgressMessage); this.Controls.Add(this.btnCopy); this.Controls.Add(this.txtExceptionMessageLarge); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ExceptionReportView"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.tabControl.ResumeLayout(false); this.tabGeneral.ResumeLayout(false); this.tabGeneral.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picGeneral)).EndInit(); this.tabAssemblies.ResumeLayout(false); this.tabSysInfo.ResumeLayout(false); this.lessDetailPanel.ResumeLayout(false); this.lessDetailPanel.PerformLayout(); this.lessDetail_optionsPanel.ResumeLayout(false); this.lessDetail_optionsPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.lessDetail_alertIcon)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListView listviewAssemblies; private System.Windows.Forms.TabControl tabControl; private System.Windows.Forms.TabPage tabGeneral; private System.Windows.Forms.Label lblExplanation; private System.Windows.Forms.TextBox txtUserExplanation; private System.Windows.Forms.Label lblDate; private System.Windows.Forms.TextBox txtDate; private System.Windows.Forms.Label lblTime; private System.Windows.Forms.TextBox txtTime; private System.Windows.Forms.Label lblApplication; private System.Windows.Forms.TextBox txtApplicationName; private System.Windows.Forms.Label lblVersion; private System.Windows.Forms.TextBox txtVersion; private System.Windows.Forms.TabPage tabExceptions; private System.Windows.Forms.TabPage tabAssemblies; private System.Windows.Forms.TabPage tabSysInfo; private System.Windows.Forms.TreeView treeEnvironment; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.Button btnEmail; private System.Windows.Forms.Label lblProgressMessage; private System.Windows.Forms.Button btnCopy; private System.Windows.Forms.TextBox txtExceptionMessage; private System.Windows.Forms.PictureBox picGeneral; private System.Windows.Forms.Button btnDetailToggle; private System.Windows.Forms.TextBox txtExceptionMessageLarge; private System.Windows.Forms.Button btnClose; private System.Windows.Forms.Panel lessDetailPanel; private System.Windows.Forms.PictureBox lessDetail_alertIcon; private System.Windows.Forms.Label label1; private System.Windows.Forms.Panel lessDetail_optionsPanel; private System.Windows.Forms.TextBox txtExceptionMessageLarge2; private System.Windows.Forms.Label lblContactCompany; private System.Windows.Forms.Button btnSimpleEmail; private System.Windows.Forms.Button btnSimpleCopy; private System.Windows.Forms.Button btnSimpleDetailToggle; } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. * */ #endregion using System; using System.Collections.Generic; using Quartz.Core; using Quartz.Impl.Matchers; namespace Quartz.Spi { /// <summary> /// The interface to be implemented by classes that want to provide a <see cref="IJob" /> /// and <see cref="ITrigger" /> storage mechanism for the /// <see cref="QuartzScheduler" />'s use. /// </summary> /// <remarks> /// Storage of <see cref="IJob" /> s and <see cref="ITrigger" /> s should be keyed /// on the combination of their name and group for uniqueness. /// </remarks> /// <seealso cref="QuartzScheduler" /> /// <seealso cref="ITrigger" /> /// <seealso cref="IJob" /> /// <seealso cref="IJobDetail" /> /// <seealso cref="JobDataMap" /> /// <seealso cref="ICalendar" /> /// <author>James House</author> /// <author>Marko Lahma (.NET)</author> public interface IJobStore { /// <summary> /// Called by the QuartzScheduler before the <see cref="IJobStore" /> is /// used, in order to give the it a chance to Initialize. /// </summary> void Initialize(ITypeLoadHelper loadHelper, ISchedulerSignaler signaler); /// <summary> /// Called by the QuartzScheduler to inform the <see cref="IJobStore" /> that /// the scheduler has started. /// </summary> void SchedulerStarted(); /// <summary> /// Called by the QuartzScheduler to inform the JobStore that /// the scheduler has been paused. /// </summary> void SchedulerPaused(); /// <summary> /// Called by the QuartzScheduler to inform the JobStore that /// the scheduler has resumed after being paused. /// </summary> void SchedulerResumed(); /// <summary> /// Called by the QuartzScheduler to inform the <see cref="IJobStore" /> that /// it should free up all of it's resources because the scheduler is /// shutting down. /// </summary> void Shutdown(); /// <summary> /// Indicates whether job store supports persistence. /// </summary> /// <returns></returns> bool SupportsPersistence { get; } /// <summary> /// How long (in milliseconds) the <see cref="IJobStore" /> implementation /// estimates that it will take to release a trigger and acquire a new one. /// </summary> long EstimatedTimeToReleaseAndAcquireTrigger { get; } /// <summary> /// Whether or not the <see cref="IJobStore" /> implementation is clustered. /// </summary> /// <returns></returns> bool Clustered { get; } /// <summary> /// Store the given <see cref="IJobDetail" /> and <see cref="ITrigger" />. /// </summary> /// <param name="newJob">The <see cref="IJobDetail" /> to be stored.</param> /// <param name="newTrigger">The <see cref="ITrigger" /> to be stored.</param> /// <throws> ObjectAlreadyExistsException </throws> void StoreJobAndTrigger(IJobDetail newJob, IOperableTrigger newTrigger); /// <summary> /// returns true if the given JobGroup is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> bool IsJobGroupPaused(string groupName); /// <summary> /// returns true if the given TriggerGroup /// is paused /// </summary> /// <param name="groupName"></param> /// <returns></returns> bool IsTriggerGroupPaused(string groupName); /// <summary> /// Store the given <see cref="IJobDetail" />. /// </summary> /// <param name="newJob">The <see cref="IJobDetail" /> to be stored.</param> /// <param name="replaceExisting"> /// If <see langword="true" />, any <see cref="IJob" /> existing in the /// <see cref="IJobStore" /> with the same name and group should be /// over-written. /// </param> void StoreJob(IJobDetail newJob, bool replaceExisting); void StoreJobsAndTriggers(IDictionary<IJobDetail, Collection.ISet<ITrigger>> triggersAndJobs, bool replace); /// <summary> /// Remove (delete) the <see cref="IJob" /> with the given /// key, and any <see cref="ITrigger" /> s that reference /// it. /// </summary> /// <remarks> /// If removal of the <see cref="IJob" /> results in an empty group, the /// group should be removed from the <see cref="IJobStore" />'s list of /// known group names. /// </remarks> /// <returns> /// <see langword="true" /> if a <see cref="IJob" /> with the given name and /// group was found and removed from the store. /// </returns> bool RemoveJob(JobKey jobKey); bool RemoveJobs(IList<JobKey> jobKeys); /// <summary> /// Retrieve the <see cref="IJobDetail" /> for the given /// <see cref="IJob" />. /// </summary> /// <returns> /// The desired <see cref="IJob" />, or null if there is no match. /// </returns> IJobDetail RetrieveJob(JobKey jobKey); /// <summary> /// Store the given <see cref="ITrigger" />. /// </summary> /// <param name="newTrigger">The <see cref="ITrigger" /> to be stored.</param> /// <param name="replaceExisting">If <see langword="true" />, any <see cref="ITrigger" /> existing in /// the <see cref="IJobStore" /> with the same name and group should /// be over-written.</param> /// <throws> ObjectAlreadyExistsException </throws> void StoreTrigger(IOperableTrigger newTrigger, bool replaceExisting); /// <summary> /// Remove (delete) the <see cref="ITrigger" /> with the given key. /// </summary> /// <remarks> /// <para> /// If removal of the <see cref="ITrigger" /> results in an empty group, the /// group should be removed from the <see cref="IJobStore" />'s list of /// known group names. /// </para> /// <para> /// If removal of the <see cref="ITrigger" /> results in an 'orphaned' <see cref="IJob" /> /// that is not 'durable', then the <see cref="IJob" /> should be deleted /// also. /// </para> /// </remarks> /// <returns> /// <see langword="true" /> if a <see cref="ITrigger" /> with the given /// name and group was found and removed from the store. /// </returns> bool RemoveTrigger(TriggerKey triggerKey); bool RemoveTriggers(IList<TriggerKey> triggerKeys); /// <summary> /// Remove (delete) the <see cref="ITrigger" /> with the /// given name, and store the new given one - which must be associated /// with the same job. /// </summary> /// <param name="triggerKey">The <see cref="ITrigger"/> to be replaced.</param> /// <param name="newTrigger">The new <see cref="ITrigger" /> to be stored.</param> /// <returns> /// <see langword="true" /> if a <see cref="ITrigger" /> with the given /// name and group was found and removed from the store. /// </returns> bool ReplaceTrigger(TriggerKey triggerKey, IOperableTrigger newTrigger); /// <summary> /// Retrieve the given <see cref="ITrigger" />. /// </summary> /// <returns> /// The desired <see cref="ITrigger" />, or null if there is no /// match. /// </returns> IOperableTrigger RetrieveTrigger(TriggerKey triggerKey); /// <summary> /// Determine whether a <see cref="IJob" /> with the given identifier already /// exists within the scheduler. /// </summary> /// <remarks> /// </remarks> /// <param name="jobKey">the identifier to check for</param> /// <returns>true if a job exists with the given identifier</returns> bool CheckExists(JobKey jobKey); /// <summary> /// Determine whether a <see cref="ITrigger" /> with the given identifier already /// exists within the scheduler. /// </summary> /// <remarks> /// </remarks> /// <param name="triggerKey">the identifier to check for</param> /// <returns>true if a trigger exists with the given identifier</returns> bool CheckExists(TriggerKey triggerKey); /// <summary> /// Clear (delete!) all scheduling data - all <see cref="IJob"/>s, <see cref="ITrigger" />s /// <see cref="ICalendar" />s. /// </summary> /// <remarks> /// </remarks> void ClearAllSchedulingData(); /// <summary> /// Store the given <see cref="ICalendar" />. /// </summary> /// <param name="name">The name.</param> /// <param name="calendar">The <see cref="ICalendar" /> to be stored.</param> /// <param name="replaceExisting">If <see langword="true" />, any <see cref="ICalendar" /> existing /// in the <see cref="IJobStore" /> with the same name and group /// should be over-written.</param> /// <param name="updateTriggers">If <see langword="true" />, any <see cref="ITrigger" />s existing /// in the <see cref="IJobStore" /> that reference an existing /// Calendar with the same name with have their next fire time /// re-computed with the new <see cref="ICalendar" />.</param> /// <throws> ObjectAlreadyExistsException </throws> void StoreCalendar(string name, ICalendar calendar, bool replaceExisting, bool updateTriggers); /// <summary> /// Remove (delete) the <see cref="ICalendar" /> with the /// given name. /// </summary> /// <remarks> /// If removal of the <see cref="ICalendar" /> would result in /// <see cref="ITrigger" />s pointing to non-existent calendars, then a /// <see cref="JobPersistenceException" /> will be thrown. /// </remarks> /// <param name="calName">The name of the <see cref="ICalendar" /> to be removed.</param> /// <returns> /// <see langword="true" /> if a <see cref="ICalendar" /> with the given name /// was found and removed from the store. /// </returns> bool RemoveCalendar(string calName); /// <summary> /// Retrieve the given <see cref="ITrigger" />. /// </summary> /// <param name="calName">The name of the <see cref="ICalendar" /> to be retrieved.</param> /// <returns> /// The desired <see cref="ICalendar" />, or null if there is no /// match. /// </returns> ICalendar RetrieveCalendar(string calName); /// <summary> /// Get the number of <see cref="IJob" />s that are /// stored in the <see cref="IJobStore" />. /// </summary> /// <returns></returns> int GetNumberOfJobs(); /// <summary> /// Get the number of <see cref="ITrigger" />s that are /// stored in the <see cref="IJobStore" />. /// </summary> /// <returns></returns> int GetNumberOfTriggers(); /// <summary> /// Get the number of <see cref="ICalendar" /> s that are /// stored in the <see cref="IJobStore" />. /// </summary> /// <returns></returns> int GetNumberOfCalendars(); /// <summary> /// Get the names of all of the <see cref="IJob" /> s that /// have the given group name. /// <para> /// If there are no jobs in the given group name, the result should be a /// zero-length array (not <see langword="null" />). /// </para> /// </summary> /// <param name="matcher"></param> /// <returns></returns> Collection.ISet<JobKey> GetJobKeys(GroupMatcher<JobKey> matcher); /// <summary> /// Get the names of all of the <see cref="ITrigger" />s /// that have the given group name. /// <para> /// If there are no triggers in the given group name, the result should be a /// zero-length array (not <see langword="null" />). /// </para> /// </summary> Collection.ISet<TriggerKey> GetTriggerKeys(GroupMatcher<TriggerKey> matcher); /// <summary> /// Get the names of all of the <see cref="IJob" /> /// groups. /// <para> /// If there are no known group names, the result should be a zero-length /// array (not <see langword="null" />). /// </para> /// </summary> IList<string> GetJobGroupNames(); /// <summary> /// Get the names of all of the <see cref="ITrigger" /> /// groups. /// <para> /// If there are no known group names, the result should be a zero-length /// array (not <see langword="null" />). /// </para> /// </summary> IList<string> GetTriggerGroupNames(); /// <summary> /// Get the names of all of the <see cref="ICalendar" /> s /// in the <see cref="IJobStore" />. /// /// <para> /// If there are no Calendars in the given group name, the result should be /// a zero-length array (not <see langword="null" />). /// </para> /// </summary> IList<string> GetCalendarNames(); /// <summary> /// Get all of the Triggers that are associated to the given Job. /// </summary> /// <remarks> /// If there are no matches, a zero-length array should be returned. /// </remarks> IList<IOperableTrigger> GetTriggersForJob(JobKey jobKey); /// <summary> /// Get the current state of the identified <see cref="ITrigger" />. /// </summary> /// <seealso cref="TriggerState" /> TriggerState GetTriggerState(TriggerKey triggerKey); ///////////////////////////////////////////////////////////////////////////// // // Trigger State manipulation methods // ///////////////////////////////////////////////////////////////////////////// /// <summary> /// Pause the <see cref="ITrigger" /> with the given key. /// </summary> void PauseTrigger(TriggerKey triggerKey); /// <summary> /// Pause all of the <see cref="ITrigger" />s in the /// given group. /// </summary> /// <remarks> /// The JobStore should "remember" that the group is paused, and impose the /// pause on any new triggers that are added to the group while the group is /// paused. /// </remarks> Collection.ISet<string> PauseTriggers(GroupMatcher<TriggerKey> matcher); /// <summary> /// Pause the <see cref="IJob" /> with the given key - by /// pausing all of its current <see cref="ITrigger" />s. /// </summary> void PauseJob(JobKey jobKey); /// <summary> /// Pause all of the <see cref="IJob" />s in the given /// group - by pausing all of their <see cref="ITrigger" />s. /// <para> /// The JobStore should "remember" that the group is paused, and impose the /// pause on any new jobs that are added to the group while the group is /// paused. /// </para> /// </summary> /// <seealso cref="string"> /// </seealso> IList<string> PauseJobs(GroupMatcher<JobKey> matcher); /// <summary> /// Resume (un-pause) the <see cref="ITrigger" /> with the /// given key. /// /// <para> /// If the <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </para> /// </summary> /// <seealso cref="string"> /// </seealso> void ResumeTrigger(TriggerKey triggerKey); /// <summary> /// Resume (un-pause) all of the <see cref="ITrigger" />s /// in the given group. /// <para> /// If any <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </para> /// </summary> IList<string> ResumeTriggers(GroupMatcher<TriggerKey> matcher); /// <summary> /// Gets the paused trigger groups. /// </summary> /// <returns></returns> Collection.ISet<string> GetPausedTriggerGroups(); /// <summary> /// Resume (un-pause) the <see cref="IJob" /> with the /// given key. /// <para> /// If any of the <see cref="IJob" />'s<see cref="ITrigger" /> s missed one /// or more fire-times, then the <see cref="ITrigger" />'s misfire /// instruction will be applied. /// </para> /// </summary> void ResumeJob(JobKey jobKey); /// <summary> /// Resume (un-pause) all of the <see cref="IJob" />s in /// the given group. /// <para> /// If any of the <see cref="IJob" /> s had <see cref="ITrigger" /> s that /// missed one or more fire-times, then the <see cref="ITrigger" />'s /// misfire instruction will be applied. /// </para> /// </summary> Collection.ISet<string> ResumeJobs(GroupMatcher<JobKey> matcher); /// <summary> /// Pause all triggers - equivalent of calling <see cref="PauseTriggers" /> /// on every group. /// <para> /// When <see cref="ResumeAll" /> is called (to un-pause), trigger misfire /// instructions WILL be applied. /// </para> /// </summary> /// <seealso cref="ResumeAll" /> void PauseAll(); /// <summary> /// Resume (un-pause) all triggers - equivalent of calling <see cref="ResumeTriggers" /> /// on every group. /// <para> /// If any <see cref="ITrigger" /> missed one or more fire-times, then the /// <see cref="ITrigger" />'s misfire instruction will be applied. /// </para> /// /// </summary> /// <seealso cref="PauseAll" /> void ResumeAll(); /// <summary> /// Get a handle to the next trigger to be fired, and mark it as 'reserved' /// by the calling scheduler. /// </summary> /// <param name="noLaterThan">If &gt; 0, the JobStore should only return a Trigger /// that will fire no later than the time represented in this value as /// milliseconds.</param> /// <param name="maxCount"></param> /// <param name="timeWindow"></param> /// <returns></returns> /// <seealso cref="ITrigger"> /// </seealso> IList<IOperableTrigger> AcquireNextTriggers(DateTimeOffset noLaterThan, int maxCount, TimeSpan timeWindow); /// <summary> /// Inform the <see cref="IJobStore" /> that the scheduler no longer plans to /// fire the given <see cref="ITrigger" />, that it had previously acquired /// (reserved). /// </summary> void ReleaseAcquiredTrigger(IOperableTrigger trigger); /// <summary> /// Inform the <see cref="IJobStore" /> that the scheduler is now firing the /// given <see cref="ITrigger" /> (executing its associated <see cref="IJob" />), /// that it had previously acquired (reserved). /// </summary> /// <returns> /// May return null if all the triggers or their calendars no longer exist, or /// if the trigger was not successfully put into the 'executing' /// state. Preference is to return an empty list if none of the triggers /// could be fired. /// </returns> IList<TriggerFiredResult> TriggersFired(IList<IOperableTrigger> triggers); /// <summary> /// Inform the <see cref="IJobStore" /> that the scheduler has completed the /// firing of the given <see cref="ITrigger" /> (and the execution its /// associated <see cref="IJob" />), and that the <see cref="JobDataMap" /> /// in the given <see cref="IJobDetail" /> should be updated if the <see cref="IJob" /> /// is stateful. /// </summary> void TriggeredJobComplete(IOperableTrigger trigger, IJobDetail jobDetail, SchedulerInstruction triggerInstCode); /// <summary> /// Inform the <see cref="IJobStore" /> of the Scheduler instance's Id, /// prior to initialize being invoked. /// </summary> string InstanceId { set; } /// <summary> /// Inform the <see cref="IJobStore" /> of the Scheduler instance's name, /// prior to initialize being invoked. /// </summary> string InstanceName { set; } /// <summary> /// Tells the JobStore the pool size used to execute jobs. /// </summary> int ThreadPoolSize { set; } } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.38.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Enterprise License Manager API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/google-apps/licensing/'>Enterprise License Manager API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20170213 (774) * <tr><th>API Docs * <td><a href='https://developers.google.com/google-apps/licensing/'> * https://developers.google.com/google-apps/licensing/</a> * <tr><th>Discovery Name<td>licensing * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Enterprise License Manager API can be found at * <a href='https://developers.google.com/google-apps/licensing/'>https://developers.google.com/google-apps/licensing/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Licensing.v1 { /// <summary>The Licensing Service.</summary> public class LicensingService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public LicensingService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public LicensingService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { licenseAssignments = new LicenseAssignmentsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "licensing"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/apps/licensing/v1/product/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "apps/licensing/v1/product/"; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://www.googleapis.com/batch/licensing/v1"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch/licensing/v1"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Enterprise License Manager API.</summary> public class Scope { /// <summary>View and manage G Suite licenses for your domain</summary> public static string AppsLicensing = "https://www.googleapis.com/auth/apps.licensing"; } /// <summary>Available OAuth 2.0 scope constants for use with the Enterprise License Manager API.</summary> public static class ScopeConstants { /// <summary>View and manage G Suite licenses for your domain</summary> public const string AppsLicensing = "https://www.googleapis.com/auth/apps.licensing"; } private readonly LicenseAssignmentsResource licenseAssignments; /// <summary>Gets the LicenseAssignments resource.</summary> public virtual LicenseAssignmentsResource LicenseAssignments { get { return licenseAssignments; } } } ///<summary>A base abstract class for Licensing requests.</summary> public abstract class LicensingBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new LicensingBaseServiceRequest instance.</summary> protected LicensingBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>An opaque string that represents a user for quota purposes. Must not exceed 40 /// characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Deprecated. Please use quotaUser instead.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Licensing parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "licenseAssignments" collection of methods.</summary> public class LicenseAssignmentsResource { private const string Resource = "licenseAssignments"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public LicenseAssignmentsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Revoke License.</summary> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> /// <param /// name="userId">email id or unique Id of the user</param> public virtual DeleteRequest Delete(string productId, string skuId, string userId) { return new DeleteRequest(service, productId, skuId, userId); } /// <summary>Revoke License.</summary> public class DeleteRequest : LicensingBaseServiceRequest<string> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Get license assignment of a particular product and sku for a user</summary> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> /// <param /// name="userId">email id or unique Id of the user</param> public virtual GetRequest Get(string productId, string skuId, string userId) { return new GetRequest(service, productId, skuId, userId); } /// <summary>Get license assignment of a particular product and sku for a user</summary> public class GetRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Assign License.</summary> /// <param name="body">The body of the request.</param> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> public virtual InsertRequest Insert(Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert body, string productId, string skuId) { return new InsertRequest(service, body, productId, skuId); } /// <summary>Assign License.</summary> public class InsertRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Insert request.</summary> public InsertRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert body, string productId, string skuId) : base(service) { ProductId = productId; SkuId = skuId; Body = body; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Licensing.v1.Data.LicenseAssignmentInsert Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "insert"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user"; } } /// <summary>Initializes Insert parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>List license assignments for given product of the customer.</summary> /// <param name="productId">Name for product</param> /// <param name="customerId">CustomerId represents the customer /// for whom licenseassignments are queried</param> public virtual ListForProductRequest ListForProduct(string productId, string customerId) { return new ListForProductRequest(service, productId, customerId); } /// <summary>List license assignments for given product of the customer.</summary> public class ListForProductRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignmentList> { /// <summary>Constructs a new ListForProduct request.</summary> public ListForProductRequest(Google.Apis.Services.IClientService service, string productId, string customerId) : base(service) { ProductId = productId; CustomerId = customerId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>CustomerId represents the customer for whom licenseassignments are queried</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerId { get; private set; } /// <summary>Maximum number of campaigns to return at one time. Must be positive. Optional. Default value is /// 100.</summary> /// [default: 100] /// [minimum: 1] /// [maximum: 1000] [Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> MaxResults { get; set; } /// <summary>Token to fetch the next page.Optional. By default server will return first page</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "listForProduct"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/users"; } } /// <summary>Initializes ListForProduct parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "maxResults", new Google.Apis.Discovery.Parameter { Name = "maxResults", IsRequired = false, ParameterType = "query", DefaultValue = "100", Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>List license assignments for given product and sku of the customer.</summary> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku</param> /// <param /// name="customerId">CustomerId represents the customer for whom licenseassignments are queried</param> public virtual ListForProductAndSkuRequest ListForProductAndSku(string productId, string skuId, string customerId) { return new ListForProductAndSkuRequest(service, productId, skuId, customerId); } /// <summary>List license assignments for given product and sku of the customer.</summary> public class ListForProductAndSkuRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignmentList> { /// <summary>Constructs a new ListForProductAndSku request.</summary> public ListForProductAndSkuRequest(Google.Apis.Services.IClientService service, string productId, string skuId, string customerId) : base(service) { ProductId = productId; SkuId = skuId; CustomerId = customerId; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>CustomerId represents the customer for whom licenseassignments are queried</summary> [Google.Apis.Util.RequestParameterAttribute("customerId", Google.Apis.Util.RequestParameterType.Query)] public virtual string CustomerId { get; private set; } /// <summary>Maximum number of campaigns to return at one time. Must be positive. Optional. Default value is /// 100.</summary> /// [default: 100] /// [minimum: 1] /// [maximum: 1000] [Google.Apis.Util.RequestParameterAttribute("maxResults", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<long> MaxResults { get; set; } /// <summary>Token to fetch the next page.Optional. By default server will return first page</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "listForProductAndSku"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/users"; } } /// <summary>Initializes ListForProductAndSku parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "customerId", new Google.Apis.Discovery.Parameter { Name = "customerId", IsRequired = true, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "maxResults", new Google.Apis.Discovery.Parameter { Name = "maxResults", IsRequired = false, ParameterType = "query", DefaultValue = "100", Pattern = null, }); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>Assign License. This method supports patch semantics.</summary> /// <param name="body">The body of the request.</param> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku for which license would be /// revoked</param> /// <param name="userId">email id or unique Id of the user</param> public virtual PatchRequest Patch(Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) { return new PatchRequest(service, body, productId, skuId, userId); } /// <summary>Assign License. This method supports patch semantics.</summary> public class PatchRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; Body = body; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku for which license would be revoked</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Licensing.v1.Data.LicenseAssignment Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Assign License.</summary> /// <param name="body">The body of the request.</param> /// <param name="productId">Name for product</param> /// <param name="skuId">Name for sku for which license would be /// revoked</param> /// <param name="userId">email id or unique Id of the user</param> public virtual UpdateRequest Update(Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) { return new UpdateRequest(service, body, productId, skuId, userId); } /// <summary>Assign License.</summary> public class UpdateRequest : LicensingBaseServiceRequest<Google.Apis.Licensing.v1.Data.LicenseAssignment> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Licensing.v1.Data.LicenseAssignment body, string productId, string skuId, string userId) : base(service) { ProductId = productId; SkuId = skuId; UserId = userId; Body = body; InitParameters(); } /// <summary>Name for product</summary> [Google.Apis.Util.RequestParameterAttribute("productId", Google.Apis.Util.RequestParameterType.Path)] public virtual string ProductId { get; private set; } /// <summary>Name for sku for which license would be revoked</summary> [Google.Apis.Util.RequestParameterAttribute("skuId", Google.Apis.Util.RequestParameterType.Path)] public virtual string SkuId { get; private set; } /// <summary>email id or unique Id of the user</summary> [Google.Apis.Util.RequestParameterAttribute("userId", Google.Apis.Util.RequestParameterType.Path)] public virtual string UserId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Licensing.v1.Data.LicenseAssignment Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{productId}/sku/{skuId}/user/{userId}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "productId", new Google.Apis.Discovery.Parameter { Name = "productId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "skuId", new Google.Apis.Discovery.Parameter { Name = "skuId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userId", new Google.Apis.Discovery.Parameter { Name = "userId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Licensing.v1.Data { /// <summary>Template for LiscenseAssignment Resource</summary> public class LicenseAssignment : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ETag of the resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("etags")] public virtual string Etags { get; set; } /// <summary>Identifies the resource as a LicenseAssignment.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Id of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("productId")] public virtual string ProductId { get; set; } /// <summary>Display Name of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("productName")] public virtual string ProductName { get; set; } /// <summary>Link to this page.</summary> [Newtonsoft.Json.JsonPropertyAttribute("selfLink")] public virtual string SelfLink { get; set; } /// <summary>Id of the sku of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("skuId")] public virtual string SkuId { get; set; } /// <summary>Display Name of the sku of the product.</summary> [Newtonsoft.Json.JsonPropertyAttribute("skuName")] public virtual string SkuName { get; set; } /// <summary>Email id of the user.</summary> [Newtonsoft.Json.JsonPropertyAttribute("userId")] public virtual string UserId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Template for LicenseAssignment Insert request</summary> public class LicenseAssignmentInsert : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Email id of the user</summary> [Newtonsoft.Json.JsonPropertyAttribute("userId")] public virtual string UserId { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>LicesnseAssignment List for a given product/sku for a customer.</summary> public class LicenseAssignmentList : Google.Apis.Requests.IDirectResponseSchema { /// <summary>ETag of the resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("etag")] public virtual string ETag { get; set; } /// <summary>The LicenseAssignments in this page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("items")] public virtual System.Collections.Generic.IList<LicenseAssignment> Items { get; set; } /// <summary>Identifies the resource as a collection of LicenseAssignments.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>The continuation token, used to page through large result sets. Provide this value in a subsequent /// request to return the next page of results.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } } }
// 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.Linq; using NUnit.Framework; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Testing; using osu.Framework.Utils; using osu.Game.Rulesets.Edit; using osu.Game.Rulesets.Mania.Beatmaps; using osu.Game.Rulesets.Mania.Edit; using osu.Game.Rulesets.Mania.Edit.Blueprints.Components; using osu.Game.Rulesets.Mania.Objects; using osu.Game.Rulesets.Mania.Objects.Drawables; using osu.Game.Rulesets.Mania.Skinning.Default; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.UI.Scrolling; using osu.Game.Screens.Edit; using osu.Game.Tests.Visual; using osuTK; using osuTK.Input; namespace osu.Game.Rulesets.Mania.Tests.Editor { public class TestSceneManiaHitObjectComposer : EditorClockTestScene { private TestComposer composer; [SetUp] public void Setup() => Schedule(() => { BeatDivisor.Value = 8; Clock.Seek(0); Child = composer = new TestComposer { RelativeSizeAxes = Axes.Both }; }); [Test] public void TestDragOffscreenSelectionVerticallyUpScroll() { DrawableHitObject lastObject = null; double originalTime = 0; Vector2 originalPosition = Vector2.Zero; setScrollStep(ScrollingDirection.Up); AddStep("seek to last object", () => { lastObject = this.ChildrenOfType<DrawableHitObject>().Single(d => d.HitObject == composer.EditorBeatmap.HitObjects.Last()); originalTime = lastObject.HitObject.StartTime; Clock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime); }); AddStep("select all objects", () => composer.EditorBeatmap.SelectedHitObjects.AddRange(composer.EditorBeatmap.HitObjects)); AddStep("click last object", () => { originalPosition = lastObject.DrawPosition; InputManager.MoveMouseTo(lastObject); InputManager.PressButton(MouseButton.Left); }); AddStep("move mouse downwards", () => { InputManager.MoveMouseTo(lastObject, new Vector2(0, lastObject.ScreenSpaceDrawQuad.Height * 4)); InputManager.ReleaseButton(MouseButton.Left); }); AddAssert("hitobjects not moved columns", () => composer.EditorBeatmap.HitObjects.All(h => ((ManiaHitObject)h).Column == 0)); AddAssert("hitobjects moved downwards", () => lastObject.DrawPosition.Y - originalPosition.Y > 0); AddAssert("hitobject has moved time", () => lastObject.HitObject.StartTime == originalTime + 125); } [Test] public void TestDragOffscreenSelectionVerticallyDownScroll() { DrawableHitObject lastObject = null; double originalTime = 0; Vector2 originalPosition = Vector2.Zero; setScrollStep(ScrollingDirection.Down); AddStep("seek to last object", () => { lastObject = this.ChildrenOfType<DrawableHitObject>().Single(d => d.HitObject == composer.EditorBeatmap.HitObjects.Last()); originalTime = lastObject.HitObject.StartTime; Clock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime); }); AddStep("select all objects", () => composer.EditorBeatmap.SelectedHitObjects.AddRange(composer.EditorBeatmap.HitObjects)); AddStep("click last object", () => { originalPosition = lastObject.DrawPosition; InputManager.MoveMouseTo(lastObject); InputManager.PressButton(MouseButton.Left); }); AddStep("move mouse upwards", () => { InputManager.MoveMouseTo(lastObject, new Vector2(0, -lastObject.ScreenSpaceDrawQuad.Height * 4)); InputManager.ReleaseButton(MouseButton.Left); }); AddAssert("hitobjects not moved columns", () => composer.EditorBeatmap.HitObjects.All(h => ((ManiaHitObject)h).Column == 0)); AddAssert("hitobjects moved upwards", () => originalPosition.Y - lastObject.DrawPosition.Y > 0); AddAssert("hitobject has moved time", () => lastObject.HitObject.StartTime == originalTime + 125); } [Test] public void TestDragOffscreenSelectionHorizontally() { DrawableHitObject lastObject = null; Vector2 originalPosition = Vector2.Zero; setScrollStep(ScrollingDirection.Down); AddStep("seek to last object", () => { lastObject = this.ChildrenOfType<DrawableHitObject>().Single(d => d.HitObject == composer.EditorBeatmap.HitObjects.Last()); Clock.Seek(composer.EditorBeatmap.HitObjects.Last().StartTime); }); AddStep("select all objects", () => composer.EditorBeatmap.SelectedHitObjects.AddRange(composer.EditorBeatmap.HitObjects)); AddStep("click last object", () => { originalPosition = lastObject.DrawPosition; InputManager.MoveMouseTo(lastObject); InputManager.PressButton(MouseButton.Left); }); AddStep("move mouse right", () => { var firstColumn = composer.Composer.Playfield.GetColumn(0); var secondColumn = composer.Composer.Playfield.GetColumn(1); InputManager.MoveMouseTo(lastObject, new Vector2(secondColumn.ScreenSpaceDrawQuad.Centre.X - firstColumn.ScreenSpaceDrawQuad.Centre.X + 1, 0)); InputManager.ReleaseButton(MouseButton.Left); }); AddAssert("hitobjects moved columns", () => composer.EditorBeatmap.HitObjects.All(h => ((ManiaHitObject)h).Column == 1)); // Todo: They'll move vertically by the height of a note since there's no snapping and the selection point is the middle of the note. AddAssert("hitobjects not moved vertically", () => lastObject.DrawPosition.Y - originalPosition.Y <= DefaultNotePiece.NOTE_HEIGHT); } [Test] public void TestDragHoldNoteSelectionVertically() { setScrollStep(ScrollingDirection.Down); AddStep("setup beatmap", () => { composer.EditorBeatmap.Clear(); composer.EditorBeatmap.Add(new HoldNote { Column = 1, EndTime = 200 }); }); DrawableHoldNote holdNote = null; AddStep("grab hold note", () => { holdNote = this.ChildrenOfType<DrawableHoldNote>().Single(); InputManager.MoveMouseTo(holdNote); InputManager.PressButton(MouseButton.Left); }); AddStep("move drag upwards", () => { InputManager.MoveMouseTo(holdNote, new Vector2(0, -100)); InputManager.ReleaseButton(MouseButton.Left); }); AddAssert("head note positioned correctly", () => Precision.AlmostEquals(holdNote.ScreenSpaceDrawQuad.BottomLeft, holdNote.Head.ScreenSpaceDrawQuad.BottomLeft)); AddAssert("tail note positioned correctly", () => Precision.AlmostEquals(holdNote.ScreenSpaceDrawQuad.TopLeft, holdNote.Tail.ScreenSpaceDrawQuad.BottomLeft)); AddAssert("head blueprint positioned correctly", () => this.ChildrenOfType<EditNotePiece>().ElementAt(0).DrawPosition == holdNote.Head.DrawPosition); AddAssert("tail blueprint positioned correctly", () => this.ChildrenOfType<EditNotePiece>().ElementAt(1).DrawPosition == holdNote.Tail.DrawPosition); } private void setScrollStep(ScrollingDirection direction) => AddStep($"set scroll direction = {direction}", () => ((Bindable<ScrollingDirection>)composer.Composer.ScrollingInfo.Direction).Value = direction); private class TestComposer : CompositeDrawable { [Cached(typeof(EditorBeatmap))] [Cached(typeof(IBeatSnapProvider))] public readonly EditorBeatmap EditorBeatmap; public readonly ManiaHitObjectComposer Composer; public TestComposer() { InternalChildren = new Drawable[] { EditorBeatmap = new EditorBeatmap(new ManiaBeatmap(new StageDefinition { Columns = 4 }) { BeatmapInfo = { Ruleset = new ManiaRuleset().RulesetInfo } }), Composer = new ManiaHitObjectComposer(new ManiaRuleset()) }; for (int i = 0; i < 10; i++) EditorBeatmap.Add(new Note { StartTime = 125 * i }); } } } }
using Microsoft.IdentityModel; using SharePointPnP.IdentityModel.Extensions.S2S.Protocols.OAuth2; using SharePointPnP.IdentityModel.Extensions.S2S.Tokens; using Microsoft.SharePoint.Client; using Microsoft.SharePoint.Client.EventReceivers; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.IdentityModel.Selectors; using System.IdentityModel.Tokens; using System.IO; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.ServiceModel; using System.Text; using System.Web; using System.Web.Configuration; using System.Web.Script.Serialization; using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction; using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException; using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration; using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials; namespace SharePoint.UIExperience.Scanner.Utilities { internal static class TokenHelper { #region public fields /// <summary> /// SharePoint principal. /// </summary> public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000"; /// <summary> /// Lifetime of HighTrust access token, 12 hours. /// </summary> public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0); #endregion public fields #region public methods /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequest request) { return GetContextTokenFromRequest(new HttpRequestWrapper(request)); } /// <summary> /// Retrieves the context token string from the specified request by looking for well-known parameter names in the /// POSTed form parameters and the querystring. Returns null if no context token is found. /// </summary> /// <param name="request">HttpRequest in which to look for a context token</param> /// <returns>The context token string</returns> public static string GetContextTokenFromRequest(HttpRequestBase request) { string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" }; foreach (string paramName in paramNames) { if (!string.IsNullOrEmpty(request.Form[paramName])) { return request.Form[paramName]; } if (!string.IsNullOrEmpty(request.QueryString[paramName])) { return request.QueryString[paramName]; } } return null; } /// <summary> /// Validate that a specified context token string is intended for this application based on the parameters /// specified in web.config. Parameters used from web.config used for validation include ClientId, /// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present, /// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not /// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an /// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents /// and a JsonWebSecurityToken based on the context token is returned. /// </summary> /// <param name="contextTokenString">The context token to validate</param> /// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation. /// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used /// for validation instead of <paramref name="appHostName"/> .</param> /// <returns>A JsonWebSecurityToken based on the context token.</returns> public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null) { JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler(); SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString); JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken; SharePointContextToken token = SharePointContextToken.Create(jsonToken); string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority; int firstDot = stsAuthority.IndexOf('.'); GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot); AcsHostUrl = stsAuthority.Substring(firstDot + 1); tokenHandler.ValidateToken(jsonToken); string[] acceptableAudiences; if (!String.IsNullOrEmpty(HostedAppHostNameOverride)) { acceptableAudiences = HostedAppHostNameOverride.Split(';'); } else if (appHostName == null) { acceptableAudiences = new[] { HostedAppHostName }; } else { acceptableAudiences = new[] { appHostName }; } bool validationSuccessful = false; string realm = Realm ?? token.Realm; foreach (var audience in acceptableAudiences) { string principal = GetFormattedPrincipal(ClientId, audience, realm); if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal)) { validationSuccessful = true; break; } } if (!validationSuccessful) { throw new AudienceUriValidationFailedException( String.Format(CultureInfo.CurrentCulture, "\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience)); } return token; } /// <summary> /// Retrieves an access token from ACS to call the source of the specified context token at the specified /// targetHost. The targetHost must be registered for the principal that sent the context token. /// </summary> /// <param name="contextToken">Context token issued by the intended access token audience</param> /// <param name="targetHost">Url authority of the target principal</param> /// <returns>An access token with an audience matching the context token's source</returns> public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost) { string targetPrincipalName = contextToken.TargetPrincipalName; // Extract the refreshToken from the context token string refreshToken = contextToken.RefreshToken; if (String.IsNullOrEmpty(refreshToken)) { return null; } string targetRealm = Realm ?? contextToken.Realm; return GetAccessToken(refreshToken, targetPrincipalName, targetHost, targetRealm); } /// <summary> /// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="authorizationCode">Authorization code to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registered for this app</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string authorizationCode, string targetPrincipalName, string targetHost, string targetRealm, Uri redirectUri) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); // Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode( clientId, ClientSecret, authorizationCode, redirectUri, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="refreshToken">Refresh token to exchange for access token</param> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAccessToken( string refreshToken, string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, null, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource); // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Retrieves an app-only access token from ACS to call the specified principal /// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is /// null, the "Realm" setting in web.config will be used instead. /// </summary> /// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param> /// <param name="targetHost">Url authority of the target principal</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <returns>An access token with an audience of the target principal</returns> public static OAuth2AccessTokenResponse GetAppOnlyAccessToken( string targetPrincipalName, string targetHost, string targetRealm) { if (targetRealm == null) { targetRealm = Realm; } string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm); string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm); OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource); oauth2Request.Resource = resource; // Get token OAuth2S2SClient client = new OAuth2S2SClient(); OAuth2AccessTokenResponse oauth2Response; try { oauth2Response = client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse; } catch (WebException wex) { using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream())) { string responseText = sr.ReadToEnd(); throw new WebException(wex.Message + " - " + responseText, wex); } } return oauth2Response; } /// <summary> /// Creates a client context based on the properties of a remote event receiver /// </summary> /// <param name="properties">Properties of a remote event receiver</param> /// <returns>A ClientContext ready to call the web where the event originated</returns> public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties) { Uri sharepointUrl; if (properties.ListEventProperties != null) { sharepointUrl = new Uri(properties.ListEventProperties.WebUrl); } else if (properties.ItemEventProperties != null) { sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl); } else if (properties.WebEventProperties != null) { sharepointUrl = new Uri(properties.WebEventProperties.FullUrl); } else { return null; } if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Creates a client context based on the properties of an app event /// </summary> /// <param name="properties">Properties of an app event</param> /// <param name="useAppWeb">True to target the app web, false to target the host web</param> /// <returns>A ClientContext ready to call the app web or the parent web</returns> public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb) { if (properties.AppEventProperties == null) { return null; } Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl; if (IsHighTrustApp()) { return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null); } return CreateAcsClientContextForUrl(properties, sharepointUrl); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="redirectUri">Redirect URI registered for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string authorizationCode, Uri redirectUri) { return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri); } /// <summary> /// Retrieves an access token from ACS using the specified authorization code, and uses that access token to /// create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="targetPrincipalName">Name of the target SharePoint principal</param> /// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param> /// <param name="targetRealm">Realm to use for the access token's nameid and audience</param> /// <param name="redirectUri">Redirect URI registered for this app</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithAuthorizationCode( string targetUrl, string targetPrincipalName, string authorizationCode, string targetRealm, Uri redirectUri) { Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Uses the specified access token to create a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="accessToken">Access token to be used when calling the specified targetUrl</param> /// <returns>A ClientContext ready to call targetUrl with the specified access token</returns> public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken) { ClientContext clientContext = new ClientContext(targetUrl); clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous; clientContext.FormDigestHandlingEnabled = false; clientContext.ExecutingWebRequest += delegate (object oSender, WebRequestEventArgs webRequestEventArgs) { webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] = "Bearer " + accessToken; }; return clientContext; } /// <summary> /// Retrieves an access token from ACS using the specified context token, and uses that access token to create /// a client context /// </summary> /// <param name="targetUrl">Url of the target SharePoint site</param> /// <param name="contextTokenString">Context token received from the target SharePoint site</param> /// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName /// of web.config will be used instead</param> /// <returns>A ClientContext ready to call targetUrl with a valid access token</returns> public static ClientContext GetClientContextWithContextToken( string targetUrl, string contextTokenString, string appHostUrl) { SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl); Uri targetUri = new Uri(targetUrl); string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken; return GetClientContextWithAccessToken(targetUrl, accessToken); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request consent and get back /// an authorization code. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format /// (e.g. "Web.Read Site.Write")</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is /// granted</param> /// <returns>Url of the SharePoint site's OAuth authorization page</returns> public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri) { return string.Format( "{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}", EnsureTrailingSlash(contextUrl), AuthorizationPage, ClientId, scope, redirectUri); } /// <summary> /// Returns the SharePoint url to which the app should redirect the browser to request a new context token. /// </summary> /// <param name="contextUrl">Absolute Url of the SharePoint site</param> /// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param> /// <returns>Url of the SharePoint site's context token redirect page</returns> public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri) { return string.Format( "{0}{1}?client_id={2}&redirect_uri={3}", EnsureTrailingSlash(contextUrl), RedirectPage, ClientId, redirectUri); } /// <summary> /// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified /// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in /// web.config, an auth challenge will be issued to the targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>An access token with an audience of the target principal</returns> public static string GetS2SAccessTokenWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Windows identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithWindowsIdentity( Uri targetApplicationUri, WindowsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Retrieves an S2S client context with an access token signed by the application's private certificate on /// behalf of the specified ClaimsIdentity and intended for application at the targetApplicationUri using the /// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the /// targetApplicationUri to discover it. Identity claim type and identity provider name (as registered in SharePoint) /// should be specified in configuration file e.g.: /// <appSettings> /// <add key = "IdentityClaimType" value="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" /> /// <add key = "TrustedIdentityTokenIssuerName" value="sso" /> /// </appSettings> /// To discover trusted identity token issuer name use following cmdlet: /// Get-SPTrustedIdentityTokenIssuer | select name /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <param name="identity">Claims identity of the user on whose behalf to create the access token</param> /// <returns>A ClientContext using an access token with an audience of the target application</returns> public static ClientContext GetS2SClientContextWithClaimsIdentity(Uri targetApplicationUri, System.Security.Claims.ClaimsIdentity identity) { string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm; JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithClaimsIdentity(identity, IdentityClaimType, TrustedIdentityTokenIssuerName) : null; string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims); return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken); } /// <summary> /// Get authentication realm from SharePoint /// </summary> /// <param name="targetApplicationUri">Url of the target SharePoint site</param> /// <returns>String representation of the realm GUID</returns> public static string GetRealmFromTargetUrl(Uri targetApplicationUri) { WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc"); request.Headers.Add("Authorization: Bearer "); try { using (request.GetResponse()) { } } catch (WebException e) { if (e.Response == null) { return null; } string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"]; if (string.IsNullOrEmpty(bearerResponseHeader)) { return null; } const string bearer = "Bearer realm=\""; int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal); if (bearerIndex < 0) { return null; } int realmIndex = bearerIndex + bearer.Length; if (bearerResponseHeader.Length >= realmIndex + 36) { string targetRealm = bearerResponseHeader.Substring(realmIndex, 36); Guid realmGuid; if (Guid.TryParse(targetRealm, out realmGuid)) { return targetRealm; } } } return null; } /// <summary> /// Determines if this is a high trust app. /// </summary> /// <returns>True if this is a high trust app.</returns> public static bool IsHighTrustApp() { return SigningCredentials != null; } /// <summary> /// Ensures that the specified URL ends with '/' if it is not null or empty. /// </summary> /// <param name="url">The url.</param> /// <returns>The url ending with '/' if it is not null or empty.</returns> public static string EnsureTrailingSlash(string url) { if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/') { return url + "/"; } return url; } #endregion #region private fields // // Configuration Constants // private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx"; private const string RedirectPage = "_layouts/15/AppRedirect.aspx"; private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000"; private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1"; private const string S2SProtocol = "OAuth2"; private const string DelegationIssuance = "DelegationIssuance1.0"; private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier; private const string TrustedForImpersonationClaimType = "trustedfordelegation"; private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken; // // Hosted app configuration // private static string clientId = null; private static string issuerId = null; private static string hostedAppHostNameOverride = null; private static string hostedAppHostName = null; private static string clientSecret = null; private static string secondaryClientSecret = null; private static string realm = null; private static string serviceNamespace = null; private static string identityClaimType = null; private static string trustedIdentityTokenIssuerName = null; // // Environment Constants // private static string acsHostUrl = "accesscontrol.windows.net"; private static string globalEndPointPrefix = "accounts"; public static string AcsHostUrl { get { if (String.IsNullOrEmpty(acsHostUrl)) { return "accesscontrol.windows.net"; } else { return acsHostUrl; } } set { acsHostUrl = value; } } public static string GlobalEndPointPrefix { get { if (globalEndPointPrefix == null) { return "accounts"; } else { return globalEndPointPrefix; } } set { globalEndPointPrefix = value; } } public static string ClientId { get { if (String.IsNullOrEmpty(clientId)) { return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); } else { return clientId; } } set { clientId = value; } } public static string IssuerId { get { if (String.IsNullOrEmpty(issuerId)) { return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); } else { return issuerId; } } set { issuerId = value; } } public static string HostedAppHostNameOverride { get { if (String.IsNullOrEmpty(hostedAppHostNameOverride)) { return WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); } else { return hostedAppHostNameOverride; } } set { hostedAppHostNameOverride = value; } } public static string HostedAppHostName { get { if (String.IsNullOrEmpty(hostedAppHostName)) { return WebConfigurationManager.AppSettings.Get("HostedAppHostName"); } else { return hostedAppHostName; } } set { hostedAppHostName = value; } } public static string ClientSecret { get { if (String.IsNullOrEmpty(clientSecret)) { return string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); } else { return clientSecret; } } set { clientSecret = value; } } public static string SecondaryClientSecret { get { if (String.IsNullOrEmpty(secondaryClientSecret)) { return WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); } else { return secondaryClientSecret; } } set { secondaryClientSecret = value; } } public static string Realm { get { if (String.IsNullOrEmpty(realm)) { return WebConfigurationManager.AppSettings.Get("Realm"); } else { return realm; } } set { realm = value; } } public static string ServiceNamespace { get { if (String.IsNullOrEmpty(serviceNamespace)) { return WebConfigurationManager.AppSettings.Get("Realm"); } else { return serviceNamespace; } } set { serviceNamespace = value; } } public static string IdentityClaimType { get { if (String.IsNullOrEmpty(identityClaimType)) { return WebConfigurationManager.AppSettings.Get("IdentityClaimType"); } else { return identityClaimType; } } set { identityClaimType = value; } } public static string TrustedIdentityTokenIssuerName { get { if (String.IsNullOrEmpty(trustedIdentityTokenIssuerName)) { return WebConfigurationManager.AppSettings.Get("TrustedIdentityTokenIssuerName"); } else { return trustedIdentityTokenIssuerName; } } set { trustedIdentityTokenIssuerName = value; } } //private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId"); //private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId"); //private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride"); //private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName"); //private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret"); //private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret"); //private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm"); //private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm"); private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath"); private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword"); private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword); private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest); #endregion #region private methods private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl) { string contextTokenString = properties.ContextToken; if (String.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host); string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken; return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken); } private static string GetAcsMetadataEndpointUrl() { return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl); } private static string GetFormattedPrincipal(string principalName, string hostName, string realm) { if (!String.IsNullOrEmpty(hostName)) { return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm); } return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm); } private static string GetAcsPrincipalName(string realm) { return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm); } private static string GetAcsGlobalEndpointUrl() { if (GlobalEndPointPrefix.Length == 0) { return String.Format(CultureInfo.InvariantCulture, "https://{0}/", AcsHostUrl); } else { return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl); } } public static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler() { JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler(); handler.Configuration = new SecurityTokenHandlerConfiguration(); handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never); handler.Configuration.CertificateValidator = X509CertificateValidator.None; List<byte[]> securityKeys = new List<byte[]>(); securityKeys.Add(Convert.FromBase64String(ClientSecret)); if (!string.IsNullOrEmpty(SecondaryClientSecret)) { securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret)); } List<SecurityToken> securityTokens = new List<SecurityToken>(); securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys)); handler.Configuration.IssuerTokenResolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver( new ReadOnlyCollection<SecurityToken>(securityTokens), false); SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry(); foreach (byte[] securitykey in securityKeys) { issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace)); } handler.Configuration.IssuerNameRegistry = issuerNameRegistry; return handler; } private static string GetS2SAccessTokenWithClaims( string targetApplicationHostName, string targetRealm, IEnumerable<JsonWebTokenClaim> claims) { return IssueToken( ClientId, IssuerId, targetRealm, SharePointPrincipal, targetRealm, targetApplicationHostName, true, claims, claims == null); } private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity) { JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()), new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory") }; return claims; } private static JsonWebTokenClaim[] GetClaimsWithClaimsIdentity(System.Security.Claims.ClaimsIdentity identity, string identityClaimType, string trustedProviderName) { var identityClaim = identity.Claims.Where(c => string.Equals(c.Type, identityClaimType, StringComparison.InvariantCultureIgnoreCase)).First(); JsonWebTokenClaim[] claims = new JsonWebTokenClaim[] { new JsonWebTokenClaim(NameIdentifierClaimType, identityClaim.Value), new JsonWebTokenClaim("nii", "trusted:" + trustedProviderName) }; return claims; } private static string IssueToken( string sourceApplication, string issuerApplication, string sourceRealm, string targetApplication, string targetRealm, string targetApplicationHostName, bool trustedForDelegation, IEnumerable<JsonWebTokenClaim> claims, bool appOnly = false) { if (null == SigningCredentials) { throw new InvalidOperationException("SigningCredentials was not initialized"); } #region Actor token string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm); string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm); string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm); List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>(); actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid)); if (trustedForDelegation && !appOnly) { actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true")); } // Create token JsonWebSecurityToken actorToken = new JsonWebSecurityToken( issuer: issuer, audience: audience, validFrom: DateTime.UtcNow, validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), signingCredentials: SigningCredentials, claims: actorClaims); string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken); if (appOnly) { // App-only token is the same as actor token for delegated case return actorTokenString; } #endregion Actor token #region Outer token List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims); outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString)); JsonWebSecurityToken jsonToken = new JsonWebSecurityToken( nameid, // outer token issuer should match actor token nameid audience, DateTime.UtcNow, DateTime.UtcNow.Add(HighTrustAccessTokenLifetime), outerClaims); string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken); #endregion Outer token return accessToken; } #endregion #region AcsMetadataParser // This class is used to get MetaData document from the global STS endpoint. It contains // methods to parse the MetaData document and get endpoints and STS certificate. public static class AcsMetadataParser { public static X509Certificate2 GetAcsSigningCert(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); if (null != document.keys && document.keys.Count > 0) { JsonKey signingKey = document.keys[0]; if (null != signingKey && null != signingKey.keyValue) { return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value)); } } throw new Exception("Metadata document does not contain ACS signing certificate."); } public static string GetDelegationServiceUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance); if (null != delegationEndpoint) { return delegationEndpoint.location; } throw new Exception("Metadata document does not contain Delegation Service endpoint Url"); } private static JsonMetadataDocument GetMetadataDocument(string realm) { string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}", GetAcsMetadataEndpointUrl(), realm); byte[] acsMetadata; using (WebClient webClient = new WebClient()) { acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm); } string jsonResponseString = Encoding.UTF8.GetString(acsMetadata); JavaScriptSerializer serializer = new JavaScriptSerializer(); JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString); if (null == document) { throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm); } return document; } public static string GetStsUrl(string realm) { JsonMetadataDocument document = GetMetadataDocument(realm); JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol); if (null != s2sEndpoint) { return s2sEndpoint.location; } throw new Exception("Metadata document does not contain STS endpoint url"); } private class JsonMetadataDocument { public string serviceName { get; set; } public List<JsonEndpoint> endpoints { get; set; } public List<JsonKey> keys { get; set; } } private class JsonEndpoint { public string location { get; set; } public string protocol { get; set; } public string usage { get; set; } } private class JsonKeyValue { public string type { get; set; } public string value { get; set; } } private class JsonKey { public string usage { get; set; } public JsonKeyValue keyValue { get; set; } } } #endregion } /// <summary> /// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token /// </summary> public class SharePointContextToken : JsonWebSecurityToken { public static SharePointContextToken Create(JsonWebSecurityToken contextToken) { return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims); } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims) : base(issuer, audience, validFrom, validTo, claims) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken) : base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken) { } public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials) : base(issuer, audience, validFrom, validTo, claims, signingCredentials) { } public string NameId { get { return GetClaimValue(this, "nameid"); } } /// <summary> /// The principal name portion of the context token's "appctxsender" claim /// </summary> public string TargetPrincipalName { get { string appctxsender = GetClaimValue(this, "appctxsender"); if (appctxsender == null) { return null; } return appctxsender.Split('@')[0]; } } /// <summary> /// The context token's "refreshtoken" claim /// </summary> public string RefreshToken { get { return GetClaimValue(this, "refreshtoken"); } } /// <summary> /// The context token's "CacheKey" claim /// </summary> public string CacheKey { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string cacheKey = (string)dict["CacheKey"]; return cacheKey; } } /// <summary> /// The context token's "SecurityTokenServiceUri" claim /// </summary> public string SecurityTokenServiceUri { get { string appctx = GetClaimValue(this, "appctx"); if (appctx == null) { return null; } ClientContext ctx = new ClientContext("http://tempuri.org"); Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx); string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"]; return securityTokenServiceUri; } } /// <summary> /// The realm portion of the context token's "audience" claim /// </summary> public string Realm { get { string aud = Audience; if (aud == null) { return null; } string tokenRealm = aud.Substring(aud.IndexOf('@') + 1); return tokenRealm; } } private static string GetClaimValue(JsonWebSecurityToken token, string claimType) { if (token == null) { throw new ArgumentNullException("token"); } foreach (JsonWebTokenClaim claim in token.Claims) { if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType)) { return claim.Value; } } return null; } } /// <summary> /// Represents a security token which contains multiple security keys that are generated using symmetric algorithms. /// </summary> public class MultipleSymmetricKeySecurityToken : SecurityToken { /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys) : this(UniqueId.CreateUniqueId(), keys) { } /// <summary> /// Initializes a new instance of the MultipleSymmetricKeySecurityToken class. /// </summary> /// <param name="tokenId">The unique identifier of the security token.</param> /// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param> public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys) { if (keys == null) { throw new ArgumentNullException("keys"); } if (String.IsNullOrEmpty(tokenId)) { throw new ArgumentException("Value cannot be a null or empty string.", "tokenId"); } foreach (byte[] key in keys) { if (key.Length <= 0) { throw new ArgumentException("The key length must be greater then zero.", "keys"); } } id = tokenId; effectiveTime = DateTime.UtcNow; securityKeys = CreateSymmetricSecurityKeys(keys); } /// <summary> /// Gets the unique identifier of the security token. /// </summary> public override string Id { get { return id; } } /// <summary> /// Gets the cryptographic keys associated with the security token. /// </summary> public override ReadOnlyCollection<SecurityKey> SecurityKeys { get { return securityKeys.AsReadOnly(); } } /// <summary> /// Gets the first instant in time at which this security token is valid. /// </summary> public override DateTime ValidFrom { get { return effectiveTime; } } /// <summary> /// Gets the last instant in time at which this security token is valid. /// </summary> public override DateTime ValidTo { get { // Never expire return DateTime.MaxValue; } } /// <summary> /// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier. /// </summary> /// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param> /// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns> public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause) { if (keyIdentifierClause == null) { throw new ArgumentNullException("keyIdentifierClause"); } // Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the // presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later // when the key is matched to the issuer. if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause) { return true; } return base.MatchesKeyIdentifierClause(keyIdentifierClause); } #region private members private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys) { List<SecurityKey> symmetricKeys = new List<SecurityKey>(); foreach (byte[] key in keys) { symmetricKeys.Add(new InMemorySymmetricSecurityKey(key)); } return symmetricKeys; } private string id; private DateTime effectiveTime; private List<SecurityKey> securityKeys; #endregion } }
/* * Naiad ver. 0.5 * Copyright (c) Microsoft Corporation * 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 * * THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT * LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR * A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. * * See the Apache Version 2.0 License for specific language governing * permissions and limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Research.Naiad; using Microsoft.Research.Naiad.Frameworks.DifferentialDataflow; namespace Microsoft.Research.Naiad.Examples.DifferentialDataflow { /// <summary> /// Demonstrates a more complicated interactive Naiad program. /// This code example was suggested by Russell Power, while an intern at MSR SVC. /// </summary> public class SearchIndex : Example { #region Custom datatypes to make things prettier public struct Document : IEquatable<Document> { public string text; public int id; public bool Equals(Document that) { return this.text == that.text && this.id == that.id; } public override int GetHashCode() { return text.GetHashCode() + id; } public Document(string t, int i) { text = t; id = i; } } public struct Query : IEquatable<Query> { public string text; public int id; public int threshold; public bool Equals(Query that) { return this.text == that.text && this.id == that.id && this.threshold == that.threshold; } public override int GetHashCode() { return text.GetHashCode() + id + threshold; } public Query(string t, int i, int thr) { text = t; id = i; threshold = thr; } } public struct Match : IEquatable<Match> { public int document; public int query; public int threshold; public bool Equals(Match that) { return this.document == that.document && this.query == that.query && this.threshold == that.threshold; } public override int GetHashCode() { return document + query + threshold; } public Match(int d, int q, int t) { document = d; query = q; threshold = t; } } #endregion public void Execute(string[] args) { int documentCount = 100000; int vocabulary = 100000; int batchSize = 10000; int iterations = 10; using (var computation = NewComputation.FromArgs(ref args)) { #region building up input data if (args.Length == 5) { documentCount = Convert.ToInt32(args[1]); vocabulary = Convert.ToInt32(args[2]); batchSize = Convert.ToInt32(args[3]); iterations = Convert.ToInt32(args[4]); } var random = new Random(0); List<Document> docs = Enumerable.Range(0, documentCount) .Select(i => new Document(Enumerable.Range(0, 10) .Select(j => String.Format("{0}", random.Next(vocabulary))) .Aggregate((x, y) => x + " " + y), i)).ToList<Document>(); List<Query>[] queryBatches = new List<Query>[iterations]; for (int i = 0; i < iterations; i++) { queryBatches[i] = Enumerable.Range(i * batchSize, batchSize) .Select(j => new Query(String.Format("{0}", j % vocabulary), j, 1)) .ToList(); } #endregion // declare inputs for documents and queries. var documents = computation.NewInputCollection<Document>(); var queries = computation.NewInputCollection<Query>(); // each document is broken down into a collection of terms, each with associated identifier. var dTerms = documents.SelectMany(doc => doc.text.Split(' ').Select(term => new Document(term, doc.id))) .Distinct(); // each query is broken down into a collection of terms, each with associated identifier and threshold. var qTerms = queries.SelectMany(query => query.text.Split(' ').Select(term => new Query(term, query.id, query.threshold))) .Distinct(); // doc terms and query terms are joined, matching pairs are counted and returned if the count exceeds the threshold. var results = dTerms.Join(qTerms, d => d.text, q => q.text, (d, q) => new Match(d.id, q.id, q.threshold)) .Count(match => match) .Select(pair => new Match(pair.First.document, pair.First.query, pair.First.threshold - (int)pair.Second)) .Where(match => match.threshold <= 0) .Select(match => new Pair<int, int>(match.document, match.query)); // subscribe to the output in case we are interested in the results var subscription = results.Subscribe(list => Console.WriteLine("matches found: {0}", list.Length)); computation.Activate(); #region Prepare some fake documents to put in the collection // creates many documents each containing 10 words from [0, ... vocabulary-1]. int share_size = docs.Count / computation.Configuration.Processes; documents.OnNext(docs.GetRange(computation.Configuration.ProcessID * share_size, share_size)); queries.OnNext(); //Console.WriteLine("Example SearchIndex in Naiad. Step 1: indexing documents, step 2: issuing queries."); Console.WriteLine("Indexing {0} random documents, {1} terms (please wait)", documentCount, 10 * documentCount); subscription.Sync(0); #endregion #region Issue batches of queries and assess performance if (computation.Configuration.ProcessID == 0) { Console.WriteLine("Issuing {0} rounds of batches of {1} queries (press [enter] to start)", iterations, batchSize); Console.ReadLine(); } for (int i = 0; i < iterations; i++) { // we round-robin through query terms. more advanced queries are possible. if (computation.Configuration.ProcessID == 0) queries.OnNext(queryBatches[i]); // introduce new queries. else queries.OnNext(); documents.OnNext(); // indicate no new docs. subscription.Sync(i + 1); // block until round is done. } documents.OnCompleted(); queries.OnCompleted(); #endregion computation.Join(); } } public string Usage { get { return ""; } } public string Help { get { return "Demonstrates a dataflow implementation of a searchable text index. Documents are loaded as bags of words, and issued queries are joined against posting sets (rather than lists) to determine how many of teh query words exist in each document. Documents matching all query terms are returned."; } } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Threading; namespace WebsitePanel.Setup.Actions { public class ActionProgressEventArgs<T> : EventArgs { public string StatusMessage { get; set; } public T EventData { get; set; } public bool Indeterminate { get; set; } } public class ProgressEventArgs : EventArgs { public int Value { get; set; } } public class ActionErrorEventArgs : EventArgs { public string ErrorMessage { get; set; } public Exception OriginalException { get; set; } } public abstract class Action { public event EventHandler<ActionProgressEventArgs<int>> ProgressChange; public event EventHandler<ActionProgressEventArgs<bool>> PrerequisiteComplete; protected object objectLock = new Object(); public virtual bool Indeterminate { get { return true; } } protected void Begin(string message) { OnInstallProgressChanged(message, 0); } protected void Finish(string message) { OnInstallProgressChanged(message, 100); } protected void OnInstallProgressChanged(string message, int progress) { if (ProgressChange == null) return; // ProgressChange(this, new ActionProgressEventArgs<int> { StatusMessage = message, EventData = progress, Indeterminate = this.Indeterminate }); } protected void OnUninstallProgressChanged(string message, int progress) { if (ProgressChange == null) return; // ProgressChange(this, new ActionProgressEventArgs<int> { StatusMessage = message, EventData = progress, Indeterminate = this.Indeterminate }); } protected void OnPrerequisiteCompleted(string message, bool result) { if (PrerequisiteComplete == null) return; // PrerequisiteComplete(this, new ActionProgressEventArgs<bool> { StatusMessage = message, EventData = result }); } } public interface IActionManager { /// <summary> /// /// </summary> event EventHandler<ProgressEventArgs> TotalProgressChanged; /// <summary> /// /// </summary> event EventHandler<ActionProgressEventArgs<int>> ActionProgressChanged; /// <summary> /// /// </summary> event EventHandler<ActionProgressEventArgs<bool>> PrerequisiteComplete; /// <summary> /// /// </summary> event EventHandler<ActionErrorEventArgs> ActionError; /// <summary> /// Gets current variables available in this session /// </summary> SetupVariables SessionVariables { get; } /// <summary> /// /// </summary> /// <param name="action"></param> void AddAction(Action action); /// <summary> /// Triggers manager to run currentScenario specified /// </summary> void Start(); /// <summary> /// Triggers manager to run prerequisites verification procedure /// </summary> void VerifyDistributivePrerequisites(); /// <summary> /// Triggers manager to prepare default parameters for the distributive /// </summary> void PrepareDistributiveDefaults(); /// <summary> /// Initiates rollback procedure from the action specified /// </summary> /// <param name="lastSuccessActionIndex"></param> void Rollback(); } public class BaseActionManager : IActionManager { private List<Action> currentScenario; // private int lastSuccessActionIndex = -1; private SetupVariables sessionVariables; public SetupVariables SessionVariables { get { return sessionVariables; } } protected List<Action> CurrentScenario { get { return currentScenario; } set { currentScenario = value; } } #region Events /// <summary> /// /// </summary> public event EventHandler<ProgressEventArgs> TotalProgressChanged; /// <summary> /// /// </summary> public event EventHandler<ActionProgressEventArgs<int>> ActionProgressChanged; /// <summary> /// /// </summary> public event EventHandler<ActionProgressEventArgs<bool>> PrerequisiteComplete; /// <summary> /// /// </summary> public event EventHandler<ActionErrorEventArgs> ActionError; /// <summary> /// /// </summary> public event EventHandler Initialize; #endregion protected BaseActionManager(SetupVariables sessionVariables) { if (sessionVariables == null) throw new ArgumentNullException("sessionVariables"); // currentScenario = new List<Action>(); // this.sessionVariables = sessionVariables; } private void OnInitialize() { if (Initialize == null) return; // Initialize(this, EventArgs.Empty); } /// <summary> /// Adds action into the list of currentScenario to be executed in the current action manager's session and attaches to its ProgressChange event /// to track the action's execution progress. /// </summary> /// <param name="action">Action to be executed</param> /// <exception cref="ArgumentNullException"/> public virtual void AddAction(Action action) { if (action == null) throw new ArgumentNullException("action"); currentScenario.Add(action); } private void UpdateActionProgress(string actionText, int actionValue, bool indeterminateAction) { OnActionProgressChanged(this, new ActionProgressEventArgs<int> { StatusMessage = actionText, EventData = actionValue, Indeterminate = indeterminateAction }); } private void UpdateTotalProgress(int value) { OnTotalProgressChanged(this, new ProgressEventArgs { Value = value }); } // Fire the Event private void OnTotalProgressChanged(object sender, ProgressEventArgs args) { // Check if there are any Subscribers if (TotalProgressChanged != null) { // Call the Event TotalProgressChanged(sender, args); } } // Fire the Event private void OnActionProgressChanged(object sender, ActionProgressEventArgs<int> args) { // Check if there are any Subscribers if (ActionProgressChanged != null) { // Call the Event ActionProgressChanged(sender, args); } } // Fire the Event private void OnPrerequisiteComplete(object sender, ActionProgressEventArgs<bool> args) { // Check if there are any Subscribers if (PrerequisiteComplete != null) { // Call the Event PrerequisiteComplete(sender, args); } } private void OnActionError(Exception ex) { // if (ActionError == null) return; // var args = new ActionErrorEventArgs { ErrorMessage = "An unexpected error has occurred. We apologize for this inconvenience.\n" + "Please contact Technical Support at info@websitepanel.net.\n\n" + "Make sure you include a copy of the Installer.log file from the\n" + "WebsitePanel Installer home directory.", OriginalException = ex, }; // ActionError(this, args); } /// <summary> /// Starts action execution. /// </summary> public virtual void Start() { var currentActionType = default(Type); #region Executing the installation session // int totalValue = 0; for (int i = 0, progress = 1; i < currentScenario.Count; i++, progress++) { var item = currentScenario[i]; // Get the next action from the queue var action = item as IInstallAction; // Take the action's type to log as much information about it as possible currentActionType = item.GetType(); // if (action != null) { item.ProgressChange += new EventHandler<ActionProgressEventArgs<int>>(action_ProgressChanged); try { // Execute an install action action.Run(SessionVariables); } catch (Exception ex) { // if (currentActionType != default(Type)) { Log.WriteError(String.Format("Failed to execute '{0}' type of action.", currentActionType)); } // Log.WriteError("Here is the original exception...", ex); // if (Utils.IsThreadAbortException(ex)) return; // Notify external clients OnActionError(ex); // Rollback(); // return; } // item.ProgressChange -= new EventHandler<ActionProgressEventArgs<int>>(action_ProgressChanged); // Calculate overall current progress status totalValue = Convert.ToInt32(progress * 100 / currentScenario.Count); // Update overall progress status UpdateTotalProgress(totalValue); } // lastSuccessActionIndex = i; } // totalValue = 100; // UpdateTotalProgress(totalValue); // #endregion } void action_ProgressChanged(object sender, ActionProgressEventArgs<int> e) { // Action progress has been changed UpdateActionProgress(e.StatusMessage, e.EventData, e.Indeterminate); } public virtual void Rollback() { var currentActionType = default(Type); // Log.WriteStart("Rolling back"); // UpdateActionProgress("Rolling back", 0, true); // var totalValue = 0; // UpdateTotalProgress(totalValue); // for (int i = lastSuccessActionIndex, progress = 1; i >= 0; i--, progress++) { var action = currentScenario[i] as IUninstallAction; // if (action != null) { action.ProgressChange += new EventHandler<ActionProgressEventArgs<int>>(action_ProgressChanged); // try { action.Run(sessionVariables); } catch (Exception ex) { if (currentActionType != default(Type)) Log.WriteError(String.Format("Failed to rollback '{0}' action.", currentActionType)); // Log.WriteError("Here is the original exception...", ex); // } // action.ProgressChange -= new EventHandler<ActionProgressEventArgs<int>>(action_ProgressChanged); } // totalValue = Convert.ToInt32(progress * 100 / (lastSuccessActionIndex + 1)); // UpdateTotalProgress(totalValue); } // Log.WriteEnd("Rolled back"); } public void VerifyDistributivePrerequisites() { var currentActionType = default(Type); try { // for (int i = 0; i < currentScenario.Count; i++) { var item = currentScenario[i]; // Get the next action from the queue var action = item as IPrerequisiteAction; // currentActionType = item.GetType(); // if (action != null) { // action.Complete += new EventHandler<ActionProgressEventArgs<bool>>(action_Complete); // Execute an install action action.Run(SessionVariables); // action.Complete -= new EventHandler<ActionProgressEventArgs<bool>>(action_Complete); } } } catch (Exception ex) { // if (currentActionType != default(Type)) { Log.WriteError(String.Format("Failed to execute '{0}' type of action.", currentActionType)); } // Log.WriteError("Here is the original exception...", ex); // if (Utils.IsThreadAbortException(ex)) return; // Notify external clients OnActionError(ex); // return; } } void action_Complete(object sender, ActionProgressEventArgs<bool> e) { OnPrerequisiteComplete(sender, e); } public void PrepareDistributiveDefaults() { // OnInitialize(); // var currentActionType = default(Type); try { // for (int i = 0; i < currentScenario.Count; i++) { // Get the next action from the queue var action = currentScenario[i] as IPrepareDefaultsAction; // if (action == null) { continue; } // currentActionType = action.GetType(); // Execute an install action action.Run(SessionVariables); } } catch (Exception ex) { // if (currentActionType != default(Type)) { Log.WriteError(String.Format("Failed to execute '{0}' type of action.", currentActionType)); } // Log.WriteError("Here is the original exception...", ex); // if (Utils.IsThreadAbortException(ex)) return; // Notify external clients OnActionError(ex); // return; } } } }
#region TypeSpec and related types are based on code from Mono // // System.Type.cs // // Author: // Rodrigo Kumpera <kumpera@gmail.com> // // // Copyright (C) 2010 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Xcst.Compiler.Reflection { class TypeSpec { ITypeIdentifier _name; string? _assemblyName; IList<ITypeIdentifier>? _nested; IList<TypeSpec>? _genericParams; IList<IModifierSpec>? _modifierSpec; bool _isByref; string? _displayFullname; // cache public bool HasModifiers => _modifierSpec != null; public bool HasGenericParameters => _genericParams != null; public bool IsNested => _nested != null && _nested.Count > 0; public bool IsByRef => _isByref; public bool? IsReferenceType { get; set; } public ITypeName Name => _name; public IEnumerable<ITypeName> Nested => _nested ?? (IEnumerable<ITypeName>)Array.Empty<ITypeName>(); public IList<IModifierSpec> Modifiers => _modifierSpec ?? Array.Empty<IModifierSpec>(); public IList<TypeSpec> GenericParameters => _genericParams ?? Array.Empty<TypeSpec>(); internal string DisplayFullName => _displayFullname ?? (_displayFullname = GetDisplayFullName(DisplayNameFormat.Default)); #pragma warning disable CS8618 private TypeSpec() { } #pragma warning restore CS8618 internal TypeSpec(string name) { _name = TypeIdentifiers.FromDisplay(name); } internal TypeSpec(string name, bool isReferenceType) : this(name) { this.IsReferenceType = isReferenceType; } public TypeSpec Clone() => new TypeSpec { _name = ParsedTypeIdentifier(_name.DisplayName), _assemblyName = _assemblyName, _nested = _nested?.ToList(), _modifierSpec = _modifierSpec?.ToList(), _genericParams = _genericParams?.ToList(), _isByref = _isByref, IsReferenceType = this.IsReferenceType }; internal string GetDisplayFullName(DisplayNameFormat flags) { bool wantAssembly = (flags & DisplayNameFormat.WANT_ASSEMBLY) != 0; bool wantModifiers = (flags & DisplayNameFormat.NO_MODIFIERS) == 0; var sb = new StringBuilder(_name.DisplayName); if (_nested != null) { foreach (var n in _nested) { sb.Append('+') .Append(n.DisplayName); } } if (_genericParams != null) { sb.Append('['); for (int i = 0; i < _genericParams.Count; ++i) { if (i > 0) { sb.Append(", "); } if (_genericParams[i]._assemblyName != null) { sb.Append('[') .Append(_genericParams[i].DisplayFullName) .Append(']'); } else { sb.Append(_genericParams[i].DisplayFullName); } } sb.Append(']'); } if (wantModifiers) { GetModifierString(sb); } if (_assemblyName != null && wantAssembly) { sb.Append(", ") .Append(_assemblyName); } return sb.ToString(); } internal string ModifierString() => GetModifierString(new StringBuilder()) .ToString(); StringBuilder GetModifierString(StringBuilder sb) { if (_modifierSpec != null) { foreach (var md in _modifierSpec) { md.Append(sb); } } if (_isByref) { sb.Append('&'); } return sb; } public static TypeSpec Parse(string typeName) { if (typeName is null) throw new ArgumentNullException(nameof(typeName)); int pos = 0; TypeSpec res = Parse(typeName, ref pos, false, true); if (pos < typeName.Length) { throw new ArgumentException("Count not parse the whole type name", nameof(typeName)); } return res; } static TypeSpec Parse(string typeName, ref int p, bool isRecurse, bool allowAqn) { // Invariants: // - On exit p, is updated to pos the current unconsumed character. // // - The callee peeks at but does not consume delimiters following // recurisve parse (so for a recursive call like the args of "Foo[P,Q]" // we'll return with p either on ',' or on ']'. If the name was aqn'd // "Foo[[P,assmblystuff],Q]" on return p with be on the ']' just // after the "assmblystuff") // // - If allowAqn is True, assembly qualification is optional. // If allowAqn is False, assembly qualification is prohibited. int pos = p; int nameStart; bool inModifiers = false; var data = new TypeSpec(); SkipSpace(typeName, ref pos); nameStart = pos; for (; pos < typeName.Length; ++pos) { switch (typeName[pos]) { case '+': data.AddName(typeName.Substring(nameStart, pos - nameStart)); nameStart = pos + 1; break; case ',': case ']': data.AddName(typeName.Substring(nameStart, pos - nameStart)); nameStart = pos + 1; inModifiers = true; if (isRecurse && !allowAqn) { p = pos; return data; } break; case '&': case '*': case '[': if (typeName[pos] != '[' && isRecurse) { throw new ArgumentException("Generic argument can't be byref or pointer type", nameof(typeName)); } data.AddName(typeName.Substring(nameStart, pos - nameStart)); nameStart = pos + 1; inModifiers = true; break; case '\\': pos++; break; } if (inModifiers) { break; } } if (nameStart < pos) { data.AddName(typeName.Substring(nameStart, pos - nameStart)); } else if (nameStart == pos) { data.AddName(String.Empty); } if (inModifiers) { for (; pos < typeName.Length; ++pos) { switch (typeName[pos]) { case '&': if (data._isByref) { throw new ArgumentException("Can't have a byref of a byref", nameof(typeName)); } data._isByref = true; break; case '*': if (data._isByref) { throw new ArgumentException("Can't have a pointer to a byref type", nameof(typeName)); } // take subsequent '*'s too int pointer_level = 1; while (pos + 1 < typeName.Length && typeName[pos + 1] == '*') { ++pos; ++pointer_level; } data.AddModifier(new PointerSpec(pointer_level)); break; case ',': if (isRecurse && allowAqn) { int end = pos; while (end < typeName.Length && typeName[end] != ']') { ++end; } if (end >= typeName.Length) { throw new ArgumentException("Unmatched ']' while parsing generic argument assembly name"); } data._assemblyName = typeName.Substring(pos + 1, end - pos - 1).Trim(); p = end; return data; } if (isRecurse) { p = pos; return data; } if (allowAqn) { data._assemblyName = typeName.Substring(pos + 1).Trim(); pos = typeName.Length; } break; case '[': if (data._isByref) { throw new ArgumentException("Byref qualifier must be the last one of a type", nameof(typeName)); } ++pos; if (pos >= typeName.Length) { throw new ArgumentException("Invalid array/generic spec", nameof(typeName)); } SkipSpace(typeName, ref pos); if (typeName[pos] != ',' && typeName[pos] != '*' && typeName[pos] != ']') { //generic args var args = new List<TypeSpec>(); if (data.HasModifiers) { throw new ArgumentException("generic args after array spec or pointer type", nameof(typeName)); } while (pos < typeName.Length) { SkipSpace(typeName, ref pos); bool aqn = typeName[pos] == '['; if (aqn) { ++pos; //skip '[' to the start of the type } args.Add(Parse(typeName, ref pos, true, aqn)); BoundCheck(pos, typeName); if (aqn) { if (typeName[pos] == ']') { ++pos; } else { throw new ArgumentException("Unclosed assembly-qualified type name at " + typeName[pos], nameof(typeName)); } BoundCheck(pos, typeName); } if (typeName[pos] == ']') { break; } if (typeName[pos] == ',') { ++pos; // skip ',' to the start of the next arg } else { throw new ArgumentException("Invalid generic arguments separator " + typeName[pos], nameof(typeName)); } } if (pos >= typeName.Length || typeName[pos] != ']') { throw new ArgumentException("Error parsing generic params spec", nameof(typeName)); } data.AddGenericParams(args); } else { //array spec int dimensions = 1; bool bound = false; while (pos < typeName.Length && typeName[pos] != ']') { if (typeName[pos] == '*') { if (bound) { throw new ArgumentException("Array spec cannot have 2 bound dimensions", nameof(typeName)); } bound = true; } else if (typeName[pos] != ',') { throw new ArgumentException("Invalid character in array spec " + typeName[pos], nameof(typeName)); } else { ++dimensions; } ++pos; SkipSpace(typeName, ref pos); } if (pos >= typeName.Length || typeName[pos] != ']') { throw new ArgumentException("Error parsing array spec", nameof(typeName)); } if (dimensions > 1 && bound) { throw new ArgumentException("Invalid array spec, multi-dimensional array cannot be bound", nameof(typeName)); } data.AddModifier(new ArraySpec(dimensions, bound)); } break; case ']': if (isRecurse) { p = pos; return data; } throw new ArgumentException("Unmatched ']'", nameof(typeName)); default: throw new ArgumentException("Bad type def, can't handle '" + typeName[pos] + "'" + " at " + pos, nameof(typeName)); } } } p = pos; return data; } internal static string EscapeDisplayName(string internalName) { // initial capacity = length of internalName. // Maybe we won't have to escape anything. var res = new StringBuilder(internalName.Length); foreach (char c in internalName) { switch (c) { case '+': case ',': case '[': case ']': case '*': case '&': case '\\': res.Append('\\') .Append(c); break; default: res.Append(c); break; } } return res.ToString(); } internal static string UnescapeInternalName(string displayName) { var res = new StringBuilder(displayName.Length); for (int i = 0; i < displayName.Length; ++i) { char c = displayName[i]; if (c == '\\') { if (++i < displayName.Length) { c = displayName[i]; } } res.Append(c); } return res.ToString(); } internal static bool NeedsEscaping(string internalName) { foreach (char c in internalName) { switch (c) { case ',': case '+': case '*': case '&': case '[': case ']': case '\\': return true; default: break; } } return false; } internal void AddName(string typeName) { if (_name is null) { _name = ParsedTypeIdentifier(typeName); } else { if (_nested is null) { _nested = new List<ITypeIdentifier>(); } _nested.Add(ParsedTypeIdentifier(typeName)); } } internal void AddGenericParams(IList<TypeSpec> args) { _genericParams = args; } internal void AddModifier(IModifierSpec md) { if (_modifierSpec is null) { _modifierSpec = new List<IModifierSpec>(); } _modifierSpec.Add(md); } static void SkipSpace(string name, ref int pos) { int p = pos; while (p < name.Length && Char.IsWhiteSpace(name[p])) { ++p; } pos = p; } static void BoundCheck(int idx, string s) { if (idx >= s.Length) { throw new ArgumentException("Invalid generic arguments spec", "typeName"); } } static ITypeIdentifier ParsedTypeIdentifier(string displayName) => TypeIdentifiers.FromDisplay(displayName); internal ITypeName TypeNameWithoutModifiers() => new TypeSpecTypeName(this, false); internal ITypeName TypeName() => new TypeSpecTypeName(this, true); #if DEBUG public override string ToString() => GetDisplayFullName(DisplayNameFormat.WANT_ASSEMBLY); #endif class TypeSpecTypeName : TypeNames.ATypeName, ITypeName { readonly TypeSpec _ts; readonly bool _wantModifiers; public override string DisplayName => (_wantModifiers) ? _ts.DisplayFullName : _ts.GetDisplayFullName(DisplayNameFormat.NO_MODIFIERS); internal TypeSpecTypeName(TypeSpec ts, bool wantModifiers) { _ts = ts; _wantModifiers = wantModifiers; } public override ITypeName NestedName(ITypeIdentifier innerName) => TypeNames.FromDisplay(DisplayName + "+" + innerName.DisplayName); } } [Flags] enum DisplayNameFormat { Default = 0x0, WANT_ASSEMBLY = 0x1, NO_MODIFIERS = 0x2, } interface IModifierSpec { Type Resolve(Type type); StringBuilder Append(StringBuilder sb); } class ArraySpec : IModifierSpec { // dimensions == 1 and bound, or dimensions > 1 and !bound readonly int _dimensions; readonly bool _bound; public int Rank => _dimensions; public bool IsBound => _bound; internal ArraySpec(int dimensions, bool bound) { _dimensions = dimensions; _bound = bound; } public Type Resolve(Type type) { if (_bound) { return type.MakeArrayType(1); } if (_dimensions == 1) { return type.MakeArrayType(); } return type.MakeArrayType(_dimensions); } public StringBuilder Append(StringBuilder sb) { if (_bound) { return sb.Append("[*]"); } return sb.Append('[') .Append(',', _dimensions - 1) .Append(']'); } public override string ToString() => Append(new StringBuilder()) .ToString(); } class PointerSpec : IModifierSpec { readonly int _pointerLevel; internal PointerSpec(int pointerLevel) { _pointerLevel = pointerLevel; } public Type Resolve(Type type) { for (int i = 0; i < _pointerLevel; ++i) { type = type.MakePointerType(); } return type; } public StringBuilder Append(StringBuilder sb) => sb.Append('*', _pointerLevel); public override string ToString() => Append(new StringBuilder()) .ToString(); } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.14.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Groups Settings API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://developers.google.com/google-apps/groups-settings/get_started'>Groups Settings API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20160525 (510) * <tr><th>API Docs * <td><a href='https://developers.google.com/google-apps/groups-settings/get_started'> * https://developers.google.com/google-apps/groups-settings/get_started</a> * <tr><th>Discovery Name<td>groupssettings * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Groups Settings API can be found at * <a href='https://developers.google.com/google-apps/groups-settings/get_started'>https://developers.google.com/google-apps/groups-settings/get_started</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Groupssettings.v1 { /// <summary>The Groupssettings Service.</summary> public class GroupssettingsService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public GroupssettingsService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public GroupssettingsService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { groups = new GroupsResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "groupssettings"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://www.googleapis.com/groups/v1/groups/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return "groups/v1/groups/"; } } /// <summary>Available OAuth 2.0 scopes for use with the Groups Settings API.</summary> public class Scope { /// <summary>View and manage the settings of a Google Apps Group</summary> public static string AppsGroupsSettings = "https://www.googleapis.com/auth/apps.groups.settings"; } private readonly GroupsResource groups; /// <summary>Gets the Groups resource.</summary> public virtual GroupsResource Groups { get { return groups; } } } ///<summary>A base abstract class for Groupssettings requests.</summary> public abstract class GroupssettingsBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new GroupssettingsBaseServiceRequest instance.</summary> protected GroupssettingsBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>Data format for the response.</summary> /// [default: atom] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for the response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/atom+xml</summary> [Google.Apis.Util.StringValueAttribute("atom")] Atom, /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>IP address of the site where the request originates. Use this if you want to enforce per-user /// limits.</summary> [Google.Apis.Util.RequestParameterAttribute("userIp", Google.Apis.Util.RequestParameterType.Query)] public virtual string UserIp { get; set; } /// <summary>Initializes Groupssettings parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "atom", Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "userIp", new Google.Apis.Discovery.Parameter { Name = "userIp", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "groups" collection of methods.</summary> public class GroupsResource { private const string Resource = "groups"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public GroupsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Gets one resource by id.</summary> /// <param name="groupUniqueId">The resource ID</param> public virtual GetRequest Get(string groupUniqueId) { return new GetRequest(service, groupUniqueId); } /// <summary>Gets one resource by id.</summary> public class GetRequest : GroupssettingsBaseServiceRequest<Google.Apis.Groupssettings.v1.Data.Groups> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string groupUniqueId) : base(service) { GroupUniqueId = groupUniqueId; InitParameters(); } /// <summary>The resource ID</summary> [Google.Apis.Util.RequestParameterAttribute("groupUniqueId", Google.Apis.Util.RequestParameterType.Path)] public virtual string GroupUniqueId { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{groupUniqueId}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "groupUniqueId", new Google.Apis.Discovery.Parameter { Name = "groupUniqueId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Updates an existing resource. This method supports patch semantics.</summary> /// <param name="body">The body of the request.</param> /// <param name="groupUniqueId">The resource ID</param> public virtual PatchRequest Patch(Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId) { return new PatchRequest(service, body, groupUniqueId); } /// <summary>Updates an existing resource. This method supports patch semantics.</summary> public class PatchRequest : GroupssettingsBaseServiceRequest<Google.Apis.Groupssettings.v1.Data.Groups> { /// <summary>Constructs a new Patch request.</summary> public PatchRequest(Google.Apis.Services.IClientService service, Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId) : base(service) { GroupUniqueId = groupUniqueId; Body = body; InitParameters(); } /// <summary>The resource ID</summary> [Google.Apis.Util.RequestParameterAttribute("groupUniqueId", Google.Apis.Util.RequestParameterType.Path)] public virtual string GroupUniqueId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Groupssettings.v1.Data.Groups Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "patch"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PATCH"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{groupUniqueId}"; } } /// <summary>Initializes Patch parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "groupUniqueId", new Google.Apis.Discovery.Parameter { Name = "groupUniqueId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } /// <summary>Updates an existing resource.</summary> /// <param name="body">The body of the request.</param> /// <param name="groupUniqueId">The resource ID</param> public virtual UpdateRequest Update(Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId) { return new UpdateRequest(service, body, groupUniqueId); } /// <summary>Updates an existing resource.</summary> public class UpdateRequest : GroupssettingsBaseServiceRequest<Google.Apis.Groupssettings.v1.Data.Groups> { /// <summary>Constructs a new Update request.</summary> public UpdateRequest(Google.Apis.Services.IClientService service, Google.Apis.Groupssettings.v1.Data.Groups body, string groupUniqueId) : base(service) { GroupUniqueId = groupUniqueId; Body = body; InitParameters(); } /// <summary>The resource ID</summary> [Google.Apis.Util.RequestParameterAttribute("groupUniqueId", Google.Apis.Util.RequestParameterType.Path)] public virtual string GroupUniqueId { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Groupssettings.v1.Data.Groups Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "update"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "PUT"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "{groupUniqueId}"; } } /// <summary>Initializes Update parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "groupUniqueId", new Google.Apis.Discovery.Parameter { Name = "groupUniqueId", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = null, }); } } } } namespace Google.Apis.Groupssettings.v1.Data { /// <summary>JSON template for Group resource</summary> public class Groups : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Are external members allowed to join the group.</summary> [Newtonsoft.Json.JsonPropertyAttribute("allowExternalMembers")] public virtual string AllowExternalMembers { get; set; } /// <summary>Is google allowed to contact admins.</summary> [Newtonsoft.Json.JsonPropertyAttribute("allowGoogleCommunication")] public virtual string AllowGoogleCommunication { get; set; } /// <summary>If posting from web is allowed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("allowWebPosting")] public virtual string AllowWebPosting { get; set; } /// <summary>If the group is archive only</summary> [Newtonsoft.Json.JsonPropertyAttribute("archiveOnly")] public virtual string ArchiveOnly { get; set; } /// <summary>Custom footer text.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customFooterText")] public virtual string CustomFooterText { get; set; } /// <summary>Default email to which reply to any message should go.</summary> [Newtonsoft.Json.JsonPropertyAttribute("customReplyTo")] public virtual string CustomReplyTo { get; set; } /// <summary>Default message deny notification message</summary> [Newtonsoft.Json.JsonPropertyAttribute("defaultMessageDenyNotificationText")] public virtual string DefaultMessageDenyNotificationText { get; set; } /// <summary>Description of the group</summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Email id of the group</summary> [Newtonsoft.Json.JsonPropertyAttribute("email")] public virtual string Email { get; set; } /// <summary>Whether to include custom footer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("includeCustomFooter")] public virtual string IncludeCustomFooter { get; set; } /// <summary>If this groups should be included in global address list or not.</summary> [Newtonsoft.Json.JsonPropertyAttribute("includeInGlobalAddressList")] public virtual string IncludeInGlobalAddressList { get; set; } /// <summary>If the contents of the group are archived.</summary> [Newtonsoft.Json.JsonPropertyAttribute("isArchived")] public virtual string IsArchived { get; set; } /// <summary>The type of the resource.</summary> [Newtonsoft.Json.JsonPropertyAttribute("kind")] public virtual string Kind { get; set; } /// <summary>Maximum message size allowed.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maxMessageBytes")] public virtual System.Nullable<int> MaxMessageBytes { get; set; } /// <summary>Can members post using the group email address.</summary> [Newtonsoft.Json.JsonPropertyAttribute("membersCanPostAsTheGroup")] public virtual string MembersCanPostAsTheGroup { get; set; } /// <summary>Default message display font. Possible values are: DEFAULT_FONT FIXED_WIDTH_FONT</summary> [Newtonsoft.Json.JsonPropertyAttribute("messageDisplayFont")] public virtual string MessageDisplayFont { get; set; } /// <summary>Moderation level for messages. Possible values are: MODERATE_ALL_MESSAGES MODERATE_NON_MEMBERS /// MODERATE_NEW_MEMBERS MODERATE_NONE</summary> [Newtonsoft.Json.JsonPropertyAttribute("messageModerationLevel")] public virtual string MessageModerationLevel { get; set; } /// <summary>Name of the Group</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>Primary language for the group.</summary> [Newtonsoft.Json.JsonPropertyAttribute("primaryLanguage")] public virtual string PrimaryLanguage { get; set; } /// <summary>Whome should the default reply to a message go to. Possible values are: REPLY_TO_CUSTOM /// REPLY_TO_SENDER REPLY_TO_LIST REPLY_TO_OWNER REPLY_TO_IGNORE REPLY_TO_MANAGERS</summary> [Newtonsoft.Json.JsonPropertyAttribute("replyTo")] public virtual string ReplyTo { get; set; } /// <summary>Should the member be notified if his message is denied by owner.</summary> [Newtonsoft.Json.JsonPropertyAttribute("sendMessageDenyNotification")] public virtual string SendMessageDenyNotification { get; set; } /// <summary>Is the group listed in groups directory</summary> [Newtonsoft.Json.JsonPropertyAttribute("showInGroupDirectory")] public virtual string ShowInGroupDirectory { get; set; } /// <summary>Moderation level for messages detected as spam. Possible values are: ALLOW MODERATE /// SILENTLY_MODERATE REJECT</summary> [Newtonsoft.Json.JsonPropertyAttribute("spamModerationLevel")] public virtual string SpamModerationLevel { get; set; } /// <summary>Permissions to add members. Possible values are: ALL_MANAGERS_CAN_ADD ALL_MEMBERS_CAN_ADD /// NONE_CAN_ADD</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanAdd")] public virtual string WhoCanAdd { get; set; } /// <summary>Permission to contact owner of the group via web UI. Possible values are: ANYONE_CAN_CONTACT /// ALL_IN_DOMAIN_CAN_CONTACT ALL_MEMBERS_CAN_CONTACT ALL_MANAGERS_CAN_CONTACT</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanContactOwner")] public virtual string WhoCanContactOwner { get; set; } /// <summary>Permissions to invite members. Possible values are: ALL_MEMBERS_CAN_INVITE ALL_MANAGERS_CAN_INVITE /// NONE_CAN_INVITE</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanInvite")] public virtual string WhoCanInvite { get; set; } /// <summary>Permissions to join the group. Possible values are: ANYONE_CAN_JOIN ALL_IN_DOMAIN_CAN_JOIN /// INVITED_CAN_JOIN CAN_REQUEST_TO_JOIN</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanJoin")] public virtual string WhoCanJoin { get; set; } /// <summary>Permission to leave the group. Possible values are: ALL_MANAGERS_CAN_LEAVE ALL_MEMBERS_CAN_LEAVE /// NONE_CAN_LEAVE</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanLeaveGroup")] public virtual string WhoCanLeaveGroup { get; set; } /// <summary>Permissions to post messages to the group. Possible values are: NONE_CAN_POST ALL_MANAGERS_CAN_POST /// ALL_MEMBERS_CAN_POST ALL_IN_DOMAIN_CAN_POST ANYONE_CAN_POST</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanPostMessage")] public virtual string WhoCanPostMessage { get; set; } /// <summary>Permissions to view group. Possible values are: ANYONE_CAN_VIEW ALL_IN_DOMAIN_CAN_VIEW /// ALL_MEMBERS_CAN_VIEW ALL_MANAGERS_CAN_VIEW</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanViewGroup")] public virtual string WhoCanViewGroup { get; set; } /// <summary>Permissions to view membership. Possible values are: ALL_IN_DOMAIN_CAN_VIEW ALL_MEMBERS_CAN_VIEW /// ALL_MANAGERS_CAN_VIEW</summary> [Newtonsoft.Json.JsonPropertyAttribute("whoCanViewMembership")] public virtual string WhoCanViewMembership { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Markup; using DevExpress.Mvvm; using DevExpress.Mvvm.UI; using System.Windows; using System.Windows.Media; using System.Windows.Shell; using System.Windows.Data; using System.Collections.ObjectModel; using DevExpress.Mvvm.UI.Interactivity; using System.Windows.Controls; using DevExpress.Mvvm.Native; using DevExpress.Mvvm.UI.Native; namespace DevExpress.Mvvm.UI { [TargetType(typeof(UserControl))] [TargetType(typeof(Window))] [ContentProperty("ThumbButtonInfos")] public class TaskbarButtonService : WindowAwareServiceBase, ITaskbarButtonService { #region Dependency Properties public static readonly DependencyProperty ProgressStateProperty = DependencyProperty.Register("ProgressState", typeof(TaskbarItemProgressState), typeof(TaskbarButtonService), new FrameworkPropertyMetadata(TaskbarItemProgressState.None, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => ((TaskbarButtonService)d).OnProgressStateChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty ItemInfoProgressStateProperty = DependencyProperty.Register("ItemInfoProgressState", typeof(TaskbarItemProgressState), typeof(TaskbarButtonService), new PropertyMetadata(TaskbarItemProgressState.None, (d, e) => ((TaskbarButtonService)d).OnItemInfoProgressStateChanged(e))); public static readonly DependencyProperty ProgressValueProperty = DependencyProperty.Register("ProgressValue", typeof(double), typeof(TaskbarButtonService), new FrameworkPropertyMetadata(0.0, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => ((TaskbarButtonService)d).OnProgressValueChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty ItemInfoProgressValueProperty = DependencyProperty.Register("ItemInfoProgressValue", typeof(double), typeof(TaskbarButtonService), new PropertyMetadata(0.0, (d, e) => ((TaskbarButtonService)d).OnItemInfoProgressValueChanged(e))); public static readonly DependencyProperty OverlayIconProperty = DependencyProperty.Register("OverlayIcon", typeof(ImageSource), typeof(TaskbarButtonService), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => ((TaskbarButtonService)d).OnOverlayIconChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty ItemInfoOverlayIconProperty = DependencyProperty.Register("ItemInfoOverlayIcon", typeof(ImageSource), typeof(TaskbarButtonService), new PropertyMetadata(null, (d, e) => ((TaskbarButtonService)d).OnItemInfoOverlayIconChanged(e))); public static readonly DependencyProperty DescriptionProperty = DependencyProperty.Register("Description", typeof(string), typeof(TaskbarButtonService), new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => ((TaskbarButtonService)d).OnDescriptionChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty ItemInfoDescriptionProperty = DependencyProperty.Register("ItemInfoDescription", typeof(string), typeof(TaskbarButtonService), new PropertyMetadata("", (d, e) => ((TaskbarButtonService)d).OnItemInfoDescriptionChanged(e))); public static readonly DependencyProperty ThumbButtonInfosProperty = DependencyProperty.Register("ThumbButtonInfos", typeof(TaskbarThumbButtonInfoCollection), typeof(TaskbarButtonService), new PropertyMetadata(null, (d, e) => ((TaskbarButtonService)d).OnThumbButtonInfosChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty ItemInfoThumbButtonInfosProperty = DependencyProperty.Register("ItemInfoThumbButtonInfos", typeof(ThumbButtonInfoCollection), typeof(TaskbarButtonService), new PropertyMetadata(null, (d, e) => ((TaskbarButtonService)d).OnItemInfoThumbButtonInfosChanged(e))); public static readonly DependencyProperty ThumbnailClipMarginProperty = DependencyProperty.Register("ThumbnailClipMargin", typeof(Thickness), typeof(TaskbarButtonService), new FrameworkPropertyMetadata(new Thickness(), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, (d, e) => ((TaskbarButtonService)d).OnThumbnailClipMarginChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty ItemInfoThumbnailClipMarginProperty = DependencyProperty.Register("ItemInfoThumbnailClipMargin", typeof(Thickness), typeof(TaskbarButtonService), new PropertyMetadata(new Thickness(), (d, e) => ((TaskbarButtonService)d).OnItemInfoThumbnailClipMarginChanged(e))); [IgnoreDependencyPropertiesConsistencyCheckerAttribute] static readonly DependencyProperty WindowItemInfoProperty = DependencyProperty.Register("WindowItemInfo", typeof(TaskbarItemInfo), typeof(TaskbarButtonService), new PropertyMetadata(null, (d, e) => ((TaskbarButtonService)d).OnWindowItemInfoChanged(e))); public static readonly DependencyProperty ThumbnailClipMarginCallbackProperty = DependencyProperty.Register("ThumbnailClipMarginCallback", typeof(Func<Size, Thickness>), typeof(TaskbarButtonService), new PropertyMetadata(null, (d, e) => ((TaskbarButtonService)d).OnThumbnailClipMarginCallbackChanged(e))); [IgnoreDependencyPropertiesConsistencyChecker] internal static readonly DependencyProperty InternalItemsProperty = DependencyProperty.RegisterAttached("InternalItems", typeof(FreezableCollection<TaskbarThumbButtonInfo>), typeof(TaskbarButtonService), new PropertyMetadata(null)); internal static FreezableCollection<TaskbarThumbButtonInfo> GetInternalItems(TaskbarButtonService obj) { return (FreezableCollection<TaskbarThumbButtonInfo>)obj.GetValue(InternalItemsProperty); } internal static void SetInternalItems(TaskbarButtonService obj, FreezableCollection<TaskbarThumbButtonInfo> value) { obj.SetValue(InternalItemsProperty, value); } #endregion TaskbarItemInfo itemInfo; public TaskbarButtonService() { SetInternalItems(this, new FreezableCollection<TaskbarThumbButtonInfo>()); ItemInfo = new TaskbarItemInfo(); } public TaskbarItemProgressState ProgressState { get { return (TaskbarItemProgressState)GetValue(ProgressStateProperty); } set { SetValue(ProgressStateProperty, value); } } public double ProgressValue { get { return (double)GetValue(ProgressValueProperty); } set { SetValue(ProgressValueProperty, value); } } public ImageSource OverlayIcon { get { return (ImageSource)GetValue(OverlayIconProperty); } set { SetValue(OverlayIconProperty, value); } } public string Description { get { return (string)GetValue(DescriptionProperty); } set { SetValue(DescriptionProperty, value); } } public TaskbarThumbButtonInfoCollection ThumbButtonInfos { get { return (TaskbarThumbButtonInfoCollection)GetValue(ThumbButtonInfosProperty); } set { SetValue(ThumbButtonInfosProperty, value); } } public Thickness ThumbnailClipMargin { get { return (Thickness)GetValue(ThumbnailClipMarginProperty); } set { SetValue(ThumbnailClipMarginProperty, value); } } public Func<Size, Thickness> ThumbnailClipMarginCallback { get { return (Func<Size, Thickness>)GetValue(ThumbnailClipMarginCallbackProperty); } set { SetValue(ThumbnailClipMarginCallbackProperty, value); } } public void UpdateThumbnailClipMargin() { if(ActualWindow != null && ThumbnailClipMarginCallback != null) ThumbnailClipMargin = ThumbnailClipMarginCallback(new Size(ActualWindow.Width, ActualWindow.Height)); } protected override void OnAttached() { base.OnAttached(); UpdateInternalItems(); } protected override void OnDetaching() { GetInternalItems(this).Clear(); base.OnDetaching(); } protected override Freezable CreateInstanceCore() { return this; } protected virtual void OnProgressStateChanged(DependencyPropertyChangedEventArgs e) { ItemInfo.ProgressState = (TaskbarItemProgressState)e.NewValue; } protected virtual void OnProgressValueChanged(DependencyPropertyChangedEventArgs e) { double newValue = (double)e.NewValue; if(Math.Abs(ItemInfo.ProgressValue - newValue) > Double.Epsilon) ItemInfo.ProgressValue = newValue; } protected virtual void OnOverlayIconChanged(DependencyPropertyChangedEventArgs e) { ItemInfo.Overlay = (ImageSource)e.NewValue; } protected virtual void OnDescriptionChanged(DependencyPropertyChangedEventArgs e) { ItemInfo.Description = (string)e.NewValue; } protected virtual void OnThumbnailClipMarginChanged(DependencyPropertyChangedEventArgs e) { ItemInfo.ThumbnailClipMargin = (Thickness)e.NewValue; } protected virtual void OnThumbnailClipMarginCallbackChanged(DependencyPropertyChangedEventArgs e) { UpdateThumbnailClipMargin(); } protected virtual void OnWindowSizeChanged(object sender, SizeChangedEventArgs e) { UpdateThumbnailClipMargin(); } TaskbarItemInfo ItemInfo { get { return itemInfo; } set { if(itemInfo == value) return; itemInfo = value; BindingOperations.SetBinding(this, ItemInfoProgressStateProperty, new Binding("ProgressState") { Source = itemInfo, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); BindingOperations.SetBinding(this, ItemInfoProgressValueProperty, new Binding("ProgressValue") { Source = itemInfo, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); BindingOperations.SetBinding(this, ItemInfoOverlayIconProperty, new Binding("Overlay") { Source = itemInfo, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); BindingOperations.SetBinding(this, ItemInfoDescriptionProperty, new Binding("Description") { Source = itemInfo, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); BindingOperations.SetBinding(this, ItemInfoThumbnailClipMarginProperty, new Binding("ThumbnailClipMargin") { Source = itemInfo, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); BindingOperations.SetBinding(this, ItemInfoThumbButtonInfosProperty, new Binding("ThumbButtonInfos") { Source = itemInfo, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); } } void OnItemInfoProgressStateChanged(DependencyPropertyChangedEventArgs e) { ProgressState = (TaskbarItemProgressState)e.NewValue; } void OnItemInfoProgressValueChanged(DependencyPropertyChangedEventArgs e) { double newValue = (double)e.NewValue; if(Math.Abs(ProgressValue - newValue) > Double.Epsilon) ProgressValue = (double)e.NewValue; } void OnItemInfoOverlayIconChanged(DependencyPropertyChangedEventArgs e) { OverlayIcon = (ImageSource)e.NewValue; } void OnItemInfoDescriptionChanged(DependencyPropertyChangedEventArgs e) { Description = (string)e.NewValue; } protected virtual void OnThumbButtonInfosChanged(DependencyPropertyChangedEventArgs e) { TaskbarThumbButtonInfoCollection collection = (TaskbarThumbButtonInfoCollection)e.NewValue; ItemInfo.ThumbButtonInfos = collection.InternalCollection; UpdateInternalItems(); } bool lockUpdateInternalItems; void UpdateInternalItems() { if(lockUpdateInternalItems) return; if(!ShouldUpdateInternalItems()) return; try { lockUpdateInternalItems = true; UpdateInternalItemsCore(); } finally { lockUpdateInternalItems = false; } } internal virtual void UpdateInternalItemsCore() { GetInternalItems(this).Clear(); foreach(TaskbarThumbButtonInfo item in ThumbButtonInfos) GetInternalItems(this).Add(item); } bool ShouldUpdateInternalItems() { if(!IsAttached) return false; TaskbarThumbButtonInfoCollection collection = ThumbButtonInfos; FreezableCollection<TaskbarThumbButtonInfo> collection2 = GetInternalItems(this); if(collection.Count != collection2.Count) return true; for(int i = 0; i < collection.Count; i++) { var item1 = collection[i]; var item2 = collection2[i]; if(item1 != item2) return true; } return false; } void OnItemInfoThumbButtonInfosChanged(DependencyPropertyChangedEventArgs e) { ThumbButtonInfos = new TaskbarThumbButtonInfoCollection((ThumbButtonInfoCollection)e.NewValue); } void OnItemInfoThumbnailClipMarginChanged(DependencyPropertyChangedEventArgs e) { ThumbnailClipMargin = (Thickness)e.NewValue; } protected override void OnActualWindowChanged(Window oldWindow) { if(oldWindow != null) oldWindow.SizeChanged -= OnWindowSizeChanged; Window window = ActualWindow; if(window == null) { BindingOperations.ClearBinding(this, WindowItemInfoProperty); ItemInfo = new TaskbarItemInfo(); return; } if(window.TaskbarItemInfo == null) { window.TaskbarItemInfo = ItemInfo; } else { window.TaskbarItemInfo.ProgressState = ItemInfo.ProgressState; window.TaskbarItemInfo.ProgressValue = ItemInfo.ProgressValue; window.TaskbarItemInfo.Description = ItemInfo.Description; window.TaskbarItemInfo.Overlay = ItemInfo.Overlay; window.TaskbarItemInfo.ThumbButtonInfos = ItemInfo.ThumbButtonInfos; window.TaskbarItemInfo.ThumbnailClipMargin = ItemInfo.ThumbnailClipMargin; ItemInfo = window.TaskbarItemInfo; } BindingOperations.SetBinding(this, WindowItemInfoProperty, new Binding("TaskbarItemInfo") { Source = window, Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); window.SizeChanged -= OnWindowSizeChanged; window.SizeChanged += OnWindowSizeChanged; OnWindowSizeChanged(window, null); } void OnWindowItemInfoChanged(DependencyPropertyChangedEventArgs e) { if(ActualWindow == null) return; TaskbarItemInfo itemInfo = (TaskbarItemInfo)e.NewValue; if(itemInfo == null) { itemInfo = new TaskbarItemInfo(); ActualWindow.TaskbarItemInfo = itemInfo; } ItemInfo = itemInfo; } IList<TaskbarThumbButtonInfo> ITaskbarButtonService.ThumbButtonInfos { get { return ThumbButtonInfos; } } } }
/* * SoapDuration.cs - Implementation of the * "System.Runtime.Remoting.Metadata.W3cXsd2001.SoapDuration" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Runtime.Remoting.Metadata.W3cXsd2001 { #if CONFIG_SERIALIZATION using System.Text; // This class processes durations in ISO/XSD notation: // // [-]PxxxxYxxMxxDTxxHxxMxxS // [-]PxxxxYxxMxxDTxxHxxMxx.xxxxxxxS public sealed class SoapDuration { // Get the schema type for this class. public static String XsdType { get { return "duration"; } } // Parse a value into a TimeSpan instance. public static TimeSpan Parse(String value) { int sign; int posn; // Bail out early if no value supplied. if(value == null) { return TimeSpan.Zero; } else if(value == String.Empty) { return TimeSpan.Zero; } // Process the sign. if(value[0] == '-') { sign = -1; posn = 1; } else { sign = 0; posn = 0; } // Initialize the field values. int years = 0; int months = 0; int days = 0; int hours = 0; int minutes = 0; int seconds = 0; int fractions = 0; // Process the fields within the value. char ch; int val = 0; int numDigits = 0; bool withinTime = false; bool withinFractions = false; while(posn < value.Length) { ch = value[posn++]; if(ch >= '0' && ch <= '9') { val = val * 10 + (int)(ch - '0'); ++numDigits; if(numDigits >= 9) { throw new RemotingException (_("Arg_InvalidSoapValue")); } } else { switch(ch) { case 'P': case 'Z': break; case 'T': withinTime = true; break; case 'Y': years = val; break; case 'M': { if(withinTime) { minutes = val; } else { months = val; } } break; case 'D': days = val; break; case 'H': hours = val; break; case '.': { seconds = val; withinFractions = true; } break; case 'S': { if(withinFractions) { while(numDigits < 7) { val *= 10; } while(numDigits > 7) { val /= 10; } fractions = val; } else { seconds = val; } } break; default: { throw new RemotingException (_("Arg_InvalidSoapValue")); } // Not reached. } val = 0; numDigits = 0; } } // Build the final value and return. long ticks = years * (360 * TimeSpan.TicksPerDay) + months * (30 * TimeSpan.TicksPerDay) + days * TimeSpan.TicksPerDay + hours * TimeSpan.TicksPerHour + minutes * TimeSpan.TicksPerHour + seconds * TimeSpan.TicksPerSecond + fractions; return new TimeSpan(sign * ticks); } // Convert a time span into a string. public static String ToString(TimeSpan value) { StringBuilder builder = new StringBuilder(32); // Process the duration's sign. long ticks = value.Ticks; if(ticks < 0) { builder.Append('-'); ticks = -ticks; } // Calculate the years and months, using a standard // month length of 30 and a year length of 360. long days = ticks / TimeSpan.TicksPerDay; int years = (int)(days / 360); days -= years * 360L; int months = (int)(days / 30); days -= months * 30L; // Output the date portion. builder.Append('P'); builder.Append(years); builder.Append('Y'); builder.Append(months); builder.Append('M'); builder.Append(days); builder.Append('D'); // Output the time portion. ticks %= TimeSpan.TicksPerDay; builder.Append('T'); builder.Append(ticks / TimeSpan.TicksPerHour); builder.Append('H'); ticks %= TimeSpan.TicksPerHour; builder.Append(ticks / TimeSpan.TicksPerMinute); builder.Append('M'); ticks %= TimeSpan.TicksPerMinute; builder.Append(ticks / TimeSpan.TicksPerSecond); ticks %= TimeSpan.TicksPerSecond; if(ticks != 0) { builder.Append('.'); builder.Append(String.Format("{0:D7}", ticks)); } builder.Append('S'); // Return the final string. return builder.ToString(); } }; // class SoapDuration #endif // CONFIG_SERIALIZATION }; // namespace System.Runtime.Remoting.Metadata.W3cXsd2001
// 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.Numerics; using System.Security.Cryptography.Asn1; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Tests.Asn1 { public class PushPopSetOf : Asn1WriterTests { [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PopNewWriter(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { Assert.Throws<InvalidOperationException>( () => writer.PopSetOf()); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PopNewWriter_CustomTag(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { Assert.Throws<InvalidOperationException>( () => writer.PopSetOf(new Asn1Tag(TagClass.ContextSpecific, (int)ruleSet, true))); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PopBalancedWriter(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(); writer.PopSetOf(); Assert.Throws<InvalidOperationException>( () => writer.PopSetOf()); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PopBalancedWriter_CustomTag(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(); writer.PopSetOf(); Assert.Throws<InvalidOperationException>( () => writer.PopSetOf(new Asn1Tag(TagClass.ContextSpecific, (int)ruleSet, true))); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushCustom_PopStandard(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, (int)ruleSet, true)); Assert.Throws<InvalidOperationException>( () => writer.PopSetOf()); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushStandard_PopCustom(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(); Assert.Throws<InvalidOperationException>( () => writer.PopSetOf(new Asn1Tag(TagClass.ContextSpecific, (int)ruleSet, true))); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushPrimitive_PopStandard(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(new Asn1Tag(UniversalTagNumber.SetOf)); writer.PopSetOf(); if (ruleSet == PublicEncodingRules.CER) { Verify(writer, "31800000"); } else { Verify(writer, "3100"); } } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushCustomPrimitive_PopConstructed(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(new Asn1Tag(TagClass.Private, 5)); writer.PopSetOf(new Asn1Tag(TagClass.Private, 5, true)); if (ruleSet == PublicEncodingRules.CER) { Verify(writer, "E5800000"); } else { Verify(writer, "E500"); } } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushStandard_PopPrimitive(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(); writer.PopSetOf(new Asn1Tag(UniversalTagNumber.SetOf)); if (ruleSet == PublicEncodingRules.CER) { Verify(writer, "31800000"); } else { Verify(writer, "3100"); } } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushCustomConstructed_PopPrimitive(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { writer.PushSetOf(new Asn1Tag(TagClass.Private, (int)ruleSet, true)); writer.PopSetOf(new Asn1Tag(TagClass.Private, (int)ruleSet)); byte tag = (byte)((int)ruleSet | 0b1110_0000); string tagHex = tag.ToString("X2"); string rest = ruleSet == PublicEncodingRules.CER ? "800000" : "00"; Verify(writer, tagHex + rest); } } [Fact] public static void BER_WritesDefinite_Empty() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER)) { writer.PushSetOf(); writer.PopSetOf(); Verify(writer, "3100"); } } [Fact] public static void CER_WritesIndefinite_Empty() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.CER)) { writer.PushSetOf(); writer.PopSetOf(); Verify(writer, "31800000"); } } [Fact] public static void DER_WritesDefinite_CustomTag_Empty() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { writer.PushSetOf(); writer.PopSetOf(); Verify(writer, "3100"); } } [Fact] public static void BER_WritesDefinite_CustomTag__Empty() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER)) { Asn1Tag tag = new Asn1Tag(TagClass.Private, 15, true); writer.PushSetOf(tag); writer.PopSetOf(tag); Verify(writer, "EF00"); } } [Fact] public static void CER_WritesIndefinite_CustomTag__Empty() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.CER)) { Asn1Tag tag = new Asn1Tag(TagClass.Application, 91, true); writer.PushSetOf(tag); writer.PopSetOf(tag); Verify(writer, "7F5B800000"); } } [Fact] public static void DER_WritesDefinite_CustomTag__Empty() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 30, true); writer.PushSetOf(tag); writer.PopSetOf(tag); Verify(writer, "BE00"); } } private static void TestNested(AsnWriter writer, Asn1Tag alt, string expectedHex) { // Written in pre-sorted order, since sorting is a different test. writer.PushSetOf(); { writer.PushSetOf(); { writer.PushSetOf(alt); { writer.PushSetOf(); writer.PopSetOf(); } writer.PopSetOf(alt); } writer.PopSetOf(); writer.PushSetOf(alt); writer.PopSetOf(alt); } writer.PopSetOf(); Verify(writer, expectedHex); } [Fact] public static void BER_Nested() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.BER)) { Asn1Tag alt = new Asn1Tag(TagClass.Private, 127, true); TestNested(writer, alt, "310A3105FF7F023100FF7F00"); } } [Fact] public static void CER_Nested() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.CER)) { Asn1Tag alt = new Asn1Tag(TagClass.ContextSpecific, 12, true); TestNested(writer, alt, "31803180AC803180000000000000AC8000000000"); } } [Fact] public static void DER_Nested() { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { Asn1Tag alt = new Asn1Tag(TagClass.Application, 5, true); TestNested(writer, alt, "31083104650231006500"); } } private static void SimpleContentShiftCore(AsnWriter writer, string expectedHex) { writer.PushSetOf(); // F00DF00D...F00DF00D byte[] contentBytes = new byte[126]; for (int i = 0; i < contentBytes.Length; i += 2) { contentBytes[i] = 0xF0; contentBytes[i + 1] = 0x0D; } writer.WriteOctetString(contentBytes); writer.PopSetOf(); Verify(writer, expectedHex); } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.DER)] public static void SimpleContentShift(PublicEncodingRules ruleSet) { const string ExpectedHex = "318180" + "047E" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D"; using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { SimpleContentShiftCore(writer, ExpectedHex); } } [Fact] public static void SimpleContentShift_CER() { const string ExpectedHex = "3180" + "047E" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "F00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00DF00D" + "0000"; using (AsnWriter writer = new AsnWriter(AsnEncodingRules.CER)) { SimpleContentShiftCore(writer, ExpectedHex); } } [Theory] [InlineData(false)] [InlineData(true)] public static void Push_After_Dispose(bool empty) { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { if (!empty) { writer.WriteNull(); } writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.PushSetOf()); } } [Theory] [InlineData(false)] [InlineData(true)] public static void Push_Custom_After_Dispose(bool empty) { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { if (!empty) { writer.WriteNull(); } writer.Dispose(); Assert.Throws<ObjectDisposedException>( () => writer.PushSetOf(new Asn1Tag(TagClass.Application, 2))); } } [Theory] [InlineData(false)] [InlineData(true)] public static void Pop_After_Dispose(bool empty) { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { if (!empty) { writer.WriteNull(); } writer.Dispose(); Assert.Throws<ObjectDisposedException>(() => writer.PopSetOf()); } } [Theory] [InlineData(false)] [InlineData(true)] public static void Pop_Custom_After_Dispose(bool empty) { using (AsnWriter writer = new AsnWriter(AsnEncodingRules.DER)) { if (!empty) { writer.WriteNull(); } writer.Dispose(); Assert.Throws<ObjectDisposedException>( () => writer.PopSetOf(new Asn1Tag(TagClass.Application, 2))); } } private static void ValidateDataSorting(AsnEncodingRules ruleSet, string expectedHex) { using (AsnWriter writer = new AsnWriter(ruleSet)) { writer.PushSetOf(); // 02 01 FF writer.WriteInteger(-1); // 02 01 00 writer.WriteInteger(0); // 02 02 00 FF writer.WriteInteger(255); // 01 01 FF writer.WriteBoolean(true); // 45 01 00 writer.WriteBoolean(new Asn1Tag(TagClass.Application, 5), false); // 02 01 7F writer.WriteInteger(127); // 02 01 80 writer.WriteInteger(sbyte.MinValue); // 02 02 00 FE writer.WriteInteger(254); // 02 01 00 writer.WriteInteger(0); writer.PopSetOf(); // The correct sort order (CER, DER) is // Universal Boolean: true // Universal Integer: 0 // Universal Integer: 0 // Universal Integer: 127 // Universal Integer: -128 // Universal Integer: -1 // Universal Integer: 254 // Universal Integer: 255 // Application 5 (Boolean): false // This test would be // // GrabBag ::= SET OF GrabBagItem // // GrabBagItem ::= CHOICE ( // value INTEGER // bool BOOLEAN // grr [APPLICATION 5] IMPLICIT BOOLEAN // ) Verify(writer, expectedHex); } } [Fact] public static void BER_DoesNotSort() { const string ExpectedHex = "311D" + "0201FF" + "020100" + "020200FF" + "0101FF" + "450100" + "02017F" + "020180" + "020200FE" + "020100"; ValidateDataSorting(AsnEncodingRules.BER, ExpectedHex); } [Fact] public static void CER_SortsData() { const string ExpectedHex = "3180" + "0101FF" + "020100" + "020100" + "02017F" + "020180" + "0201FF" + "020200FE" + "020200FF" + "450100" + "0000"; ValidateDataSorting(AsnEncodingRules.CER, ExpectedHex); } [Fact] public static void DER_SortsData() { const string ExpectedHex = "311D" + "0101FF" + "020100" + "020100" + "02017F" + "020180" + "0201FF" + "020200FE" + "020200FF" + "450100"; ValidateDataSorting(AsnEncodingRules.DER, ExpectedHex); } [Theory] [InlineData(PublicEncodingRules.BER, false)] [InlineData(PublicEncodingRules.CER, false)] [InlineData(PublicEncodingRules.DER, false)] [InlineData(PublicEncodingRules.BER, true)] [InlineData(PublicEncodingRules.CER, true)] [InlineData(PublicEncodingRules.DER, true)] public static void CannotEncodeWhileUnbalanced(PublicEncodingRules ruleSet, bool customTag) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { if (customTag) { writer.PushSetOf(new Asn1Tag(TagClass.ContextSpecific, (int)ruleSet, true)); } else { writer.PushSetOf(); } int written = -5; Assert.Throws<InvalidOperationException>(() => writer.Encode()); Assert.Throws<InvalidOperationException>(() => writer.TryEncode(Span<byte>.Empty, out written)); Assert.Equal(-5, written); byte[] buf = new byte[10]; Assert.Throws<InvalidOperationException>(() => writer.TryEncode(buf, out written)); Assert.Equal(-5, written); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushSetOf_EndOfContents(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { AssertExtensions.Throws<ArgumentException>( "tag", () => writer.PushSetOf(Asn1Tag.EndOfContents)); } } [Theory] [InlineData(PublicEncodingRules.BER)] [InlineData(PublicEncodingRules.CER)] [InlineData(PublicEncodingRules.DER)] public static void PushSequence_PopSetOf(PublicEncodingRules ruleSet) { using (AsnWriter writer = new AsnWriter((AsnEncodingRules)ruleSet)) { Asn1Tag tag = new Asn1Tag(TagClass.ContextSpecific, 3); writer.PushSequence(tag); Assert.Throws<InvalidOperationException>( () => writer.PopSetOf(tag)); } } } }
//----------------------------------------------------------------------- // <copyright file="Serialization.cs" company="Akka.NET Project"> // Copyright (C) 2009-2016 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Akka.Actor; using Akka.Util.Internal; namespace Akka.Serialization { public class Information { public Address Address { get; set; } public ActorSystem System { get; set; } } public class Serialization { [ThreadStatic] private static Information _currentTransportInformation; public static T SerializeWithTransport<T>(ActorSystem system, Address address, Func<T> action) { _currentTransportInformation = new Information() { System = system, Address = address }; var res = action(); _currentTransportInformation = null; return res; } private readonly Serializer _nullSerializer; private readonly Dictionary<Type, Serializer> _serializerMap = new Dictionary<Type, Serializer>(); private readonly Dictionary<int, Serializer> _serializers = new Dictionary<int, Serializer>(); public Serialization(ExtendedActorSystem system) { System = system; _nullSerializer = new NullSerializer(system); _serializers.Add(_nullSerializer.Identifier, _nullSerializer); var serializersConfig = system.Settings.Config.GetConfig("akka.actor.serializers").AsEnumerable().ToList(); var serializerBindingConfig = system.Settings.Config.GetConfig("akka.actor.serialization-bindings").AsEnumerable().ToList(); var namedSerializers = new Dictionary<string, Serializer>(); foreach (var kvp in serializersConfig) { var serializerTypeName = kvp.Value.GetString(); var serializerType = Type.GetType(serializerTypeName); if (serializerType == null) { system.Log.Warning("The type name for serializer '{0}' did not resolve to an actual Type: '{1}'", kvp.Key, serializerTypeName); continue; } var serializer = (Serializer)Activator.CreateInstance(serializerType, system); _serializers.Add(serializer.Identifier, serializer); namedSerializers.Add(kvp.Key, serializer); } foreach (var kvp in serializerBindingConfig) { var typename = kvp.Key; var serializerName = kvp.Value.GetString(); var messageType = Type.GetType(typename); if (messageType == null) { system.Log.Warning("The type name for message/serializer binding '{0}' did not resolve to an actual Type: '{1}'", serializerName, typename); continue; } var serializer = namedSerializers[serializerName]; if (serializer == null) { system.Log.Warning("Serialization binding to non existing serializer: '{0}'", serializerName); continue; } _serializerMap.Add(messageType, serializer); } } public ActorSystem System { get; private set; } public void AddSerializer(Serializer serializer) { _serializers.Add(serializer.Identifier, serializer); } public void AddSerializationMap(Type type, Serializer serializer) { _serializerMap.Add(type, serializer); } public object Deserialize(byte[] bytes, int serializerId, Type type) { Serializer serializer; if (!_serializers.TryGetValue(serializerId, out serializer)) throw new SerializationException( $"Cannot find serializer with id [{serializerId}]. The most probable reason" + " is that the configuration entry akka.actor.serializers is not in sync between the two systems."); return serializer.FromBinary(bytes, type); } public object Deserialize(byte[] bytes, int serializerId, string manifest) { Serializer serializer; if (!_serializers.TryGetValue(serializerId, out serializer)) throw new SerializationException( $"Cannot find serializer with id [{serializerId}]. The most probable reason" + " is that the configuration entry akka.actor.serializers is not in sync between the two systems."); if (serializer is SerializerWithStringManifest) return ((SerializerWithStringManifest)serializer).FromBinary(bytes, manifest); if (string.IsNullOrEmpty(manifest)) return serializer.FromBinary(bytes, null); Type type; try { type = Type.GetType(manifest); } catch { throw new SerializationException($"Cannot find manifest class [{manifest}] for serializer with id [{serializerId}]."); } return serializer.FromBinary(bytes, type); } public Serializer FindSerializerFor(object obj) { if (obj == null) return _nullSerializer; Type type = obj.GetType(); return FindSerializerForType(type); } //cache to eliminate lots of typeof operator calls private readonly Type _objectType = typeof(object); public Serializer FindSerializerForType(Type objectType) { Type type = objectType; //TODO: see if we can do a better job with proper type sorting here - most specific to least specific (object serializer goes last) foreach (var serializerType in _serializerMap) { //force deferral of the base "object" serializer until all other higher-level types have been evaluated if (serializerType.Key.IsAssignableFrom(type) && serializerType.Key != _objectType) return serializerType.Value; } //do a final check for the "object" serializer if (_serializerMap.ContainsKey(_objectType) && _objectType.IsAssignableFrom(type)) return _serializerMap[_objectType]; throw new Exception("Serializer not found for type " + objectType.Name); } public static string SerializedActorPath(IActorRef actorRef) { if (Equals(actorRef, ActorRefs.NoSender)) return String.Empty; var path = actorRef.Path; ExtendedActorSystem originalSystem = null; if (actorRef is ActorRefWithCell) { originalSystem = actorRef.AsInstanceOf<ActorRefWithCell>().Underlying.System.AsInstanceOf<ExtendedActorSystem>(); } if (_currentTransportInformation == null) { if (originalSystem == null) { var res = path.ToSerializationFormat(); return res; } else { var defaultAddress = originalSystem.Provider.DefaultAddress; var res = path.ToSerializationFormatWithAddress(defaultAddress); return res; } } //CurrentTransportInformation exists var system = _currentTransportInformation.System; var address = _currentTransportInformation.Address; if (originalSystem == null || originalSystem == system) { var res = path.ToSerializationFormatWithAddress(address); return res; } else { var provider = originalSystem.Provider; var res = path.ToSerializationFormatWithAddress(provider.GetExternalAddressFor(address).GetOrElse(provider.DefaultAddress)); return res; } } public Serializer GetSerializerById(int serializerId) { return _serializers[serializerId]; } } }
//! \file ArcAMI.cs //! \date Thu Jul 03 09:40:40 2014 //! \brief Muv-Luv Amaterasu Translation archive. // // Copyright (C) 2014 by morkt // // 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 System.Text; using System.Linq; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Globalization; using GameRes.Compression; using GameRes.Formats.Strings; using GameRes.Formats.Properties; namespace GameRes.Formats.Amaterasu { internal class AmiEntry : PackedEntry { public uint Id; private Lazy<string> m_ext; private Lazy<string> m_name; private Lazy<string> m_type; public override string Name { get { return m_name.Value; } set { m_name = new Lazy<string> (() => value); } } public override string Type { get { return m_type.Value; } set { m_type = new Lazy<string> (() => value); } } public AmiEntry (uint id, Func<string> ext_factory) { Id = id; m_ext = new Lazy<string> (ext_factory); m_name = new Lazy<string> (GetName); m_type = new Lazy<string> (GetEntryType); } private string GetName () { return string.Format ("{0:x8}.{1}", Id, m_ext.Value); } private string GetEntryType () { var ext = m_ext.Value; if ("grp" == ext) return "image"; if ("scr" == ext) return "script"; return ""; } } internal class AmiOptions : ResourceOptions { public bool UseBaseArchive; public string BaseArchive; } [Export(typeof(ArchiveFormat))] public class AmiOpener : ArchiveFormat { public override string Tag { get { return "AMI"; } } public override string Description { get { return Strings.arcStrings.AMIDescription; } } public override uint Signature { get { return 0x00494d41; } } public override bool IsHierarchic { get { return false; } } public override bool CanCreate { get { return true; } } public AmiOpener () { Extensions = new string[] { "ami", "amr" }; } public override ArcFile TryOpen (ArcView file) { int count = file.View.ReadInt32 (4); if (count <= 0) return null; uint base_offset = file.View.ReadUInt32 (8); long max_offset = file.MaxOffset; if (base_offset >= max_offset) return null; uint cur_offset = 16; var dir = new List<Entry> (count); for (int i = 0; i < count; ++i) { if (cur_offset+16 > base_offset) return null; uint id = file.View.ReadUInt32 (cur_offset); uint offset = file.View.ReadUInt32 (cur_offset+4); uint size = file.View.ReadUInt32 (cur_offset+8); uint packed_size = file.View.ReadUInt32 (cur_offset+12); var entry = new AmiEntry (id, () => { uint signature = file.View.ReadUInt32 (offset); if (0x00524353 == signature) return "scr"; else if (0 != packed_size || 0x00505247 == signature) return "grp"; else return "dat"; }); entry.Offset = offset; entry.UnpackedSize = size; entry.IsPacked = 0 != packed_size; entry.Size = entry.IsPacked ? packed_size : size; if (!entry.CheckPlacement (max_offset)) return null; dir.Add (entry); cur_offset += 16; } return new ArcFile (file, this, dir); } public override Stream OpenEntry (ArcFile arc, Entry entry) { var input = arc.File.CreateStream (entry.Offset, entry.Size); var packed_entry = entry as AmiEntry; if (null == packed_entry || !packed_entry.IsPacked) return input; else return new ZLibStream (input, CompressionMode.Decompress); } public override void Create (Stream output, IEnumerable<Entry> list, ResourceOptions options, EntryCallback callback) { ArcFile base_archive = null; var ami_options = GetOptions<AmiOptions> (options); if (null != ami_options && ami_options.UseBaseArchive && !string.IsNullOrEmpty (ami_options.BaseArchive)) { var base_file = new ArcView (ami_options.BaseArchive); try { if (base_file.View.ReadUInt32(0) == Signature) base_archive = TryOpen (base_file); if (null == base_archive) throw new InvalidFormatException (string.Format ("{0}: base archive could not be read", Path.GetFileName (ami_options.BaseArchive))); base_file = null; } finally { if (null != base_file) base_file.Dispose(); } } try { var file_table = new SortedDictionary<uint, PackedEntry>(); if (null != base_archive) { foreach (var entry in base_archive.Dir.Cast<AmiEntry>()) file_table[entry.Id] = entry; } int update_count = UpdateFileTable (file_table, list); if (0 == update_count) throw new InvalidFormatException (arcStrings.AMINoFiles); uint file_count = (uint)file_table.Count; if (null != callback) callback ((int)file_count+1, null, null); int callback_count = 0; long start_offset = output.Position; uint data_offset = file_count * 16 + 16; output.Seek (data_offset, SeekOrigin.Current); foreach (var entry in file_table) { if (null != callback) callback (callback_count++, entry.Value, arcStrings.MsgAddingFile); long current_offset = output.Position; if (current_offset > uint.MaxValue) throw new FileSizeException(); if (entry.Value is AmiEntry) CopyAmiEntry (base_archive, entry.Value, output); else entry.Value.Size = WriteAmiEntry (entry.Value, output); entry.Value.Offset = (uint)current_offset; } if (null != callback) callback (callback_count++, null, arcStrings.MsgWritingIndex); output.Position = start_offset; using (var header = new BinaryWriter (output, Encoding.ASCII, true)) { header.Write (Signature); header.Write (file_count); header.Write (data_offset); header.Write ((uint)0); foreach (var entry in file_table) { header.Write (entry.Key); header.Write ((uint)entry.Value.Offset); header.Write ((uint)entry.Value.UnpackedSize); header.Write ((uint)entry.Value.Size); } } } finally { if (null != base_archive) base_archive.Dispose(); } } int UpdateFileTable (IDictionary<uint, PackedEntry> table, IEnumerable<Entry> list) { int update_count = 0; foreach (var entry in list) { if (entry.Type != "image" && !entry.Name.EndsWith (".scr", StringComparison.InvariantCultureIgnoreCase)) continue; uint id; if (!uint.TryParse (Path.GetFileNameWithoutExtension (entry.Name), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out id)) continue; PackedEntry existing; if (table.TryGetValue (id, out existing) && !(existing is AmiEntry)) { var file_new = new FileInfo (entry.Name); if (!file_new.Exists) continue; var file_old = new FileInfo (existing.Name); if (file_new.LastWriteTime <= file_old.LastWriteTime) continue; } table[id] = new PackedEntry { Name = entry.Name, Type = entry.Type }; ++update_count; } return update_count; } void CopyAmiEntry (ArcFile base_archive, Entry entry, Stream output) { using (var input = base_archive.File.CreateStream (entry.Offset, entry.Size)) input.CopyTo (output); } uint WriteAmiEntry (PackedEntry entry, Stream output) { uint packed_size = 0; using (var input = File.OpenRead (entry.Name)) { long file_size = input.Length; if (file_size > uint.MaxValue) throw new FileSizeException(); entry.UnpackedSize = (uint)file_size; if ("image" == entry.Type) { packed_size = WriteImageEntry (entry, input, output); } else { input.CopyTo (output); } } return packed_size; } static Lazy<GrpFormat> s_grp_format = new Lazy<GrpFormat> (() => FormatCatalog.Instance.ImageFormats.OfType<GrpFormat>().FirstOrDefault()); uint WriteImageEntry (PackedEntry entry, Stream input, Stream output) { var grp = s_grp_format.Value; if (null == grp) // probably never happens throw new FileFormatException ("GRP image encoder not available"); bool is_grp = grp.Signature == FormatCatalog.ReadSignature (input); input.Position = 0; var start = output.Position; using (var zstream = new ZLibStream (output, CompressionMode.Compress, CompressionLevel.Level9, true)) { if (is_grp) { input.CopyTo (zstream); } else { var image = ImageFormat.Read (input); if (null == image) throw new InvalidFormatException (string.Format (arcStrings.MsgInvalidImageFormat, entry.Name)); grp.Write (zstream, image); entry.UnpackedSize = (uint)zstream.TotalIn; } } return (uint)(output.Position - start); } public override ResourceOptions GetDefaultOptions () { return new AmiOptions { UseBaseArchive = Settings.Default.AMIUseBaseArchive, BaseArchive = Settings.Default.AMIBaseArchive, }; } public override object GetCreationWidget () { return new GUI.CreateAMIWidget(); } } public class AmiScriptData : ScriptData { public uint Id; public uint Type; } [Export(typeof(ScriptFormat))] public class ScrFormat : ScriptFormat { public override string Tag { get { return "SCR"; } } public override string Description { get { return Strings.arcStrings.SCRDescription; } } public override uint Signature { get { return 0x00524353; } } public override ScriptData Read (string name, Stream stream) { if (Signature != FormatCatalog.ReadSignature (stream)) return null; uint script_id = Convert.ToUInt32 (name, 16); uint max_offset = (uint)Math.Min (stream.Length, 0xffffffff); using (var file = new BinaryReader (stream, Encodings.cp932, true)) { uint script_type = file.ReadUInt32(); var script = new AmiScriptData { Id = script_id, Type = script_type }; uint count = file.ReadUInt32(); for (uint i = 0; i < count; ++i) { uint offset = file.ReadUInt32(); if (offset >= max_offset) throw new InvalidFormatException ("Invalid offset in script data file"); int size = file.ReadInt32(); uint id = file.ReadUInt32(); var header_pos = file.BaseStream.Position; file.BaseStream.Position = offset; byte[] line = file.ReadBytes (size); if (line.Length != size) throw new InvalidFormatException ("Premature end of file"); string text = Encodings.cp932.GetString (line); script.TextLines.Add (new ScriptLine { Id = id, Text = text }); file.BaseStream.Position = header_pos; } return script; } } public string GetName (ScriptData script_data) { var script = script_data as AmiScriptData; if (null != script) return script.Id.ToString ("x8"); else return null; } struct IndexEntry { public uint offset, size, id; } public override void Write (Stream stream, ScriptData script_data) { var script = script_data as AmiScriptData; if (null == script) throw new ArgumentException ("Illegal ScriptData", "script_data"); using (var file = new BinaryWriter (stream, Encodings.cp932, true)) { file.Write (Signature); file.Write (script.Type); uint count = (uint)script.TextLines.Count; file.Write (count); var index_pos = file.BaseStream.Position; file.Seek ((int)count*12, SeekOrigin.Current); var index = new IndexEntry[count]; int i = 0; foreach (var line in script.TextLines) { var text = Encodings.cp932.GetBytes (line.Text); index[i].offset = (uint)file.BaseStream.Position; index[i].size = (uint)text.Length; index[i].id = line.Id; file.Write (text); file.Write ((byte)0); ++i; } var end_pos = file.BaseStream.Position; file.BaseStream.Position = index_pos; foreach (var entry in index) { file.Write (entry.offset); file.Write (entry.size); file.Write (entry.id); } file.BaseStream.Position = end_pos; } } } }
// 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 Xunit; namespace System.Collections.ArrayListTests { public class BinarySearchTests : IComparer { #region "Test Data - Keep the data close to tests so it can vary independently from other tests" static string[] strHeroes = { "Aquaman", "Atom", "Batman", "Black Canary", "Captain America", "Captain Atom", "Catwoman", "Cyborg", "Flash", "Green Arrow", "Green Lantern", "Hawkman", "Huntress", "Ironman", "Nightwing", "Robin", "SpiderMan", "Steel", "Superman", "Thor", "Wildcat", "Wonder Woman", }; static string[] strFindHeroes = { "Batman", "Superman", "SpiderMan", "Wonder Woman", "Green Lantern", "Flash", "Steel" }; #endregion [Fact] public void TestStandardArrayList() { // // Construct array list. // ArrayList list = new ArrayList(); // Add items to the lists. for (int ii = 0; ii < strHeroes.Length; ++ii) list.Add(strHeroes[ii]); // Verify items added to list. Assert.Equal(strHeroes.Length, list.Count); // // [] Use BinarySearch to find selected items. // // Search and verify selected items. for (int ii = 0; ii < strFindHeroes.Length; ++ii) { // Locate item. int ndx = list.BinarySearch(strFindHeroes[ii]); Assert.True(ndx >= 0); // Verify item. Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii])); } // Return Value; // The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number, // which is the bitwise complement of the index of the next element. list = new ArrayList(); for (int i = 0; i < 100; i++) list.Add(i); list.Sort(); Assert.Equal(100, ~list.BinarySearch(150)); //[]null - should return -1 Assert.Equal(-1, list.BinarySearch(null)); //[]we can add null as a value and then search it!!! list.Add(null); list.Sort(); Assert.Equal(0, list.BinarySearch(null)); //[]duplicate values, always return the first one list = new ArrayList(); for (int i = 0; i < 100; i++) list.Add(5); list.Sort(); //remember this is BinarySeearch Assert.Equal(49, list.BinarySearch(5)); } [Fact] public void TestArrayListWrappers() { // // Construct array list. // ArrayList arrList = new ArrayList(); // Add items to the lists. for (int ii = 0; ii < strHeroes.Length; ++ii) { arrList.Add(strHeroes[ii]); } // Verify items added to list. Assert.Equal(strHeroes.Length, arrList.Count); //Adapter, GetRange, Synchronized, ReadOnly returns a slightly different version of //BinarySearch, Following variable cotains each one of these types of array lists ArrayList[] arrayListTypes = { arrList, ArrayList.Adapter(arrList), ArrayList.FixedSize(arrList), arrList.GetRange(0, arrList.Count), ArrayList.ReadOnly(arrList), ArrayList.Synchronized(arrList)}; int ndx = 0; foreach (ArrayList arrayListType in arrayListTypes) { arrList = arrayListType; // // [] Use BinarySearch to find selected items. // // Search and verify selected items. for (int ii = 0; ii < strFindHeroes.Length; ++ii) { // Locate item. ndx = arrList.BinarySearch(0, arrList.Count, strFindHeroes[ii], this); Assert.True(ndx >= 0); // Verify item. Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii])); } // // [] Locate item in list using null comparer. // ndx = arrList.BinarySearch(0, arrList.Count, "Batman", null); Assert.Equal(2, ndx); // // [] Locate insertion index of new list item. // // Append the list. ndx = arrList.BinarySearch(0, arrList.Count, "Batgirl", this); Assert.Equal(2, ~ndx); // // [] Bogus Arguments // Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(-100, 1000, arrList.Count, this)); Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(-100, 1000, "Batman", this)); Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(-1, arrList.Count, "Batman", this)); Assert.Throws<ArgumentOutOfRangeException>(() => arrList.BinarySearch(0, -1, "Batman", this)); Assert.Throws<ArgumentException>(() => arrList.BinarySearch(1, arrList.Count, "Batman", this)); Assert.Throws<ArgumentException>(() => arrList.BinarySearch(3, arrList.Count - 2, "Batman", this)); } } [Fact] public void TestCustomComparer() { ArrayList list = null; list = new ArrayList(); // Add items to the lists. for (int ii = 0; ii < strHeroes.Length; ++ii) list.Add(strHeroes[ii]); // Verify items added to list. Assert.Equal(strHeroes.Length, list.Count); // // [] Use BinarySearch to find selected items. // // Search and verify selected items. for (int ii = 0; ii < strFindHeroes.Length; ++ii) { // Locate item. int ndx = list.BinarySearch(strFindHeroes[ii], new BinarySearchTests()); Assert.True(ndx < strHeroes.Length); // Verify item. Assert.Equal(0, strHeroes[ndx].CompareTo(strFindHeroes[ii])); } //Return Value; //The zero-based index of the value in the sorted ArrayList, if value is found; otherwise, a negative number, which is the //bitwise complement of the index of the next element. list = new ArrayList(); for (int i = 0; i < 100; i++) list.Add(i); list.Sort(); Assert.Equal(100, ~list.BinarySearch(150, new BinarySearchTests())); //[]null - should return -1 Assert.Equal(-1, list.BinarySearch(null, new BinarySearchTests())); //[]we can add null as a value and then search it!!! list.Add(null); list.Sort(); Assert.Equal(0, list.BinarySearch(null, new CompareWithNullEnabled())); //[]duplicate values, always return the first one list = new ArrayList(); for (int i = 0; i < 100; i++) list.Add(5); list.Sort(); //remember this is BinarySeearch Assert.Equal(49, list.BinarySearch(5, new BinarySearchTests())); //[]IC as null list = new ArrayList(); for (int i = 0; i < 100; i++) list.Add(5); list.Sort(); //remember this is BinarySeearch Assert.Equal(49, list.BinarySearch(5, null)); } public virtual int Compare(object x, object y) { if (x is string) { return ((string)x).CompareTo((string)y); } var comparer = new Comparer(System.Globalization.CultureInfo.InvariantCulture); if (x is int || y is string) { return comparer.Compare(x, y); } return -1; } } class CompareWithNullEnabled : IComparer { public int Compare(Object a, Object b) { if (a == b) return 0; if (a == null) return -1; if (b == null) return 1; IComparable ia = a as IComparable; if (ia != null) return ia.CompareTo(b); IComparable ib = b as IComparable; if (ib != null) return -ib.CompareTo(a); throw new ArgumentException("Wrong stuff"); } } }
using Cinemachine.Utility; using System; using System.Collections.Generic; using UnityEngine; namespace Cinemachine { /// <summary> /// This is a virtual camera "manager" that owns and manages a collection /// of child Virtual Cameras. These child vcams are mapped to individual states in /// an animation state machine, allowing you to associate specific vcams to specific /// animation states. When that state is active in the state machine, then the /// associated camera will be activated. /// /// You can define custom blends and transitions between child cameras. /// /// In order to use this behaviour, you must have an animated target (i.e. an object /// animated with a state machine) to drive the behaviour. /// </summary> [DocumentationSorting(13, DocumentationSortingAttribute.Level.UserRef)] [ExecuteInEditMode, DisallowMultipleComponent] [AddComponentMenu("Cinemachine/CinemachineStateDrivenCamera")] public class CinemachineStateDrivenCamera : CinemachineVirtualCameraBase { /// <summary>Default object for the camera children to look at (the aim target), if not specified in a child rig. May be empty</summary> [Tooltip("Default object for the camera children to look at (the aim target), if not specified in a child camera. May be empty if all of the children define targets of their own.")] [NoSaveDuringPlay] public Transform m_LookAt = null; /// <summary>Default object for the camera children wants to move with (the body target), if not specified in a child rig. May be empty</summary> [Tooltip("Default object for the camera children wants to move with (the body target), if not specified in a child camera. May be empty if all of the children define targets of their own.")] [NoSaveDuringPlay] public Transform m_Follow = null; /// <summary>When enabled, the current camera and blend will be indicated in the game window, for debugging</summary> [Tooltip("When enabled, the current child camera and blend will be indicated in the game window, for debugging")] public bool m_ShowDebugText = false; /// <summary>Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources.</summary> [Tooltip("Force all child cameras to be enabled. This is useful if animating them in Timeline, but consumes extra resources")] public bool m_EnableAllChildCameras; // This is just for the inspector editor. // Probably it can be implemented without this serialized property [HideInInspector][NoSaveDuringPlay] public CinemachineVirtualCameraBase[] m_ChildCameras = null; /// <summary>The state machine whose state changes will drive this camera's choice of active child</summary> [Tooltip("The state machine whose state changes will drive this camera's choice of active child")] public Animator m_AnimatedTarget; /// <summary>Which layer in the target FSM to observe</summary> [Tooltip("Which layer in the target state machine to observe")] public int m_LayerIndex; /// <summary>This represents a single instrunction to the StateDrivenCamera. It associates /// an state from the state machine with a child Virtual Camera, and also holds /// activation tuning parameters.</summary> [Serializable] public struct Instruction { [Tooltip("The full hash of the animation state")] public int m_FullHash; [Tooltip("The virtual camera to activate whrn the animation state becomes active")] public CinemachineVirtualCameraBase m_VirtualCamera; [Tooltip("How long to wait (in seconds) before activating the virtual camera. This filters out very short state durations")] public float m_ActivateAfter; [Tooltip("The minimum length of time (in seconds) to keep a virtual camera active")] public float m_MinDuration; }; [Tooltip("The set of instructions associating virtual cameras with states. These instructions are used to choose the live child at any given moment")] public Instruction[] m_Instructions; /// <summary> /// The blend which is used if you don't explicitly define a blend between two Virtual Camera children. /// </summary> [CinemachineBlendDefinitionProperty] [Tooltip("The blend which is used if you don't explicitly define a blend between two Virtual Camera children")] public CinemachineBlendDefinition m_DefaultBlend = new CinemachineBlendDefinition(CinemachineBlendDefinition.Style.EaseInOut, 0.5f); /// <summary> /// This is the asset which contains custom settings for specific child blends. /// </summary> [HideInInspector] [Tooltip("This is the asset which contains custom settings for specific child blends")] public CinemachineBlenderSettings m_CustomBlends = null; /// <summary>Internal API for the Inspector editor. This implements nested states.</summary> [Serializable] [DocumentationSorting(13.2f, DocumentationSortingAttribute.Level.Undoc)] public struct ParentHash { public int m_Hash; public int m_ParentHash; public ParentHash(int h, int p) { m_Hash = h; m_ParentHash = p; } } [HideInInspector][SerializeField] public ParentHash[] m_ParentHash = null; /// <summary>Get the current "best" child virtual camera, that would be chosen /// if the State Driven Camera were active.</summary> public ICinemachineCamera LiveChild { set; get; } /// <summary>Return the live child.</summary> public override ICinemachineCamera LiveChildOrSelf { get { return LiveChild; } } /// <summary>Check whether the vcam a live child of this camera.</summary> /// <param name="vcam">The Virtual Camera to check</param> /// <returns>True if the vcam is currently actively influencing the state of this vcam</returns> public override bool IsLiveChild(ICinemachineCamera vcam) { return vcam == LiveChild || (mActiveBlend != null && (vcam == mActiveBlend.CamA || vcam == mActiveBlend.CamB)); } /// <summary>The State of the current live child</summary> public override CameraState State { get { return m_State; } } /// <summary>Get the current LookAt target. Returns parent's LookAt if parent /// is non-null and no specific LookAt defined for this camera</summary> override public Transform LookAt { get { return ResolveLookAt(m_LookAt); } set { m_LookAt = value; } } /// <summary>Get the current Follow target. Returns parent's Follow if parent /// is non-null and no specific Follow defined for this camera</summary> override public Transform Follow { get { return ResolveFollow(m_Follow); } set { m_Follow = value; } } /// <summary>Remove a Pipeline stage hook callback. /// Make sure it is removed from all the children.</summary> /// <param name="d">The delegate to remove.</param> public override void RemovePostPipelineStageHook(OnPostPipelineStageDelegate d) { base.RemovePostPipelineStageHook(d); UpdateListOfChildren(); foreach (var vcam in m_ChildCameras) vcam.RemovePostPipelineStageHook(d); } /// <summary>Called by CinemachineCore at designated update time /// so the vcam can position itself and track its targets. This implementation /// updates all the children, chooses the best one, and implements any required blending.</summary> /// <param name="worldUp">Default world Up, set by the CinemachineBrain</param> /// <param name="deltaTime">Delta time for time-based effects (ignore if less than or equal to 0)</param> public override void UpdateCameraState(Vector3 worldUp, float deltaTime) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineStateDrivenCamera.UpdateCameraState"); if (!PreviousStateIsValid) deltaTime = -1; UpdateListOfChildren(); CinemachineVirtualCameraBase best = ChooseCurrentCamera(deltaTime); if (m_ChildCameras != null) { for (int i = 0; i < m_ChildCameras.Length; ++i) { CinemachineVirtualCameraBase vcam = m_ChildCameras[i]; if (vcam != null) { vcam.gameObject.SetActive(m_EnableAllChildCameras || vcam == best); if (vcam.VirtualCameraGameObject.activeInHierarchy) { vcam.AddPostPipelineStageHook(OnPostPipelineStage); CinemachineCore.Instance.UpdateVirtualCamera(vcam, worldUp, deltaTime); } } } } ICinemachineCamera previousCam = LiveChild; LiveChild = best; // Are we transitioning cameras? if (previousCam != null && LiveChild != null && previousCam != LiveChild) { // Create a blend (will be null if a cut) float duration = 0; AnimationCurve curve = LookupBlendCurve(previousCam, LiveChild, out duration); mActiveBlend = CreateBlend( previousCam, LiveChild, curve, duration, mActiveBlend, deltaTime); // Notify incoming camera of transition LiveChild.OnTransitionFromCamera(previousCam); // Generate Camera Activation event if live CinemachineCore.Instance.GenerateCameraActivationEvent(LiveChild); // If cutting, generate a camera cut event if live if (mActiveBlend == null) CinemachineCore.Instance.GenerateCameraCutEvent(LiveChild); } // Advance the current blend (if any) if (mActiveBlend != null) { mActiveBlend.TimeInBlend += (deltaTime >= 0) ? deltaTime : mActiveBlend.Duration; if (mActiveBlend.IsComplete) mActiveBlend = null; } if (mActiveBlend != null) { mActiveBlend.UpdateCameraState(worldUp, deltaTime); m_State = mActiveBlend.State; } else if (LiveChild != null) m_State = LiveChild.State; // Push the raw position back to the game object's transform, so it // moves along with the camera. Leave the orientation alone, because it // screws up camera dragging when there is a LookAt behaviour. if (Follow != null) transform.position = State.RawPosition; PreviousStateIsValid = true; //UnityEngine.Profiling.Profiler.EndSample(); } /// <summary>Makes sure the internal child cache is up to date</summary> protected override void OnEnable() { base.OnEnable(); InvalidateListOfChildren(); mActiveBlend = null; } /// <summary>Makes sure the internal child cache is up to date</summary> public void OnTransformChildrenChanged() { InvalidateListOfChildren(); } #if UNITY_EDITOR /// <summary>Displays the current active camera on the game screen, if requested</summary> protected override void OnGUI() { base.OnGUI(); if (!m_ShowDebugText) CinemachineGameWindowDebug.ReleaseScreenPos(this); else { // Show the active camera and blend ICinemachineCamera vcam = LiveChild; string text = "CM " + gameObject.name + ": "; if (mActiveBlend == null) text += (vcam != null) ? vcam.Name : "(none)"; else text += mActiveBlend.Description; Rect r = CinemachineGameWindowDebug.GetScreenPos(this, text, GUI.skin.box); GUI.Label(r, text, GUI.skin.box); } } #endif CameraState m_State = CameraState.Default; /// <summary>The list of child cameras. These are just the immediate children in the hierarchy.</summary> public CinemachineVirtualCameraBase[] ChildCameras { get { UpdateListOfChildren(); return m_ChildCameras; }} /// <summary>Is there a blend in progress?</summary> public bool IsBlending { get { return mActiveBlend != null; } } /// <summary>API for the inspector editor. Animation module does not have hashes /// for state parents, so we have to invent them in order to implement nested state /// handling</summary> public static string CreateFakeHashName(int parentHash, string stateName) { return parentHash.ToString() + "_" + stateName; } float mActivationTime = 0; Instruction mActiveInstruction; float mPendingActivationTime = 0; Instruction mPendingInstruction; private CinemachineBlend mActiveBlend = null; void InvalidateListOfChildren() { m_ChildCameras = null; LiveChild = null; } void UpdateListOfChildren() { if (m_ChildCameras != null && mInstructionDictionary != null && mStateParentLookup != null) return; List<CinemachineVirtualCameraBase> list = new List<CinemachineVirtualCameraBase>(); CinemachineVirtualCameraBase[] kids = GetComponentsInChildren<CinemachineVirtualCameraBase>(true); foreach (CinemachineVirtualCameraBase k in kids) if (k.transform.parent == transform) list.Add(k); m_ChildCameras = list.ToArray(); ValidateInstructions(); } private Dictionary<int, int> mInstructionDictionary; private Dictionary<int, int> mStateParentLookup; /// <summary>Internal API for the inspector editor.</summary> public void ValidateInstructions() { if (m_Instructions == null) m_Instructions = new Instruction[0]; mInstructionDictionary = new Dictionary<int, int>(); for (int i = 0; i < m_Instructions.Length; ++i) { if (m_Instructions[i].m_VirtualCamera != null && m_Instructions[i].m_VirtualCamera.transform.parent != transform) { m_Instructions[i].m_VirtualCamera = null; } mInstructionDictionary[m_Instructions[i].m_FullHash] = i; } // Create the parent lookup mStateParentLookup = new Dictionary<int, int>(); if (m_ParentHash != null) foreach (var i in m_ParentHash) mStateParentLookup[i.m_Hash] = i.m_ParentHash; // Zap the cached current instructions mActivationTime = mPendingActivationTime = 0; mActiveBlend = null; } private CinemachineVirtualCameraBase ChooseCurrentCamera(float deltaTime) { //UnityEngine.Profiling.Profiler.BeginSample("CinemachineStateDrivenCamera.ChooseCurrentCamera"); if (m_ChildCameras == null || m_ChildCameras.Length == 0) { mActivationTime = 0; //UnityEngine.Profiling.Profiler.EndSample(); return null; } CinemachineVirtualCameraBase defaultCam = m_ChildCameras[0]; if (m_AnimatedTarget == null || !m_AnimatedTarget.gameObject.activeSelf || m_LayerIndex < 0 || m_LayerIndex >= m_AnimatedTarget.layerCount) { mActivationTime = 0; //UnityEngine.Profiling.Profiler.EndSample(); return defaultCam; } // Get the current state AnimatorStateInfo info = m_AnimatedTarget.GetCurrentAnimatorStateInfo(m_LayerIndex); int hash = info.fullPathHash; // Is there an animation clip substate? AnimatorClipInfo[] clips = m_AnimatedTarget.GetCurrentAnimatorClipInfo(m_LayerIndex); if (clips.Length > 1) { // Find the strongest-weighted one int bestClip = -1; for (int i = 0; i < clips.Length; ++i) if (bestClip < 0 || clips[i].weight > clips[bestClip].weight) bestClip = i; // Use its hash if (bestClip >= 0 && clips[bestClip].weight > 0) hash = Animator.StringToHash(CreateFakeHashName(hash, clips[bestClip].clip.name)); } // If we don't have an instruction for this state, find a suitable default while (hash != 0 && !mInstructionDictionary.ContainsKey(hash)) hash = mStateParentLookup.ContainsKey(hash) ? mStateParentLookup[hash] : 0; float now = Time.time; if (mActivationTime != 0) { // Is it active now? if (mActiveInstruction.m_FullHash == hash) { // Yes, cancel any pending mPendingActivationTime = 0; //UnityEngine.Profiling.Profiler.EndSample(); return mActiveInstruction.m_VirtualCamera; } // Is it pending? if (deltaTime >= 0) { if (mPendingActivationTime != 0 && mPendingInstruction.m_FullHash == hash) { // Has it been pending long enough, and are we allowed to switch away // from the active action? if ((now - mPendingActivationTime) > mPendingInstruction.m_ActivateAfter && ((now - mActivationTime) > mActiveInstruction.m_MinDuration || mPendingInstruction.m_VirtualCamera.Priority > mActiveInstruction.m_VirtualCamera.Priority)) { // Yes, activate it now mActiveInstruction = mPendingInstruction; mActivationTime = now; mPendingActivationTime = 0; } //UnityEngine.Profiling.Profiler.EndSample(); return mActiveInstruction.m_VirtualCamera; } } } // Neither active nor pending. mPendingActivationTime = 0; // cancel the pending, if any if (!mInstructionDictionary.ContainsKey(hash)) { // No defaults set, we just ignore this state if (mActivationTime != 0) return mActiveInstruction.m_VirtualCamera; //UnityEngine.Profiling.Profiler.EndSample(); return defaultCam; } // Can we activate it now? Instruction newInstr = m_Instructions[mInstructionDictionary[hash]]; if (newInstr.m_VirtualCamera == null) newInstr.m_VirtualCamera = defaultCam; if (deltaTime >= 0 && mActivationTime > 0) { if (newInstr.m_ActivateAfter > 0 || ((now - mActivationTime) < mActiveInstruction.m_MinDuration && newInstr.m_VirtualCamera.Priority <= mActiveInstruction.m_VirtualCamera.Priority)) { // Too early - make it pending mPendingInstruction = newInstr; mPendingActivationTime = now; if (mActivationTime != 0) return mActiveInstruction.m_VirtualCamera; //UnityEngine.Profiling.Profiler.EndSample(); return defaultCam; } } // Activate now mActiveInstruction = newInstr; mActivationTime = now; //UnityEngine.Profiling.Profiler.EndSample(); return mActiveInstruction.m_VirtualCamera; } private AnimationCurve LookupBlendCurve( ICinemachineCamera fromKey, ICinemachineCamera toKey, out float duration) { // Get the blend curve that's most appropriate for these cameras AnimationCurve blendCurve = m_DefaultBlend.BlendCurve; if (m_CustomBlends != null) { string fromCameraName = (fromKey != null) ? fromKey.Name : string.Empty; string toCameraName = (toKey != null) ? toKey.Name : string.Empty; blendCurve = m_CustomBlends.GetBlendCurveForVirtualCameras( fromCameraName, toCameraName, blendCurve); } var keys = blendCurve.keys; duration = (keys == null || keys.Length == 0) ? 0 : keys[keys.Length-1].time; return blendCurve; } private CinemachineBlend CreateBlend( ICinemachineCamera camA, ICinemachineCamera camB, AnimationCurve blendCurve, float duration, CinemachineBlend activeBlend, float deltaTime) { if (blendCurve == null || duration <= 0 || (camA == null && camB == null)) return null; if (camA == null || activeBlend != null) { // Blend from the current camera position CameraState state = (activeBlend != null) ? activeBlend.State : State; camA = new StaticPointVirtualCamera(state, (activeBlend != null) ? "Mid-blend" : "(none)"); } return new CinemachineBlend(camA, camB, blendCurve,duration, 0); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.Remoting.Channels; using System.Text; using System.Threading; namespace Apache.Geode.Client.FwkClient { using Apache.Geode.DUnitFramework; class ClientComm : MarshalByRefObject, IClientComm { private static Dictionary<string, object> m_InstanceMap = new Dictionary<string, object>(); private static Dictionary<string, AppDomain> m_appDomainMap = new Dictionary<string, AppDomain>(); private static volatile bool m_exiting = false; private void CallP(int objectId, string assemblyName, string typeName, string methodName, object[] paramList, ref object result) { if (m_exiting) { return; } string objID = objectId.ToString(); object typeInst = null; string appDomain = null; // assume first argument to be the name of AppDomain if (paramList != null && paramList.Length > 0) { object param = paramList[paramList.Length - 1]; if (param is string && (appDomain = (string)param).StartsWith( Util.AppDomainPrefix)) { appDomain = appDomain.Substring(Util.AppDomainPrefix.Length); if (appDomain.Length > 0) { objID = Util.AppDomainPrefix + ":" + appDomain + objID; object[] newParams = new object[paramList.Length - 1]; Array.Copy(paramList, 0, newParams, 0, paramList.Length - 1); paramList = newParams; } else { appDomain = null; } } else { appDomain = null; } } lock (((ICollection)m_InstanceMap).SyncRoot) { if (m_InstanceMap.ContainsKey(objID)) { typeInst = m_InstanceMap[objID]; } else if (appDomain != null) { AppDomain domain; if (!m_appDomainMap.ContainsKey(appDomain)) { domain = AppDomain.CreateDomain(appDomain); CreateBBServerConnection urlConn = (CreateBBServerConnection)domain. CreateInstanceAndUnwrap("FwkClient", "Apache.Geode.Client.FwkClient.CreateBBServerConnection"); urlConn.OpenBBServerConnection(ClientProcess.bbUrl); urlConn.SetLogFile(Util.LogFile); Util.Log("Created app domain {0}",domain); m_appDomainMap.Add(appDomain, domain); } else { domain = m_appDomainMap[appDomain]; CreateBBServerConnection urlConn = (CreateBBServerConnection)domain. CreateInstanceAndUnwrap("FwkClient", "Apache.Geode.Client.FwkClient.CreateBBServerConnection"); urlConn.SetLogFile(Util.LogFile); } try { typeInst = domain.CreateInstanceAndUnwrap(assemblyName, typeName); } catch (Exception e) { Util.Log("Exception thrown for app domain CreateInstanceAndUnwrap : {0} ", e.Message); } if (typeInst != null) { m_InstanceMap[objID] = typeInst; } else { throw new IllegalArgException( "FATAL: Could not load class with name: " + typeName); } } else { Assembly assmb = null; try { assmb = Assembly.Load(assemblyName); } catch (Exception) { throw new IllegalArgException( "FATAL: Could not load assembly: " + assemblyName); } typeInst = assmb.CreateInstance(typeName); if (typeInst != null) { m_InstanceMap[objID] = typeInst; } else { throw new IllegalArgException( "FATAL: Could not load class with name: " + typeName); } } } MethodInfo[] mInfos = typeInst.GetType().GetMethods( BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy); MethodInfo mInfo = null; foreach (MethodInfo method in mInfos) { if (method.Name.Equals(methodName, StringComparison.CurrentCultureIgnoreCase)) { ParameterInfo[] prms = method.GetParameters(); int paramLen = (paramList != null ? paramList.Length : 0); if (paramLen == prms.Length) { mInfo = method; } } } if (mInfo != null) { Thread currentThread = Thread.CurrentThread; lock (((ICollection)UnitThread.GlobalUnitThreads).SyncRoot) { if (!UnitThread.GlobalUnitThreads.ContainsKey(currentThread)) { UnitThread.GlobalUnitThreads.Add(currentThread, true); } } if (result == null) { mInfo.Invoke(typeInst, paramList); } else { result = mInfo.Invoke(typeInst, paramList); } lock (((ICollection)UnitThread.GlobalUnitThreads).SyncRoot) { if (!UnitThread.GlobalUnitThreads.ContainsKey(currentThread)) { UnitThread.GlobalUnitThreads.Remove(currentThread); } } } else { throw new IllegalArgException("FATAL: Could not load function with name: " + methodName + ", in class: " + typeInst.GetType()); } } #region IClientComm Members public void Call(int objectId, string assemblyName, string typeName, string methodName, params object[] paramList) { object obj = null; CallP(objectId, assemblyName, typeName, methodName, paramList, ref obj); } public object CallR(int objectId, string assemblyName, string typeName, string methodName, params object[] paramList) { object obj = 0; CallP(objectId, assemblyName, typeName, methodName, paramList, ref obj); return obj; } public void RemoveObjectID(int objectId) { lock (((ICollection)m_InstanceMap).SyncRoot) { if (m_InstanceMap.ContainsKey(objectId.ToString())) { m_InstanceMap.Remove(objectId.ToString()); } } } public void SetLogFile(string logFile) { Util.LogFile = logFile; } public void SetLogLevel(Util.LogLevel logLevel) { Util.CurrentLogLevel = logLevel; } public bool CreateNew(string clientId, int port) { string clientPath = Assembly.GetExecutingAssembly().Location; string[] args = Environment.GetCommandLineArgs(); string argStr = string.Empty; for (int i = 1; i < args.Length - 1; i++) { string arg = args[i]; if (arg.StartsWith("--id=")) { argStr += ("\"--id=" + clientId + "\" "); } else { argStr += ('"' + arg + "\" "); } } argStr += port.ToString(); Process proc; return Util.StartProcess(clientPath, argStr, false, null, false, false, false, out proc); } public void DumpStackTrace() { StringBuilder dumpStr = new StringBuilder(); try { dumpStr.Append(Util.MarkerString); dumpStr.Append("Dumping managed stack for process [" + Util.PID + "]:"); dumpStr.Append(Util.MarkerString); lock (((ICollection)UnitThread.GlobalUnitThreads).SyncRoot) { foreach (Thread thread in UnitThread.GlobalUnitThreads.Keys) { dumpStr.Append(UnitThread.GetStackTrace(thread)); dumpStr.Append(Environment.NewLine + Environment.NewLine); } } dumpStr.Append(Util.MarkerString); Util.Log(dumpStr.ToString()); dumpStr.Length = 0; dumpStr.Append("Dumping native stack for process [" + Util.PID + "]:"); dumpStr.Append(Util.MarkerString); Process cdbProc; // Expect to find 'cdb.pl' in the same dir as FwkClient.exe if (Util.StartProcess("perl", Util.AssemblyDir + "/cdb.pl " + Util.PID, false, null, true, false, true, out cdbProc)) { StreamReader cdbRead = cdbProc.StandardOutput; StreamReader cdbReadErr = cdbProc.StandardError; dumpStr.Append(cdbRead.ReadToEnd()); dumpStr.Append(cdbReadErr.ReadToEnd()); cdbProc.WaitForExit(); cdbRead.Close(); cdbReadErr.Close(); } else { dumpStr.Append("Failed to start: perl "); dumpStr.Append(Util.AssemblyDir + "/cdb.pl " + Util.PID); } } catch (Exception ex) { dumpStr.Append("Exception while invoking cdb.pl: "); dumpStr.Append(ex.ToString()); } dumpStr.Append(Util.MarkerString + Environment.NewLine); Util.Log(dumpStr.ToString()); } public void TestCleanup() { foreach (UnitFnMethod deleg in Util.RegisteredTestCompleteDelegates) { try { Util.Log("Cleaning test on client [{0}]: Calling {1} :: {2}", Util.ClientId, deleg.Method.DeclaringType, deleg.Method); deleg(); } catch (Exception ex) { Util.Log(Util.LogLevel.Error, ex.ToString()); } } } public void Exit(bool force) { try { m_exiting = true; if (!force) { foreach (UnitFnMethod deleg in Util.RegisteredTestCompleteDelegates) { try { Util.Log("Exiting client [{0}]: Calling {1} :: {2}", Util.ClientId, deleg.Method.DeclaringType, deleg.Method); deleg(); } catch (Exception ex) { Util.Log(Util.LogLevel.Error, ex.ToString()); } } } } finally { Environment.Exit(0); Util.Process.Kill(); } } public Process GetClientProcess() { return Util.Process; } #endregion } }
using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using LayeredForms; using LayeredForms.Utilities; namespace BorderSkin.BorderSkinning.Skin { internal enum SkinElementKeys { Frames, NormalTextBrush, MaxTextBrush, TextFormat, Font, StretchRect, ContentRect, NormalEdges, MaxEdges, BackColor, ElementAlign, TextAlign, ID, MaskOutBitmap, ImagePath } class SkinElement : IDisposable { public static readonly int MaskOutColor = 0xFFFFFF; private readonly Dictionary<SkinElementKeys, Object> _elements = new Dictionary<SkinElementKeys, object>(); private bool _disposedValue; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!_disposedValue) { foreach (object element in _elements.Values) { var disposable = element as IDisposable; if (disposable != null) { disposable.Dispose(); } } } _disposedValue = true; } public SolidBrush NormalTextBrush { get { return GetWithoutException<SolidBrush>(SkinElementKeys.NormalTextBrush); } set { _elements[SkinElementKeys.NormalTextBrush] = value; } } public SolidBrush MaxTextBrush { get { return GetWithoutException<SolidBrush>(SkinElementKeys.MaxTextBrush); } set { _elements[SkinElementKeys.MaxTextBrush] = value; } } public StringFormat TextFormat { get { return GetWithoutException<StringFormat>(SkinElementKeys.TextFormat); } set { _elements[SkinElementKeys.TextFormat] = value; } } public Font Font { get { return GetWithoutException<Font>(SkinElementKeys.Font); } set { _elements[SkinElementKeys.Font] = value; } } public Padding StretchPadding { get { return GetWithoutException<Padding>(SkinElementKeys.StretchRect); } set { _elements[SkinElementKeys.StretchRect] = value; } } public Padding ContentPadding { get { return GetWithoutException<Padding>(SkinElementKeys.ContentRect); } set { _elements[SkinElementKeys.ContentRect] = value; } } public Padding NormalEdges { get { return GetWithoutException<Padding>(SkinElementKeys.NormalEdges); } set { _elements[SkinElementKeys.NormalEdges] = value; } } public Padding MaxEdges { get { return GetWithoutException<Padding>(SkinElementKeys.MaxEdges); } set { _elements[SkinElementKeys.MaxEdges] = value; } } public Color BackColor { get { return GetWithoutException<Color>(SkinElementKeys.BackColor); } set { _elements[SkinElementKeys.BackColor] = value; } } public VerticalAlignment ElementAlign { get { return GetWithoutException<VerticalAlignment>(SkinElementKeys.ElementAlign); } set { _elements[SkinElementKeys.ElementAlign] = value; } } public VerticalAlignment TextAlign { get { return GetWithoutException<VerticalAlignment>(SkinElementKeys.TextAlign); } set { _elements[SkinElementKeys.TextAlign] = value; } } public String ID { get { return GetWithoutException<string>(SkinElementKeys.ID); } set { _elements[SkinElementKeys.ID] = value; } } public int FrameWidth { get { return FrameSize.Width; } } public int FrameHeight { get { return FrameSize.Height; } } public ImageWithDeviceContext MaskOutBitmap { get { return GetWithoutException<ImageWithDeviceContext>(SkinElementKeys.MaskOutBitmap); } set { _elements[SkinElementKeys.MaskOutBitmap] = value; } } public string ImagePath { get { return GetWithoutException<string>(SkinElementKeys.ImagePath); } set { _elements[SkinElementKeys.ImagePath] = value; } } public Size FrameSize { get { return Frames != null ? Frames[0].Size : Size.Empty; } } public ImageWithDeviceContext[] Frames { get { return GetWithoutException<ImageWithDeviceContext[]>(SkinElementKeys.Frames); } set { _elements[SkinElementKeys.Frames] = value; } } private T GetWithoutException<T>(SkinElementKeys property) { Object value; _elements.TryGetValue(property, out value); return value != null ? (T) value : default(T); } public SolidBrush GetTextBrush(bool maximized) { return maximized ? MaxTextBrush : NormalTextBrush; } public Padding GetEdges(bool maximized) { return maximized ? MaxEdges : NormalEdges; } public int GetStateYPosition(bool activeType) { return activeType ? 0 : FrameHeight; } public Padding CalculateEdgesRelativeToTopLeftCorner(int blockWidth, bool maximized) { return CalculateEdgesRelativeToTopLeftCorner(blockWidth, maximized, FrameWidth); } public Padding CalculateEdgesRelativeToTopLeftCorner(int blockWidth, bool maximized, int objectWidth) { Padding edges = GetEdges(maximized); switch (ElementAlign) { case VerticalAlignment.center: edges.Left = (blockWidth/2) + (objectWidth/2) - (edges.Right + edges.Left); break; case VerticalAlignment.right: edges.Left = blockWidth - (objectWidth + edges.Left); break; } return edges; } } }
using System; using EventHandlerList = System.ComponentModel.EventHandlerList; using BitSet = antlr.collections.impl.BitSet; using AST = antlr.collections.AST; using ASTArray = antlr.collections.impl.ASTArray; using antlr.debug; using MessageListener = antlr.debug.MessageListener; using ParserListener = antlr.debug.ParserListener; using ParserMatchListener = antlr.debug.ParserMatchListener; using ParserTokenListener = antlr.debug.ParserTokenListener; using SemanticPredicateListener = antlr.debug.SemanticPredicateListener; using SyntacticPredicateListener = antlr.debug.SyntacticPredicateListener; using TraceListener = antlr.debug.TraceListener; /* private Vector messageListeners; private Vector newLineListeners; private Vector matchListeners; private Vector tokenListeners; private Vector semPredListeners; private Vector synPredListeners; private Vector traceListeners; */ namespace antlr { /*ANTLR Translator Generator * Project led by Terence Parr at http://www.jGuru.com * Software rights: http://www.antlr.org/license.html * * $Id:$ */ // // ANTLR C# Code Generator by Micheal Jordan // Kunle Odutola : kunle UNDERSCORE odutola AT hotmail DOT com // Anthony Oguntimehin // // With many thanks to Eric V. Smith from the ANTLR list. // public abstract class Parser : IParserDebugSubject { // Used to store event delegates private EventHandlerList events_; protected internal EventHandlerList Events { get { if (null == events_) { events_ = new EventHandlerList(); } return events_; } } // The unique keys for each event that Parser [objects] can generate internal static readonly object EnterRuleEventKey = new object(); internal static readonly object ExitRuleEventKey = new object(); internal static readonly object DoneEventKey = new object(); internal static readonly object ReportErrorEventKey = new object(); internal static readonly object ReportWarningEventKey = new object(); internal static readonly object NewLineEventKey = new object(); internal static readonly object MatchEventKey = new object(); internal static readonly object MatchNotEventKey = new object(); internal static readonly object MisMatchEventKey = new object(); internal static readonly object MisMatchNotEventKey = new object(); internal static readonly object ConsumeEventKey = new object(); internal static readonly object LAEventKey = new object(); internal static readonly object SemPredEvaluatedEventKey = new object(); internal static readonly object SynPredStartedEventKey = new object(); internal static readonly object SynPredFailedEventKey = new object(); internal static readonly object SynPredSucceededEventKey = new object(); protected internal ParserSharedInputState inputState; /*Nesting level of registered handlers */ // protected int exceptionLevel = 0; /*Table of token type to token names */ protected internal string[] tokenNames; /*AST return value for a rule is squirreled away here */ protected internal AST returnAST; /*AST support code; parser and treeparser delegate to this object */ protected internal ASTFactory _astFactory; private bool ignoreInvalidDebugCalls = false; /*Used to keep track of indentdepth for traceIn/Out */ protected internal int traceDepth = 0; public Parser() { inputState = new ParserSharedInputState(); } public Parser(ParserSharedInputState state) { inputState = state; } /// <summary> /// /// </summary> public event TraceEventHandler EnterRule { add { Events.AddHandler(EnterRuleEventKey, value); } remove { Events.RemoveHandler(EnterRuleEventKey, value); } } public event TraceEventHandler ExitRule { add { Events.AddHandler(ExitRuleEventKey, value); } remove { Events.RemoveHandler(ExitRuleEventKey, value); } } public event TraceEventHandler Done { add { Events.AddHandler(DoneEventKey, value); } remove { Events.RemoveHandler(DoneEventKey, value); } } public event MessageEventHandler ErrorReported { add { Events.AddHandler(ReportErrorEventKey, value); } remove { Events.RemoveHandler(ReportErrorEventKey, value); } } public event MessageEventHandler WarningReported { add { Events.AddHandler(ReportWarningEventKey, value); } remove { Events.RemoveHandler(ReportWarningEventKey, value); } } public event MatchEventHandler MatchedToken { add { Events.AddHandler(MatchEventKey, value); } remove { Events.RemoveHandler(MatchEventKey, value); } } public event MatchEventHandler MatchedNotToken { add { Events.AddHandler(MatchNotEventKey, value); } remove { Events.RemoveHandler(MatchNotEventKey, value); } } public event MatchEventHandler MisMatchedToken { add { Events.AddHandler(MisMatchEventKey, value); } remove { Events.RemoveHandler(MisMatchEventKey, value); } } public event MatchEventHandler MisMatchedNotToken { add { Events.AddHandler(MisMatchNotEventKey, value); } remove { Events.RemoveHandler(MisMatchNotEventKey, value); } } public event TokenEventHandler ConsumedToken { add { Events.AddHandler(ConsumeEventKey, value); } remove { Events.RemoveHandler(ConsumeEventKey, value); } } public event TokenEventHandler TokenLA { add { Events.AddHandler(LAEventKey, value); } remove { Events.RemoveHandler(LAEventKey, value); } } public event SemanticPredicateEventHandler SemPredEvaluated { add { Events.AddHandler(SemPredEvaluatedEventKey, value); } remove { Events.RemoveHandler(SemPredEvaluatedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredStarted { add { Events.AddHandler(SynPredStartedEventKey, value); } remove { Events.RemoveHandler(SynPredStartedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredFailed { add { Events.AddHandler(SynPredFailedEventKey, value); } remove { Events.RemoveHandler(SynPredFailedEventKey, value); } } public event SyntacticPredicateEventHandler SynPredSucceeded { add { Events.AddHandler(SynPredSucceededEventKey, value); } remove { Events.RemoveHandler(SynPredSucceededEventKey, value); } } public virtual void addMessageListener(MessageListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addMessageListener() is only valid if parser built for debugging"); } public virtual void addParserListener(ParserListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserListener() is only valid if parser built for debugging"); } public virtual void addParserMatchListener(ParserMatchListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserMatchListener() is only valid if parser built for debugging"); } public virtual void addParserTokenListener(ParserTokenListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addParserTokenListener() is only valid if parser built for debugging"); } public virtual void addSemanticPredicateListener(SemanticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addSemanticPredicateListener() is only valid if parser built for debugging"); } public virtual void addSyntacticPredicateListener(SyntacticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addSyntacticPredicateListener() is only valid if parser built for debugging"); } public virtual void addTraceListener(TraceListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("addTraceListener() is only valid if parser built for debugging"); } /*Get another token object from the token stream */ public abstract void consume(); /*Consume tokens until one matches the given token */ public virtual void consumeUntil(int tokenType) { while (LA(1) != Token.EOF_TYPE && LA(1) != tokenType) { consume(); } } /*Consume tokens until one matches the given token set */ public virtual void consumeUntil(BitSet bset) { while (LA(1) != Token.EOF_TYPE && !bset.member(LA(1))) { consume(); } } protected internal virtual void defaultDebuggingSetup(TokenStream lexer, TokenBuffer tokBuf) { // by default, do nothing -- we're not debugging } /*Get the AST return value squirreled away in the parser */ public virtual AST getAST() { return returnAST; } public virtual ASTFactory astFactory { get { if (null == _astFactory) { _astFactory = new ASTFactory(); } return _astFactory; } set { _astFactory = value; } } public virtual ASTFactory getASTFactory() { return astFactory; } public virtual string getFilename() { return inputState.filename; } public virtual ParserSharedInputState getInputState() { return inputState; } public virtual void setInputState(ParserSharedInputState state) { inputState = state; } public virtual void resetState() { traceDepth = 0; inputState.reset(); } public virtual string getTokenName(int num) { return tokenNames[num]; } public virtual string[] getTokenNames() { return tokenNames; } public virtual bool isDebugMode() { return false; } /*Return the token type of the ith token of lookahead where i=1 * is the current token being examined by the parser (i.e., it * has not been matched yet). */ public abstract int LA(int i); /*Return the ith token of lookahead */ public abstract IToken LT(int i); // Forwarded to TokenBuffer public virtual int mark() { return inputState.input.mark(); } /*Make sure current lookahead symbol matches token type <tt>t</tt>. * Throw an exception upon mismatch, which is catch by either the * error handler or by the syntactic predicate. */ public virtual void match(int t) { if (LA(1) != t) throw new MismatchedTokenException(tokenNames, LT(1), t, false, getFilename()); else consume(); } /*Make sure current lookahead symbol matches the given set * Throw an exception upon mismatch, which is catch by either the * error handler or by the syntactic predicate. */ public virtual void match(BitSet b) { if (!b.member(LA(1))) throw new MismatchedTokenException(tokenNames, LT(1), b, false, getFilename()); else consume(); } public virtual void matchNot(int t) { if (LA(1) == t) throw new MismatchedTokenException(tokenNames, LT(1), t, true, getFilename()); else consume(); } /// <summary> /// @deprecated as of 2.7.2. This method calls System.exit() and writes /// directly to stderr, which is usually not appropriate when /// a parser is embedded into a larger application. Since the method is /// <code>static</code>, it cannot be overridden to avoid these problems. /// ANTLR no longer uses this method internally or in generated code. /// </summary> /// [Obsolete("De-activated since version 2.7.2.6 as it cannot be overidden.", true)] public static void panic() { System.Console.Error.WriteLine("Parser: panic"); System.Environment.Exit(1); } public virtual void removeMessageListener(MessageListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeMessageListener() is only valid if parser built for debugging"); } public virtual void removeParserListener(ParserListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserListener() is only valid if parser built for debugging"); } public virtual void removeParserMatchListener(ParserMatchListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserMatchListener() is only valid if parser built for debugging"); } public virtual void removeParserTokenListener(ParserTokenListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeParserTokenListener() is only valid if parser built for debugging"); } public virtual void removeSemanticPredicateListener(SemanticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("removeSemanticPredicateListener() is only valid if parser built for debugging"); } public virtual void removeSyntacticPredicateListener(SyntacticPredicateListener l) { if (!ignoreInvalidDebugCalls) throw new System.ArgumentException("removeSyntacticPredicateListener() is only valid if parser built for debugging"); } public virtual void removeTraceListener(TraceListener l) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("removeTraceListener() is only valid if parser built for debugging"); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(RecognitionException ex) { Console.Error.WriteLine(ex); } /*Parser error-reporting function can be overridden in subclass */ public virtual void reportError(string s) { if (getFilename() == null) { Console.Error.WriteLine("error: " + s); } else { Console.Error.WriteLine(getFilename() + ": error: " + s); } } /*Parser warning-reporting function can be overridden in subclass */ public virtual void reportWarning(string s) { if (getFilename() == null) { Console.Error.WriteLine("warning: " + s); } else { Console.Error.WriteLine(getFilename() + ": warning: " + s); } } public virtual void recover(RecognitionException ex, BitSet tokenSet) { consume(); consumeUntil(tokenSet); } public virtual void rewind(int pos) { inputState.input.rewind(pos); } /// <summary> /// Specify an object with support code (shared by Parser and TreeParser. /// Normally, the programmer does not play with this, using /// <see cref="setASTNodeClass"/> instead. /// </summary> /// <param name="f"></param> public virtual void setASTFactory(ASTFactory f) { astFactory = f; } /// <summary> /// Specify the type of node to create during tree building. /// </summary> /// <param name="cl">Fully qualified AST Node type name.</param> public virtual void setASTNodeClass(string cl) { astFactory.setASTNodeType(cl); } /// <summary> /// Specify the type of node to create during tree building. /// use <see cref="setASTNodeClass"/> now to be consistent with /// Token Object Type accessor. /// </summary> /// <param name="nodeType">Fully qualified AST Node type name.</param> [Obsolete("Replaced by setASTNodeClass(string) since version 2.7.1", true)] public virtual void setASTNodeType(string nodeType) { setASTNodeClass(nodeType); } public virtual void setDebugMode(bool debugMode) { if (!ignoreInvalidDebugCalls) throw new System.SystemException("setDebugMode() only valid if parser built for debugging"); } public virtual void setFilename(string f) { inputState.filename = f; } public virtual void setIgnoreInvalidDebugCalls(bool Value) { ignoreInvalidDebugCalls = Value; } /*Set or change the input token buffer */ public virtual void setTokenBuffer(TokenBuffer t) { inputState.input = t; } public virtual void traceIndent() { for (int i = 0; i < traceDepth; i++) Console.Out.Write(" "); } public virtual void traceIn(string rname) { traceDepth += 1; traceIndent(); Console.Out.WriteLine("> " + rname + "; LA(1)==" + LT(1).getText() + ((inputState.guessing > 0)?" [guessing]":"")); } public virtual void traceOut(string rname) { traceIndent(); Console.Out.WriteLine("< " + rname + "; LA(1)==" + LT(1).getText() + ((inputState.guessing > 0)?" [guessing]":"")); traceDepth -= 1; } } }
// 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 Microsoft.CodeAnalysis.CSharp.CodeRefactorings.MoveDeclarationNearReference; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.MoveDeclarationNearReference { public class MoveDeclarationNearReferenceTests : AbstractCSharpCodeActionTest { protected override object CreateCodeRefactoringProvider(Workspace workspace) { return new MoveDeclarationNearReferenceCodeRefactoringProvider(); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMove1() { await TestAsync( @"class C { void M() { int [||]x; { Console.WriteLine(x); } } }", @"class C { void M() { { int x; Console.WriteLine(x); } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMove2() { await TestAsync( @"class C { void M() { int [||]x; Console.WriteLine(); Console.WriteLine(x); } }", @"class C { void M() { Console.WriteLine(); int x; Console.WriteLine(x); } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMove3() { await TestAsync( @"class C { void M() { int [||]x; Console.WriteLine(); { Console.WriteLine(x); } { Console.WriteLine(x); } }", @"class C { void M() { Console.WriteLine(); int x; { Console.WriteLine(x); } { Console.WriteLine(x); } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMove4() { await TestAsync( @"class C { void M() { int [||]x; Console.WriteLine(); { Console.WriteLine(x); } }", @"class C { void M() { Console.WriteLine(); { int x; Console.WriteLine(x); } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestAssign1() { await TestAsync( @"class C { void M() { int [||]x; { x = 5; Console.WriteLine(x); } } }", @"class C { void M() { { int x = 5; Console.WriteLine(x); } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestAssign2() { await TestAsync( @"class C { void M() { int [||]x = 0; { x = 5; Console.WriteLine(x); } } }", @"class C { void M() { { int x = 5; Console.WriteLine(x); } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestAssign3() { await TestAsync( @"class C { void M() { var [||]x = (short)0; { x = 5; Console.WriteLine(x); } } }", @"class C { void M() { { var x = (short)0; x = 5; Console.WriteLine(x); } } }", index: 0); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissing1() { await TestMissingAsync( @"class C { void M() { int [||]x; Console.WriteLine(x); } }"); } [WorkItem(538424, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538424")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWhenReferencedInDeclaration() { await TestMissingAsync( @"class Program { static void Main ( ) { object [ ] [||]x = { x = null } ; x . ToString ( ) ; } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingWhenInDeclarationGroup() { await TestMissingAsync( @"class Program { static void Main ( ) { int [||]i = 5; int j = 10; Console.WriteLine(i); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] [WorkItem(541475, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541475")] public async Task Regression8190() { await TestMissingAsync( @"class Program { void M() { { object x; [|object|] } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestFormatting() { await TestAsync( @"class Program { static void Main(string[] args) { int [||]i = 5; Console.WriteLine(); Console.Write(i); } }", @"class Program { static void Main(string[] args) { Console.WriteLine(); int i = 5; Console.Write(i); } }", index: 0, compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingInHiddenBlock1() { await TestMissingAsync( @"class Program { void Main() { int [|x|] = 0; Foo(); #line hidden Bar(x); } #line default }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestMissingInHiddenBlock2() { await TestMissingAsync( @"class Program { void Main() { int [|x|] = 0; Foo(); #line hidden Foo(); #line default Bar(x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestAvailableInNonHiddenBlock1() { await TestAsync( @"#line default class Program { void Main() { int [||]x = 0; Foo(); Bar(x); #line hidden } #line default }", @"#line default class Program { void Main() { Foo(); int x = 0; Bar(x); #line hidden } #line default }", compareTokens: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestAvailableInNonHiddenBlock2() { await TestAsync( @"class Program { void Main() { int [||]x = 0; Foo(); #line hidden Foo(); #line default Foo(); Bar(x); } }", @"class Program { void Main() { Foo(); #line hidden Foo(); #line default Foo(); int x = 0; Bar(x); } }", compareTokens: false); } [WorkItem(545435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestWarnOnChangingScopes1() { await TestAsync( @"using System . Linq ; class Program { void Main ( ) { var [||]@lock = new object ( ) ; new [ ] { 1 } . AsParallel ( ) . ForAll ( ( i ) => { lock ( @lock ) { } } ) ; } } ", @"using System . Linq ; class Program { void Main ( ) { new [ ] { 1 } . AsParallel ( ) . ForAll ( ( i ) => { {|Warning:var @lock = new object ( ) ;|} lock ( @lock ) { } } ) ; } } "); } [WorkItem(545435, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545435")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TestWarnOnChangingScopes2() { await TestAsync( @"using System ; using System . Linq ; class Program { void Main ( ) { var [||]i = 0 ; foreach ( var v in new [ ] { 1 } ) { Console . Write ( i ) ; i ++ ; } } } ", @"using System ; using System . Linq ; class Program { void Main ( ) { foreach ( var v in new [ ] { 1 } ) { {|Warning:var i = 0 ;|} Console . Write ( i ) ; i ++ ; } } } "); } [WorkItem(545840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545840")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task InsertCastIfNecessary1() { await TestAsync( @"using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { var [||]a = Outer(x => Inner(x, null), null); unsafe { Console.WriteLine(a); } } }", @"using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { unsafe { var a = Outer(x => Inner(x, null), (object)null); Console.WriteLine(a); } } }", compareTokens: false); } [WorkItem(545835, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task InsertCastIfNecessary2() { await TestAsync( @"using System; class X { static int Foo(Func<int?, byte> x, object y) { return 1; } static int Foo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { var [||]a = Foo(X => (byte)X.Value, null); unchecked { Console.WriteLine(a); } } }", @"using System; class X { static int Foo(Func<int?, byte> x, object y) { return 1; } static int Foo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { unchecked { var a = Foo(X => (byte)X.Value, (object)null); Console.WriteLine(a); } } }", compareTokens: false); } [WorkItem(546267, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546267")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task MissingIfNotInDeclarationSpan() { await TestMissingAsync( @"using System; using System.Collections.Generic; using System.Linq; class Program { static void Main(string[] args) { // Comment [||]about foo! // Comment about foo! // Comment about foo! // Comment about foo! // Comment about foo! // Comment about foo! // Comment about foo! int foo; Console.WriteLine(); Console.WriteLine(foo); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task Tuple() { await TestAsync( @"class C { void M() { (int, string) [||]x; { Console.WriteLine(x); } } }", @"class C { void M() { { (int, string) x; Console.WriteLine(x); } } }", index: 0, parseOptions: TestOptions.Regular.WithTuplesFeature(), withScriptOption: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsMoveDeclarationNearReference)] public async Task TupleWithNames() { await TestAsync( @"class C { void M() { (int a, string b) [||]x; { Console.WriteLine(x); } } }", @"class C { void M() { { (int a, string b) x; Console.WriteLine(x); } } }", index: 0, parseOptions: TestOptions.Regular.WithTuplesFeature(), withScriptOption: true); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using OpenMetaverse; namespace OpenSim.Region.Framework.Scenes.Animation { /// <summary> /// Written to decode and encode a binary animation asset. /// The SecondLife Client reads in a BVH file and converts /// it to the format described here. This isn't /// </summary> public class BinBVHAnimation { /// <summary> /// Rotation Keyframe count (used internally) /// Don't use this, use the rotationkeys.Length on each joint /// </summary> private int rotationkeys; /// <summary> /// Position Keyframe count (used internally) /// Don't use this, use the positionkeys.Length on each joint /// </summary> private int positionkeys; public UInt16 unknown0; // Always 1 public UInt16 unknown1; // Always 0 /// <summary> /// Animation Priority /// </summary> public int Priority; /// <summary> /// The animation length in seconds. /// </summary> public Single Length; /// <summary> /// Expression set in the client. Null if [None] is selected /// </summary> public string ExpressionName; // "" (null) /// <summary> /// The time in seconds to start the animation /// </summary> public Single InPoint; /// <summary> /// The time in seconds to end the animation /// </summary> public Single OutPoint; /// <summary> /// Loop the animation /// </summary> public bool Loop; /// <summary> /// Meta data. Ease in Seconds. /// </summary> public Single EaseInTime; /// <summary> /// Meta data. Ease out seconds. /// </summary> public Single EaseOutTime; /// <summary> /// Meta Data for the Hand Pose /// </summary> public uint HandPose; /// <summary> /// Number of joints defined in the animation /// Don't use this.. use joints.Length /// </summary> private uint m_jointCount; /// <summary> /// Contains an array of joints /// </summary> public binBVHJoint[] Joints; public byte[] ToBytes() { byte[] outputbytes; using (MemoryStream ms = new MemoryStream()) using (BinaryWriter iostream = new BinaryWriter(ms)) { iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown0))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(unknown1))); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(Length))); iostream.Write(BinBVHUtil.WriteNullTerminatedString(ExpressionName)); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(InPoint))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(OutPoint))); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Loop ? 1 : 0))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseInTime))); iostream.Write(BinBVHUtil.ES(Utils.FloatToBytes(EaseOutTime))); iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes(HandPose))); iostream.Write(BinBVHUtil.ES(Utils.UIntToBytes((uint)(Joints.Length)))); for (int i = 0; i < Joints.Length; i++) { Joints[i].WriteBytesToStream(iostream, InPoint, OutPoint); } iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(0))); using (MemoryStream ms2 = (MemoryStream)iostream.BaseStream) outputbytes = ms2.ToArray(); } return outputbytes; } public BinBVHAnimation() { rotationkeys = 0; positionkeys = 0; unknown0 = 1; unknown1 = 0; Priority = 1; Length = 0; ExpressionName = string.Empty; InPoint = 0; OutPoint = 0; Loop = false; EaseInTime = 0; EaseOutTime = 0; HandPose = 1; m_jointCount = 0; Joints = new binBVHJoint[1]; Joints[0] = new binBVHJoint(); Joints[0].Name = "mPelvis"; Joints[0].Priority = 7; Joints[0].positionkeys = new binBVHJointKey[1]; Joints[0].rotationkeys = new binBVHJointKey[1]; Random rnd = new Random(); Joints[0].rotationkeys[0] = new binBVHJointKey(); Joints[0].rotationkeys[0].time = (0f); Joints[0].rotationkeys[0].key_element.X = ((float)rnd.NextDouble() * 2 - 1); Joints[0].rotationkeys[0].key_element.Y = ((float)rnd.NextDouble() * 2 - 1); Joints[0].rotationkeys[0].key_element.Z = ((float)rnd.NextDouble() * 2 - 1); Joints[0].positionkeys[0] = new binBVHJointKey(); Joints[0].positionkeys[0].time = (0f); Joints[0].positionkeys[0].key_element.X = ((float)rnd.NextDouble() * 2 - 1); Joints[0].positionkeys[0].key_element.Y = ((float)rnd.NextDouble() * 2 - 1); Joints[0].positionkeys[0].key_element.Z = ((float)rnd.NextDouble() * 2 - 1); } public BinBVHAnimation(byte[] animationdata) { int i = 0; if (!BitConverter.IsLittleEndian) { unknown0 = Utils.BytesToUInt16(BinBVHUtil.EndianSwap(animationdata,i,2)); i += 2; // Always 1 unknown1 = Utils.BytesToUInt16(BinBVHUtil.EndianSwap(animationdata, i, 2)); i += 2; // Always 0 Priority = Utils.BytesToInt(BinBVHUtil.EndianSwap(animationdata, i, 4)); i += 4; Length = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; } else { unknown0 = Utils.BytesToUInt16(animationdata, i); i += 2; // Always 1 unknown1 = Utils.BytesToUInt16(animationdata, i); i += 2; // Always 0 Priority = Utils.BytesToInt(animationdata, i); i += 4; Length = Utils.BytesToFloat(animationdata, i); i += 4; } ExpressionName = ReadBytesUntilNull(animationdata, ref i); if (!BitConverter.IsLittleEndian) { InPoint = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; OutPoint = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; Loop = (Utils.BytesToInt(BinBVHUtil.EndianSwap(animationdata, i, 4)) != 0); i += 4; EaseInTime = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; EaseOutTime = Utils.BytesToFloat(BinBVHUtil.EndianSwap(animationdata, i, 4), 0); i += 4; HandPose = Utils.BytesToUInt(BinBVHUtil.EndianSwap(animationdata, i, 4)); i += 4; // Handpose? m_jointCount = Utils.BytesToUInt(animationdata, i); i += 4; // Get Joint count } else { InPoint = Utils.BytesToFloat(animationdata, i); i += 4; OutPoint = Utils.BytesToFloat(animationdata, i); i += 4; Loop = (Utils.BytesToInt(animationdata, i) != 0); i += 4; EaseInTime = Utils.BytesToFloat(animationdata, i); i += 4; EaseOutTime = Utils.BytesToFloat(animationdata, i); i += 4; HandPose = Utils.BytesToUInt(animationdata, i); i += 4; // Handpose? m_jointCount = Utils.BytesToUInt(animationdata, i); i += 4; // Get Joint count } Joints = new binBVHJoint[m_jointCount]; // deserialize the number of joints in the animation. // Joints are variable length blocks of binary data consisting of joint data and keyframes for (int iter = 0; iter < m_jointCount; iter++) { binBVHJoint joint = readJoint(animationdata, ref i); Joints[iter] = joint; } } /// <summary> /// Variable length strings seem to be null terminated in the animation asset.. but.. /// use with caution, home grown. /// advances the index. /// </summary> /// <param name="data">The animation asset byte array</param> /// <param name="i">The offset to start reading</param> /// <returns>a string</returns> private static string ReadBytesUntilNull(byte[] data, ref int i) { char nterm = '\0'; // Null terminator int endpos = i; int startpos = i; // Find the null character for (int j = i; j < data.Length; j++) { char spot = Convert.ToChar(data[j]); if (spot == nterm) { endpos = j; break; } } // if we got to the end, then it's a zero length string if (i == endpos) { // advance the 1 null character i++; return string.Empty; } else { // We found the end of the string // append the bytes from the beginning of the string to the end of the string // advance i byte[] interm = new byte[endpos-i]; for (; i<endpos; i++) { interm[i-startpos] = data[i]; } i++; // advance past the null character return Utils.BytesToString(interm); } } /// <summary> /// Read in a Joint from an animation asset byte array /// Variable length Joint fields, yay! /// Advances the index /// </summary> /// <param name="data">animation asset byte array</param> /// <param name="i">Byte Offset of the start of the joint</param> /// <returns>The Joint data serialized into the binBVHJoint structure</returns> private binBVHJoint readJoint(byte[] data, ref int i) { binBVHJointKey[] positions; binBVHJointKey[] rotations; binBVHJoint pJoint = new binBVHJoint(); /* 109 84 111 114 114 111 0 <--- Null terminator */ pJoint.Name = ReadBytesUntilNull(data, ref i); // Joint name /* 2 <- Priority Revisited 0 0 0 */ /* 5 <-- 5 keyframes 0 0 0 ... 5 Keyframe data blocks */ /* 2 <-- 2 keyframes 0 0 0 .. 2 Keyframe data blocks */ if (!BitConverter.IsLittleEndian) { pJoint.Priority = Utils.BytesToInt(BinBVHUtil.EndianSwap(data, i, 4)); i += 4; // Joint Priority override? rotationkeys = Utils.BytesToInt(BinBVHUtil.EndianSwap(data, i, 4)); i += 4; // How many rotation keyframes } else { pJoint.Priority = Utils.BytesToInt(data, i); i += 4; // Joint Priority override? rotationkeys = Utils.BytesToInt(data, i); i += 4; // How many rotation keyframes } // argh! floats into two bytes!.. bad bad bad bad // After fighting with it for a while.. -1, to 1 seems to give the best results rotations = readKeys(data, ref i, rotationkeys, -1f, 1f); for (int iter = 0; iter < rotations.Length; iter++) { rotations[iter].W = 1f - (rotations[iter].key_element.X + rotations[iter].key_element.Y + rotations[iter].key_element.Z); } if (!BitConverter.IsLittleEndian) { positionkeys = Utils.BytesToInt(BinBVHUtil.EndianSwap(data, i, 4)); i += 4; // How many position keyframes } else { positionkeys = Utils.BytesToInt(data, i); i += 4; // How many position keyframes } // Read in position keyframes // argh! more floats into two bytes!.. *head desk* // After fighting with it for a while.. -5, to 5 seems to give the best results positions = readKeys(data, ref i, positionkeys, -5f, 5f); pJoint.rotationkeys = rotations; pJoint.positionkeys = positions; return pJoint; } /// <summary> /// Read Keyframes of a certain type /// advance i /// </summary> /// <param name="data">Animation Byte array</param> /// <param name="i">Offset in the Byte Array. Will be advanced</param> /// <param name="keycount">Number of Keyframes</param> /// <param name="min">Scaling Min to pass to the Uint16ToFloat method</param> /// <param name="max">Scaling Max to pass to the Uint16ToFloat method</param> /// <returns></returns> private binBVHJointKey[] readKeys(byte[] data, ref int i, int keycount, float min, float max) { float x; float y; float z; /* 0.o, Float values in Two bytes.. this is just wrong >:( 17 255 <-- Time Code 17 255 <-- Time Code 255 255 <-- X 127 127 <-- X 255 255 <-- Y 127 127 <-- Y 213 213 <-- Z 142 142 <---Z */ binBVHJointKey[] m_keys = new binBVHJointKey[keycount]; for (int j = 0; j < keycount; j++) { binBVHJointKey pJKey = new binBVHJointKey(); if (!BitConverter.IsLittleEndian) { pJKey.time = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, InPoint, OutPoint); i += 2; x = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, min, max); i += 2; y = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, min, max); i += 2; z = Utils.UInt16ToFloat(BinBVHUtil.EndianSwap(data, i, 2), 0, min, max); i += 2; } else { pJKey.time = Utils.UInt16ToFloat(data, i, InPoint, OutPoint); i += 2; x = Utils.UInt16ToFloat(data, i, min, max); i += 2; y = Utils.UInt16ToFloat(data, i, min, max); i += 2; z = Utils.UInt16ToFloat(data, i, min, max); i += 2; } pJKey.key_element = new Vector3(x, y, z); m_keys[j] = pJKey; } return m_keys; } } /// <summary> /// A Joint and it's associated meta data and keyframes /// </summary> public struct binBVHJoint { /// <summary> /// Name of the Joint. Matches the avatar_skeleton.xml in client distros /// </summary> public string Name; /// <summary> /// Joint Animation Override? Was the same as the Priority in testing.. /// </summary> public int Priority; /// <summary> /// Array of Rotation Keyframes in order from earliest to latest /// </summary> public binBVHJointKey[] rotationkeys; /// <summary> /// Array of Position Keyframes in order from earliest to latest /// This seems to only be for the Pelvis? /// </summary> public binBVHJointKey[] positionkeys; public void WriteBytesToStream(BinaryWriter iostream, float InPoint, float OutPoint) { iostream.Write(BinBVHUtil.WriteNullTerminatedString(Name)); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(Priority))); iostream.Write(BinBVHUtil.ES(Utils.IntToBytes(rotationkeys.Length))); for (int i=0;i<rotationkeys.Length;i++) { rotationkeys[i].WriteBytesToStream(iostream, InPoint, OutPoint, -1f, 1f); } iostream.Write(BinBVHUtil.ES(Utils.IntToBytes((positionkeys.Length)))); for (int i = 0; i < positionkeys.Length; i++) { positionkeys[i].WriteBytesToStream(iostream, InPoint, OutPoint, -256f, 256f); } } } /// <summary> /// A Joint Keyframe. This is either a position or a rotation. /// </summary> public struct binBVHJointKey { // Time in seconds for this keyframe. public float time; /// <summary> /// Either a Vector3 position or a Vector3 Euler rotation /// </summary> public Vector3 key_element; public float W; public void WriteBytesToStream(BinaryWriter iostream, float InPoint, float OutPoint, float min, float max) { iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(time, InPoint, OutPoint)))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(key_element.X, min, max)))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(key_element.Y, min, max)))); iostream.Write(BinBVHUtil.ES(Utils.UInt16ToBytes(BinBVHUtil.FloatToUInt16(key_element.Z, min, max)))); } } /// <summary> /// Poses set in the animation metadata for the hands. /// </summary> public enum HandPose : uint { Spread = 0, Relaxed = 1, Point_Both = 2, Fist = 3, Relaxed_Left = 4, Point_Left = 5, Fist_Left = 6, Relaxed_Right = 7, Point_Right = 8, Fist_Right = 9, Salute_Right = 10, Typing = 11, Peace_Right = 12 } public static class BinBVHUtil { public const float ONE_OVER_U16_MAX = 1.0f / UInt16.MaxValue; public static UInt16 FloatToUInt16(float val, float lower, float upper) { UInt16 uival = 0; //m_parentGroup.GetTimeDilation() * (float)ushort.MaxValue //0-1 // float difference = upper - lower; // we're trying to get a zero lower and modify all values equally so we get a percentage position if (lower > 0) { upper -= lower; val = val - lower; // start with 500 upper and 200 lower.. subtract 200 from the upper and the value } else //if (lower < 0 && upper > 0) { // double negative, 0 minus negative 5 is 5. upper += 0 - lower; lower += 0 - lower; val += 0 - lower; } if (upper == 0) val = 0; else { val /= upper; } uival = (UInt16)(val * UInt16.MaxValue); return uival; } /// <summary> /// Endian Swap /// Swaps endianness if necessary /// </summary> /// <param name="arr">Input array</param> /// <returns></returns> public static byte[] ES(byte[] arr) { if (!BitConverter.IsLittleEndian) Array.Reverse(arr); return arr; } public static byte[] EndianSwap(byte[] arr, int offset, int len) { byte[] bendian = new byte[offset + len]; Buffer.BlockCopy(arr, offset, bendian, 0, len); Array.Reverse(bendian); return bendian; } public static byte[] WriteNullTerminatedString(string str) { byte[] output = new byte[str.Length + 1]; Char[] chr = str.ToCharArray(); int i = 0; for (i = 0; i < chr.Length; i++) { output[i] = Convert.ToByte(chr[i]); } output[i] = Convert.ToByte('\0'); return output; } } } /* switch (jointname) { case "mPelvis": case "mTorso": case "mNeck": case "mHead": case "mChest": case "mHipLeft": case "mHipRight": case "mKneeLeft": case "mKneeRight": // XYZ->ZXY t = x; x = y; y = t; break; case "mCollarLeft": case "mCollarRight": case "mElbowLeft": case "mElbowRight": // YZX ->ZXY t = z; z = x; x = y; y = t; break; case "mWristLeft": case "mWristRight": case "mShoulderLeft": case "mShoulderRight": // ZYX->ZXY t = y; y = z; z = t; break; case "mAnkleLeft": case "mAnkleRight": // XYZ ->ZXY t = x; x = z; z = y; y = t; break; } */
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNet.Authorization; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Mvc; using Microsoft.AspNet.Mvc.Rendering; using Microsoft.Data.Entity; using Microsoft.Extensions.Logging; using FPS.Models; using FPS.Services; using FPS.ViewModels.Account; namespace FPS.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<UserAccount> _userManager; private readonly SignInManager<UserAccount> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<UserAccount> userManager, SignInManager<UserAccount> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new UserAccount { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // "Please confirm your account by clicking this link: <a href=\"" + callbackUrl + "\">link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToAction(nameof(HomeController.Index), "Home"); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null) { var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.ExternalPrincipal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (User.IsSignedIn()) { return RedirectToAction(nameof(ManageController.Index), "Manage"); } if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new UserAccount { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // "Please reset your password by clicking here: <a href=\"" + callbackUrl + "\">link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError("", "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private async Task<UserAccount> GetCurrentUserAsync() { return await _userManager.FindByIdAsync(HttpContext.User.GetUserId()); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
//---------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. //---------------------------------------------------------------- namespace System.Activities.Presentation.Internal.PropertyEditing { using System; using System.Windows; using System.Windows.Controls; using System.Windows.Media; // <summary> // PropertyPanel is a simplified version of a horizontal StackPanel that we use for PropertyContainer // visuals in lieu of Grid, which was too heavy-weight and bogging down perf. It exposes a property, // LastChildWidth, that specifies the forced width of the last child in the panel. All other // children are stacked on the left and eat up the remainder of the space left on the panel. // // The panel also deals with drawing compartments for itself and the last child and it deals with // visually nesting sub-properties based on their depth (Level). // </summary> internal class PropertyPanel : Panel { // LastChildWidth DP public static readonly DependencyProperty OutlineBrushProperty = DependencyProperty.Register("OutlineBrush", typeof(Brush), typeof(PropertyPanel), new FrameworkPropertyMetadata((Brush)null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender)); public static readonly DependencyProperty SelectionBrushProperty = DependencyProperty.Register("SelectionBrush", typeof(Brush), typeof(PropertyPanel), new FrameworkPropertyMetadata((Brush)null, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.SubPropertiesDoNotAffectRender)); public static readonly DependencyProperty OutlineThicknessProperty = DependencyProperty.Register("OutlineThickness", typeof(double), typeof(PropertyPanel), new FrameworkPropertyMetadata((double)1, FrameworkPropertyMetadataOptions.AffectsRender)); public static readonly DependencyProperty IgnoreFirstChildBackgroundProperty = DependencyProperty.Register("IgnoreFirstChildBackground", typeof(bool), typeof(PropertyPanel), new FrameworkPropertyMetadata( false, FrameworkPropertyMetadataOptions.AffectsRender)); public static DependencyProperty LastChildWidthProperty = DependencyProperty.Register( "LastChildWidth", typeof(double), typeof(PropertyPanel), new FrameworkPropertyMetadata( (double)0, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender)); public static DependencyProperty LevelProperty = DependencyProperty.Register( "Level", typeof(int), typeof(PropertyPanel), new FrameworkPropertyMetadata( (int)0, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); public static DependencyProperty LevelIndentProperty = DependencyProperty.Register( "LevelIndent", typeof(double), typeof(PropertyPanel), new FrameworkPropertyMetadata( (double)13, FrameworkPropertyMetadataOptions.AffectsArrange | FrameworkPropertyMetadataOptions.AffectsMeasure)); // <summary> // Gets or sets the pixel width of the last child added into this panel. // </summary> public double LastChildWidth { get { return (double)this.GetValue(LastChildWidthProperty); } set { this.SetValue(LastChildWidthProperty, value); } } // Level DP // <summary> // Gets or sets the indentation level for the first child in this panel. Levels are // measured in ints, with 0 = no indentation, 1 = 1st sub-property, ... // The actual amount of space taken up by each level is controled by LevelIndent property // </summary> public int Level { get { return (int)this.GetValue(LevelProperty); } set { this.SetValue(LevelProperty, value); } } // LevelIndent DP // <summary> // Gets or sets the pixel width that the first child is indented for each level that // it belongs to // </summary> public double LevelIndent { get { return (double)this.GetValue(LevelIndentProperty); } set { this.SetValue(LevelIndentProperty, value); } } // OutlineBrush DP // <summary> // Gets or sets the line brush to use for the panel compartments // </summary> public Brush OutlineBrush { get { return (Brush)GetValue(OutlineBrushProperty); } set { SetValue(OutlineBrushProperty, value); } } // SelectionBrush DP // <summary> // Gets or sets the brush to be used as the background for everything but the last // element in the panel // </summary> public Brush SelectionBrush { get { return (Brush)GetValue(SelectionBrushProperty); } set { SetValue(SelectionBrushProperty, value); } } // OutlineThickness DP // <summary> // Gets or sets the line thickness for the panel compartments (not as Thickness, but // instead as a simple double) // </summary> public double OutlineThickness { get { return (double)GetValue(OutlineThicknessProperty); } set { SetValue(OutlineThicknessProperty, value); } } // IgnoreFirstChildBackground DP // <summary> // Gets or sets a flag indicating whether the SelectionBrush background should // or should not be applied to the first child of the panel // </summary> public bool IgnoreFirstChildBackground { get { return (bool)GetValue(IgnoreFirstChildBackgroundProperty); } set { SetValue(IgnoreFirstChildBackgroundProperty, value); } } // Stacks the children to the left, leaving LastChildWidth amount of space for the last child protected override Size MeasureOverride(Size availableSize) { double lastChildWidth = Math.Max(0, this.LastChildWidth); double indent = this.LevelIndent * this.Level; double availableWidth = Math.Max(0, availableSize.Width - lastChildWidth - indent); int childrenCount = InternalChildren.Count; int lastIndex = childrenCount - 1; Size actualSize = new Size(); for (int i = 0; i < childrenCount; i++) { UIElement child = InternalChildren[i]; if (i == lastIndex) { InternalChildren[i].Measure(new Size(lastChildWidth, availableSize.Height)); } else { InternalChildren[i].Measure(new Size(availableWidth, availableSize.Height)); } availableWidth -= child.DesiredSize.Width; //Compute the actual size for the propertypanel actualSize.Height = Math.Max(actualSize.Height, child.DesiredSize.Height); actualSize.Width += child.DesiredSize.Width; } return actualSize; } // Stacks the children to the left, leaving LastChildWidth amount of space for the last child protected override Size ArrangeOverride(Size finalSize) { double lastChildWidth = Math.Max(0, this.LastChildWidth); double indent = this.LevelIndent * this.Level; double availableWidth = Math.Max(0, finalSize.Width - lastChildWidth - indent); double left = indent; int childrenCount = InternalChildren.Count; int lastIndex = childrenCount - 1; for (int i = 0; i < childrenCount; i++) { UIElement child = InternalChildren[i]; double desiredWidth = child.DesiredSize.Width; if (i == lastIndex) { child.Arrange(new Rect(Math.Max(0, finalSize.Width - lastChildWidth), 0, lastChildWidth, finalSize.Height)); } else { child.Arrange(new Rect(left, 0, Math.Min(desiredWidth, availableWidth), finalSize.Height)); } left += desiredWidth; availableWidth -= desiredWidth; availableWidth = Math.Max(0, availableWidth); } return finalSize; } // Custom renders compartments and dividers protected override void OnRender(DrawingContext dc) { Size renderSize = this.RenderSize; Brush outlineBrush = this.OutlineBrush; double outlineThickness = this.OutlineThickness; double halfThickness = outlineThickness / 2.0; double dividerRight = Math.Max(0, this.LastChildWidth); double dividerLeft = renderSize.Width - dividerRight - outlineThickness; Brush selectionBrush = this.SelectionBrush; if (selectionBrush != null) { bool ignoreFirstChildBackground = this.IgnoreFirstChildBackground; double firstChildWidth = 0; if (ignoreFirstChildBackground && this.Children.Count > 0) { firstChildWidth = this.Children[0].RenderSize.Width; } dc.DrawRectangle(selectionBrush, null, new Rect( firstChildWidth, 0, Math.Max(dividerLeft - firstChildWidth, 0), renderSize.Height)); } base.OnRender(dc); // Use Guidelines to avoid anti-aliasing (fuzzy border lines) dc.PushGuidelineSet(new GuidelineSet( // X coordinates for guidelines (vertical lines) new double[] { 0, dividerLeft, dividerLeft + outlineThickness, renderSize.Width - outlineThickness, renderSize.Width }, // Y coordinates for guidelines (horizontal lines) new double[] { 0, renderSize.Height - outlineThickness, renderSize.Height })); Pen outlinePen = new Pen(outlineBrush, outlineThickness); // Bottom edge dc.DrawLine( outlinePen, new Point(0, renderSize.Height - halfThickness), new Point(renderSize.Width, renderSize.Height - halfThickness)); // Top edge dc.DrawLine( outlinePen, new Point(0, 0 - halfThickness), new Point(renderSize.Width, 0 - halfThickness)); // Right edge dc.DrawLine( outlinePen, new Point(renderSize.Width - halfThickness, 0), new Point(renderSize.Width - halfThickness, renderSize.Height)); // Divider dc.DrawLine( outlinePen, new Point(dividerLeft + halfThickness, 0), new Point(dividerLeft + halfThickness, renderSize.Height)); dc.Pop(); } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.SqlServer { using System.Data.Common; using System.Data.Entity.Core.Common; using System.Data.Entity.Infrastructure; using System.Data.Entity.Infrastructure.DependencyResolution; using System.Data.Entity.Infrastructure.Interception; using System.Data.Entity.Migrations.History; using System.Data.SqlClient; using System.Reflection; using Xunit; public class DatabaseExistsInInitializerTests : FunctionalTestBase, IDisposable { private const string Password = "Password1"; private const string NormalUser = "EFGooseWithDbVisibility"; private const string ImpairedUser = "EFGooseWithoutDbVisibility"; private const string DatabaseWithMigrationHistory = "MigratoryGoose"; private const string DatabaseWithoutMigrationHistory = "NonMigratoryGoose"; private const string DatabaseOutOfDate = "MigratedGoose"; public DatabaseExistsInInitializerTests() { EnsureDatabaseExists(DatabaseWithMigrationHistory, drophistoryTable: false, outOfDate: false); EnsureUserExists(DatabaseWithMigrationHistory, NormalUser, allowMasterQuery: true); EnsureUserExists(DatabaseWithMigrationHistory, ImpairedUser, allowMasterQuery: false); EnsureDatabaseExists(DatabaseWithoutMigrationHistory, drophistoryTable: true, outOfDate: false); EnsureUserExists(DatabaseWithoutMigrationHistory, NormalUser, allowMasterQuery: true); EnsureUserExists(DatabaseWithoutMigrationHistory, ImpairedUser, allowMasterQuery: false); EnsureDatabaseExists(DatabaseOutOfDate, drophistoryTable: false, outOfDate: true); EnsureUserExists(DatabaseOutOfDate, NormalUser, allowMasterQuery: true); EnsureUserExists(DatabaseOutOfDate, ImpairedUser, allowMasterQuery: false); MutableResolver.AddResolver<IManifestTokenResolver>( new SingletonDependencyResolver<IManifestTokenResolver>(new BasicManifestTokenResolver())); } private static void AssertDoesNotExist(string connectionString) { using (var context = ExistsContext.Create(connectionString)) { context.Database.Initialize(force: false); Assert.True(context.InitializerCalled); Assert.False(context.Exists); } } public void Dispose() { context.Database.Initialize(force: false); Assert.True(context.InitializerCalled); Assert.True(context.Exists); MutableResolver.ClearResolvers(); } [Fact] public void Exists_check_with_master_persist_info() { ExistsTest(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true); } [Fact] public void Exists_check_with_master_no_persist_info() { ExistsTest(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false); } [Fact] public void Exists_check_without_master_persist_info() { ExistsTestNoMaster(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true); } [Fact] public void Exists_check_without_master_no_persist_info() { ExistsTestNoMaster(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_persist_info() { ExistsTest(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: true); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_no_persist_info() { ExistsTest(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: false); } [Fact] public void Exists_check_with_master_persist_info_no_MigrationHistory() { ExistsTest(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true); } [Fact] public void Exists_check_with_master_no_persist_info_no_MigrationHistory() { ExistsTest(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false); } [Fact] public void Exists_check_without_master_persist_info_no_MigrationHistory() { ExistsTestNoMaster(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true); } [Fact] public void Exists_check_without_master_no_persist_info_no_MigrationHistory() { ExistsTestNoMaster(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_persist_info_no_MigrationHistory() { ExistsTest(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: true); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_no_persist_info_no_MigrationHistory() { ExistsTest(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: false); } [Fact] public void Exists_check_with_master_persist_info_out_of_date() { ExistsTest(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true); } [Fact] public void Exists_check_with_master_no_persist_info_out_of_date() { ExistsTest(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false); } [Fact] public void Exists_check_without_master_persist_info_out_of_date() { ExistsTestNoMaster(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true); } [Fact] public void Exists_check_without_master_no_persist_info_out_of_date() { ExistsTestNoMaster(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_persist_info_out_of_date() { ExistsTest(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: true); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_no_persist_info_out_of_date() { ExistsTest(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: false); } [Fact] public void Not_exists_check_with_master_persist_info() { NotExistsTest(NormalUser, persistSecurityInfo: true); } [Fact] public void Not_exists_check_with_master_no_persist_info() { NotExistsTest(NormalUser, persistSecurityInfo: false); } [Fact] public void Not_exists_check_without_master_persist_info() { NotExistsTestNoMaster(NormalUser, persistSecurityInfo: true); } [Fact] public void Not_exists_check_without_master_no_persist_info() { NotExistsTestNoMaster(NormalUser, persistSecurityInfo: false); } [Fact] // CodePlex 2113 public void Not_exists_check_with_no_master_query_persist_info() { NotExistsTest(ImpairedUser, persistSecurityInfo: true); } [Fact] // CodePlex 2113 public void Not_exists_check_with_no_master_query_no_persist_info() { NotExistsTest(ImpairedUser, persistSecurityInfo: false); } [Fact] // CodePlex 2068 public void Exists_check_with_master_persist_info_open_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_with_master_no_persist_info_open_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_without_master_persist_info_open_connection() { ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_without_master_no_persist_info_open_connection() { ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true); } [Fact] // CodePlex 2113, 2068 public void Exists_check_with_no_master_query_persist_info_open_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2113, 2068 public void Exists_check_with_no_master_query_no_persist_info_open_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: true); } [Fact] public void Exists_check_with_master_persist_info_closed_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Exists_check_with_master_no_persist_info_closed_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] public void Exists_check_without_master_persist_info_closed_connection() { ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Exists_check_without_master_no_persist_info_closed_connection() { ExistsTestNoMasterWithConnection(DatabaseWithMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_persist_info_closed_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_no_persist_info_closed_connection() { ExistsTestWithConnection(DatabaseWithMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: false); } [Fact] // CodePlex 2068 public void Exists_check_with_master_persist_info_open_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_with_master_no_persist_info_open_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_without_master_persist_info_open_connection_no_MigrationHistory() { ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_without_master_no_persist_info_open_connection_no_MigrationHistory() { ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: true); } [Fact] // CodePlex 2113, 2068 public void Exists_check_with_no_master_query_persist_info_open_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2113, 2068 public void Exists_check_with_no_master_query_no_persist_info_open_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: true); } [Fact] public void Exists_check_with_master_persist_info_closed_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Exists_check_with_master_no_persist_info_closed_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] public void Exists_check_without_master_persist_info_closed_connection_no_MigrationHistory() { ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Exists_check_without_master_no_persist_info_closed_connection_no_MigrationHistory() { ExistsTestNoMasterWithConnection(DatabaseWithoutMigrationHistory, NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_persist_info_closed_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: true, openConnection: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_no_persist_info_closed_connection_no_MigrationHistory() { ExistsTestWithConnection(DatabaseWithoutMigrationHistory, ImpairedUser, persistSecurityInfo: false, openConnection: false); } [Fact] // CodePlex 2068 public void Exists_check_with_master_persist_info_open_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_with_master_no_persist_info_open_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_without_master_persist_info_open_connection_out_of_date() { ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2068 public void Exists_check_without_master_no_persist_info_open_connection_out_of_date() { ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: true); } [Fact] // CodePlex 2113, 2068 public void Exists_check_with_no_master_query_persist_info_open_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: true, openConnection: true); } [Fact] // CodePlex 2113, 2068 public void Exists_check_with_no_master_query_no_persist_info_open_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: false, openConnection: true); } [Fact] public void Exists_check_with_master_persist_info_closed_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Exists_check_with_master_no_persist_info_closed_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] public void Exists_check_without_master_persist_info_closed_connection_out_of_date() { ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Exists_check_without_master_no_persist_info_closed_connection_out_of_date() { ExistsTestNoMasterWithConnection(DatabaseOutOfDate, NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_persist_info_closed_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: true, openConnection: false); } [Fact] // CodePlex 2113 public void Exists_check_with_no_master_query_no_persist_info_closed_connection_out_of_date() { ExistsTestWithConnection(DatabaseOutOfDate, ImpairedUser, persistSecurityInfo: false, openConnection: false); } [Fact] public void Not_exists_check_with_master_persist_info_closed_connection() { NotExistsTestWithConnection(NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Not_exists_check_with_master_no_persist_info_closed_connection() { NotExistsTestWithConnection(NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] public void Not_exists_check_without_master_persist_info_closed_connection() { NotExistsTestNoMasterWithConnection(NormalUser, persistSecurityInfo: true, openConnection: false); } [Fact] public void Not_exists_check_without_master_no_persist_info_closed_connection() { NotExistsTestNoMasterWithConnection(NormalUser, persistSecurityInfo: false, openConnection: false); } [Fact] // CodePlex 2113 public void Not_exists_check_with_no_master_query_persist_info_closed_connection() { NotExistsTestWithConnection(ImpairedUser, persistSecurityInfo: true, openConnection: false); } [Fact] // CodePlex 2113 public void Not_exists_check_with_no_master_query_no_persist_info_closed_connection() { NotExistsTestWithConnection(ImpairedUser, persistSecurityInfo: false, openConnection: false); } private void ExistsTest(string databaseName, string username, bool persistSecurityInfo) { AssertExists( databaseName, ModelHelpers.SimpleConnectionStringWithCredentials( databaseName, username, Password, persistSecurityInfo)); } private void ExistsTestNoMaster(string databaseName, string username, bool persistSecurityInfo) { var interceptor = new NoMasterInterceptor(); try { DbInterception.Add(interceptor); AssertExists( databaseName, ModelHelpers.SimpleConnectionStringWithCredentials( databaseName, username, Password, persistSecurityInfo)); } finally { DbInterception.Remove(interceptor); } } private void NotExistsTest(string username, bool persistSecurityInfo) { AssertDoesNotExist( ModelHelpers.SimpleConnectionStringWithCredentials( "IDoNotExist", username, Password, persistSecurityInfo)); } private void NotExistsTestNoMaster(string username, bool persistSecurityInfo) { var interceptor = new NoMasterInterceptor(); try { DbInterception.Add(interceptor); AssertDoesNotExist( ModelHelpers.SimpleConnectionStringWithCredentials( "IDoNotExist", username, Password, persistSecurityInfo)); } finally { DbInterception.Remove(interceptor); } } private void ExistsTestWithConnection(string databaseName, string username, bool persistSecurityInfo, bool openConnection) { AssertExistsWithConnection( databaseName, ModelHelpers.SimpleConnectionStringWithCredentials( databaseName, username, Password, persistSecurityInfo), openConnection); } private void ExistsTestNoMasterWithConnection(string databaseName, string username, bool persistSecurityInfo, bool openConnection) { var interceptor = new NoMasterInterceptor(); try { DbInterception.Add(interceptor); AssertExistsWithConnection( databaseName, ModelHelpers.SimpleConnectionStringWithCredentials( databaseName, username, Password, persistSecurityInfo), openConnection); } finally { DbInterception.Remove(interceptor); } } private void NotExistsTestWithConnection(string username, bool persistSecurityInfo, bool openConnection) { AssertDoesNotExistWithConnection( ModelHelpers.SimpleConnectionStringWithCredentials( "IDoNotExist", username, Password, persistSecurityInfo), openConnection); } private void NotExistsTestNoMasterWithConnection(string username, bool persistSecurityInfo, bool openConnection) { var interceptor = new NoMasterInterceptor(); try { DbInterception.Add(interceptor); AssertDoesNotExistWithConnection( ModelHelpers.SimpleConnectionStringWithCredentials( "IDoNotExist", username, Password, persistSecurityInfo), openConnection); } finally { DbInterception.Remove(interceptor); } } private static void AssertExists(string databaseName, string connectionString) { using (var context = ExistsContext.Create(connectionString)) { AssertExists(databaseName, context); } } private static void AssertExistsWithConnection(string databaseName, string connectionString, bool openConnection) { using (var connection = new SqlConnection(connectionString)) { if (openConnection) { connection.Open(); } using (var context = ExistsContext.Create(connection)) { AssertExists(databaseName, context); } connection.Close(); } } private static void AssertExists(string databaseName, ExistsContext context) { context.Database.Initialize(force: false); Assert.True(context.InitializerCalled); Assert.True(context.Exists); if (databaseName == DatabaseWithMigrationHistory) { context.SetDropCreateIfNotExists(); context.Database.Initialize(force: true); context.Database.Initialize(force: true); context.SetDropCreateIfModelChanges(); context.Database.Initialize(force: true); context.Database.Initialize(force: true); } else if (databaseName == DatabaseWithoutMigrationHistory) { context.SetDropCreateIfNotExists(); context.Database.Initialize(force: true); context.Database.Initialize(force: true); context.SetDropCreateIfModelChanges(); Assert.Throws<NotSupportedException>(() => context.Database.Initialize(force: true)) .ValidateMessage("Database_NoDatabaseMetadata"); } else if (databaseName == DatabaseOutOfDate) { context.SetDropCreateIfNotExists(); Assert.Throws<InvalidOperationException>(() => context.Database.Initialize(force: true)) .ValidateMessage("DatabaseInitializationStrategy_ModelMismatch", context.GetType().Name); } } private static void AssertDoesNotExistWithConnection(string connectionString, bool openConnection) { using (var connection = new SqlConnection(connectionString)) { if (openConnection) { connection.Open(); } using (var context = ExistsContext.Create(connection)) { context.Database.Initialize(force: false); Assert.True(context.InitializerCalled); Assert.False(context.Exists); } connection.Close(); } } private static void EnsureDatabaseExists(string databaseName, bool drophistoryTable, bool outOfDate) { using (var context = outOfDate ? new ExistsContextModelChanged(SimpleConnectionString(databaseName)) : new ExistsContext(SimpleConnectionString(databaseName))) { if (!context.Database.Exists()) { context.Database.Create(); if (drophistoryTable) { context.Database.ExecuteSqlCommand("DROP TABLE " + HistoryContext.DefaultTableName); } else { context.Database.ExecuteSqlCommand(@"UPDATE __MigrationHistory SET ContextKey = 'TestContextKey'"); } } } } private void EnsureUserExists(string databaseName, string username, bool allowMasterQuery) { using (var connection = new SqlConnection(SimpleConnectionString("master"))) { connection.Open(); var loginExists = ExecuteScalarReturnsOne( connection, "SELECT COUNT(*) FROM sys.sql_logins WHERE name = N'{0}'", username); if (!loginExists) { ExecuteNonQuery(connection, "CREATE LOGIN [{0}] WITH PASSWORD=N'{1}'", username, Password); } var userExists = ExecuteScalarReturnsOne( connection, "SELECT COUNT(*) FROM sys.sysusers WHERE name = N'{0}'", username); if (!userExists) { ExecuteNonQuery(connection, "CREATE USER [{0}] FROM LOGIN [{0}]", username); if (!allowMasterQuery) { ExecuteNonQuery(connection, "DENY VIEW ANY DATABASE TO [{0}]", username); } } connection.Close(); } using (var connection = new SqlConnection(SimpleConnectionString(databaseName))) { connection.Open(); var userExists = ExecuteScalarReturnsOne( connection, "SELECT COUNT(*) FROM sys.sysusers WHERE name = N'{0}'", username); if (!userExists) { ExecuteNonQuery(connection, "CREATE USER [{0}] FROM LOGIN [{0}]", username); ExecuteNonQuery(connection, "GRANT VIEW DEFINITION TO [{0}]", username); ExecuteNonQuery(connection, "GRANT SELECT TO [{0}]", username); } connection.Close(); } } private static void ExecuteNonQuery(SqlConnection connection, string commandText, params object[] args) { using (var command = connection.CreateCommand()) { command.CommandText = string.Format(commandText, args); command.ExecuteNonQuery(); } } private static bool ExecuteScalarReturnsOne(SqlConnection connection, string commandText, params object[] args) { using (var command = connection.CreateCommand()) { try { command.CommandText = string.Format(commandText, args); return (int)command.ExecuteScalar() == 1; } catch (Exception) { return false; } } } public class NoMasterInterceptor : IDbConnectionInterceptor { public void BeginningTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext) { } public void BeganTransaction(DbConnection connection, BeginTransactionInterceptionContext interceptionContext) { } public void Closing(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { } public void Closed(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { } public void ConnectionStringGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void ConnectionStringGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void ConnectionStringSetting( DbConnection connection, DbConnectionPropertyInterceptionContext<string> interceptionContext) { } public void ConnectionStringSet(DbConnection connection, DbConnectionPropertyInterceptionContext<string> interceptionContext) { } public void ConnectionTimeoutGetting(DbConnection connection, DbConnectionInterceptionContext<int> interceptionContext) { } public void ConnectionTimeoutGot(DbConnection connection, DbConnectionInterceptionContext<int> interceptionContext) { } public void DatabaseGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void DatabaseGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void DataSourceGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void DataSourceGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void Disposing(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { } public void Disposed(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { } public void EnlistingTransaction(DbConnection connection, EnlistTransactionInterceptionContext interceptionContext) { } public void EnlistedTransaction(DbConnection connection, EnlistTransactionInterceptionContext interceptionContext) { } public void Opening(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { if (connection.Database == "master") { interceptionContext.Exception = (SqlException)Activator.CreateInstance( typeof(SqlException), BindingFlags.Instance | BindingFlags.NonPublic, null, new object[] { "No master for you!", null, null, Guid.NewGuid() }, null); } } public void Opened(DbConnection connection, DbConnectionInterceptionContext interceptionContext) { } public void ServerVersionGetting(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void ServerVersionGot(DbConnection connection, DbConnectionInterceptionContext<string> interceptionContext) { } public void StateGetting(DbConnection connection, DbConnectionInterceptionContext<ConnectionState> interceptionContext) { } public void StateGot(DbConnection connection, DbConnectionInterceptionContext<ConnectionState> interceptionContext) { } } public class ExistsContext : DbContext { public bool InitializerCalled { get; set; } public bool Exists { get; set; } private static int _typeCount; static ExistsContext() { Database.SetInitializer<ExistsContext>(null); } public ExistsContext(string connectionString) : base(connectionString) { SetContextKey(); } public ExistsContext(DbConnection connection) : base(connection, contextOwnsConnection: false) { SetContextKey(); } private void SetContextKey() { var internalContext = typeof(DbContext) .GetField("_internalContext", BindingFlags.Instance | BindingFlags.NonPublic) .GetValue(this); internalContext.GetType().BaseType .GetField("_defaultContextKey", BindingFlags.Instance | BindingFlags.NonPublic) .SetValue(internalContext, "TestContextKey"); } public DbSet<ExistsEntity> Entities { get; set; } public static ExistsContext Create(string connectionString) { return (ExistsContext)Activator.CreateInstance(GetNewContxtType(), connectionString); } public static ExistsContext Create(DbConnection connection) { return (ExistsContext)Activator.CreateInstance(GetNewContxtType(), connection); } private static Type GetNewContxtType() { var typeNumber = _typeCount++; var typeBits = new Type[8]; for (var bit = 0; bit < 8; bit++) { typeBits[bit] = ((typeNumber & 1) == 1) ? typeof(int) : typeof(string); typeNumber >>= 1; } return typeof(ExistsContext<>).MakeGenericType(typeof(Tuple<,,,,,,,>).MakeGenericType(typeBits)); } public virtual void SetDropCreateIfNotExists() { throw new NotImplementedException(); } public virtual void SetDropCreateIfModelChanges() { throw new NotImplementedException(); } } public class ExistsContextModelChanged : ExistsContext { static ExistsContextModelChanged() { Database.SetInitializer<ExistsContextModelChanged>(null); } public ExistsContextModelChanged(string connectionString) : base(connectionString) { } public ExistsContextModelChanged(DbConnection connection) : base(connection) { } public DbSet<ModelChangedEntity> ModelChangedEntities { get; set; } } public class ExistsContext<T> : ExistsContext { private static readonly ExistsInitializer<T> _initializer = new ExistsInitializer<T>(); private static readonly CreateDatabaseIfNotExists<ExistsContext<T>> _dropCreateIfNotExists = new CreateDatabaseIfNotExists<ExistsContext<T>>(); private static readonly DropCreateDatabaseIfModelChanges<ExistsContext<T>> _dropCreateIfModelChanges = new DropCreateDatabaseIfModelChanges<ExistsContext<T>>(); private static readonly DropCreateDatabaseAlways<ExistsContext<T>> _dropCreateAlways = new DropCreateDatabaseAlways<ExistsContext<T>>(); static ExistsContext() { Database.SetInitializer(_initializer); } public ExistsContext(string connectionString) : base(connectionString) { } public ExistsContext(DbConnection connection) : base(connection) { } public override void SetDropCreateIfNotExists() { Database.SetInitializer(_dropCreateIfNotExists); } public override void SetDropCreateIfModelChanges() { Database.SetInitializer(_dropCreateIfModelChanges); } } public class BasicManifestTokenResolver : IManifestTokenResolver { public string ResolveManifestToken(DbConnection connection) { return DbProviderServices.GetProviderServices(connection).GetProviderManifestToken(connection); } } public class ExistsInitializer<T> : IDatabaseInitializer<ExistsContext<T>> { public void InitializeDatabase(ExistsContext<T> context) { context.InitializerCalled = true; context.Exists = context.Database.Exists(); } } public class ExistsEntity { public int Id { get; set; } } public class ModelChangedEntity { public int Id { get; set; } } } }
using System; using System.Threading; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using Mono.Unix.Native; namespace Manos.IO.Managed { class Context : Manos.IO.Context { private AutoResetEvent pulse; private Queue<Action> outstanding; private List<PrepareWatcher> prepares; private List<CheckWatcher> checks; private List<IdleWatcher> idles; private List<AsyncWatcher> asyncs; private List<TimerWatcher> timers; private volatile bool running; private object syncRoot = new object (); public Context () { pulse = new AutoResetEvent (false); outstanding = new Queue<Action> (); asyncs = new List<AsyncWatcher> (); prepares = new List<PrepareWatcher> (); checks = new List<CheckWatcher> (); idles = new List<IdleWatcher> (); timers = new List<TimerWatcher> (); } internal void Enqueue (Action cb) { if (cb == null) throw new ArgumentNullException ("cb"); lock (syncRoot) { outstanding.Enqueue (cb); } pulse.Set (); } internal void Remove (AsyncWatcher async) { asyncs.Remove (async); } internal void Remove (PrepareWatcher prepare) { prepares.Remove (prepare); } internal void Remove (CheckWatcher check) { checks.Remove (check); } internal void Remove (IdleWatcher check) { idles.Remove (check); } internal void Remove (TimerWatcher timer) { timers.Remove (timer); } protected override void Dispose (bool disposing) { if (pulse != null) { pulse.Dispose (); Dispose (ref checks); Dispose (ref prepares); Dispose (ref idles); Dispose (ref timers); outstanding = null; checks = null; prepares = null; idles = null; timers = null; } } static void Dispose<T> (ref List<T> items) where T : IBaseWatcher { var localItems = items; items = new List<T> (); foreach (var item in localItems) { item.Dispose (); } } public override void Start () { running = true; while (running) { RunOnce (); } } public override void RunOnce () { pulse.WaitOne (); RunOnceNonblocking (); } public override void RunOnceNonblocking () { foreach (var prep in prepares.ToArray ()) { prep.Invoke (); } int count = 0; lock (this) { count = outstanding.Count; } while (count-- > 0) { Action cb; lock (this) { cb = outstanding.Dequeue (); } cb (); } foreach (var idle in idles.ToArray ()) { idle.Invoke (); pulse.Set (); } foreach (var check in checks.ToArray ()) { check.Invoke (); } } public override void Stop () { running = false; } public override IAsyncWatcher CreateAsyncWatcher (Action cb) { var result = new AsyncWatcher (this, cb); asyncs.Add (result); return result; } public override ICheckWatcher CreateCheckWatcher (Action cb) { var result = new CheckWatcher (this, cb); checks.Add (result); return result; } public override IIdleWatcher CreateIdleWatcher (Action cb) { var result = new IdleWatcher (this, cb); idles.Add (result); return result; } public override IPrepareWatcher CreatePrepareWatcher (Action cb) { var result = new PrepareWatcher (this, cb); prepares.Add (result); return result; } public override ITimerWatcher CreateTimerWatcher (TimeSpan timeout, Action cb) { return CreateTimerWatcher (timeout, TimeSpan.Zero, cb); } public override ITimerWatcher CreateTimerWatcher (TimeSpan timeout, TimeSpan repeat, Action cb) { var result = new TimerWatcher (this, cb, timeout, repeat); timers.Add (result); return result; } public override Manos.IO.ITcpSocket CreateTcpSocket (AddressFamily addressFamily) { return new TcpSocket (this, addressFamily); } public override ITcpServerSocket CreateTcpServerSocket(AddressFamily addressFamily) { return new TcpSocket (this, addressFamily); } public override Manos.IO.ITcpSocket CreateSecureSocket (string certFile, string keyFile) { throw new NotSupportedException (); } public override IByteStream OpenFile (string fileName, OpenMode openMode, int blockSize) { FileAccess access; switch (openMode) { case OpenMode.Read: access = FileAccess.Read; break; case OpenMode.ReadWrite: access = FileAccess.ReadWrite; break; case OpenMode.Write: access = FileAccess.Write; break; default: throw new ArgumentException ("openMode"); } var fs = new System.IO.FileStream (fileName, FileMode.Open, access, FileShare.ReadWrite, blockSize, true); return new FileStream (this, fs, blockSize); } public override IByteStream CreateFile (string fileName, int blockSize) { var fs = System.IO.File.Create (fileName); return new FileStream (this, fs, blockSize); } public override Manos.IO.IUdpSocket CreateUdpSocket (AddressFamily family) { return new UdpSocket (this, family); } } }
using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace WebApplication2 { /// <summary> /// Summary description for frmAddProcedure. /// </summary> public partial class frmUpdBudget : System.Web.UI.Page { private static string strURL = System.Configuration.ConfigurationSettings.AppSettings["local_url"]; private static string strDB = System.Configuration.ConfigurationSettings.AppSettings["local_db"]; public SqlConnection epsDbConn = new SqlConnection(strDB); /*private int GetIndexOfFY (string s) { return (lstFY.Items.IndexOf (lstFY.Items.FindByValue(s))); } private int GetIndexOfFunds (string s) { return (lstFunds.Items.IndexOf (lstFunds.Items.FindByValue(s))); } private int GetIndexOfType (string s) { return (lstType.Items.IndexOf (lstType.Items.FindByValue(s))); } private int GetIndexOfVisibility (string s) { return (lstVisibility.Items.IndexOf (lstVisibility.Items.FindByValue(s))); } */ private int GetIndexOfStatus(string s) { return (lstStatus.Items.IndexOf(lstStatus.Items.FindByValue(s))); } private int GetIndexOfCurr(string s) { return (lstCurr.Items.IndexOf(lstCurr.Items.FindByValue(s))); } private int GetIndexOfFunds(string s) { return (lstFunds.Items.IndexOf(lstFunds.Items.FindByValue(s))); } protected void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { btnAction.Text = Session["Action"].ToString(); loadCurr(); if (Session["MgrOption"].ToString() == "Budget") { loadFunds(); lstFY.Visible = true; lblFunction.Text = Session["Action"].ToString() + " Budget"; if (Session["Action"].ToString() == "Update") { loadData2(); } else { loadFY(); lblName.Visible = false; txtName.Visible = false; } } else { lblFunction.Text = Session["Action"].ToString() + " Fund"; lblStartDate.Visible = true; txtStartDate.Visible = true; lblEndDate.Visible = true; txtEndDate.Visible = true; lblFY.Visible = false; lstFY.Visible = false; lblName.Text = "Source of Funds Name"; txtName.Text = ""; txtAmt.Text = ""; lblCurr.Text = "Fund Currency"; lstCurr.Visible = true; lstFunds.Visible = false; lblFunds.Visible = false; lblStart.Visible = true; lblEnd.Visible = true; loadCurr(); if (Session["Action"].ToString() == "Update") { loadData1(); } } } } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { } #endregion private void loadData1() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveFund"; cmd.Parameters.Add("@FundsId", SqlDbType.Int); cmd.Parameters["@FundsId"].Value = Session["FundsId"].ToString(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Fund"); txtName.Text = ds.Tables["Fund"].Rows[0][0].ToString(); lstStatus.SelectedIndex = GetIndexOfStatus(ds.Tables["Fund"].Rows[0][1].ToString()); lstCurr.SelectedIndex = GetIndexOfCurr(ds.Tables["Fund"].Rows[0][2].ToString()); txtAmt.Text = ds.Tables["Fund"].Rows[0][4].ToString(); txtStartDate.Text = ds.Tables["Fund"].Rows[0][5].ToString(); txtEndDate.Text = ds.Tables["Fund"].Rows[0][6].ToString(); cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); //decimal.Parse(tbHours.Text, System.Globalization.NumberStyles.AllowDecimalPoint|System.Globalization.NumberStyles.AllowThousands); } private void loadData2() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveBudget"; cmd.Parameters.Add("@BudgetsId", SqlDbType.Int); cmd.Parameters["@BudgetsId"].Value = Session["BudgetsId"].ToString(); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Budget"); txtName.Text = ds.Tables["Budget"].Rows[0][0].ToString(); lstStatus.SelectedIndex = GetIndexOfStatus(ds.Tables["Budget"].Rows[0][1].ToString()); lstCurr.SelectedIndex = GetIndexOfCurr(ds.Tables["Budget"].Rows[0][2].ToString()); txtAmt.Text = ds.Tables["Budget"].Rows[0][3].ToString(); txtStartDate.Text = ds.Tables["Budget"].Rows[0][4].ToString(); txtEndDate.Text = ds.Tables["Budget"].Rows[0][5].ToString(); if (Session["Action"].ToString() == "Update") { lblFY.Visible=false; lstFY.Visible = false; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); //decimal.Parse(tbHours.Text, System.Globalization.NumberStyles.AllowDecimalPoint|System.Globalization.NumberStyles.AllowThousands); } private void loadFY() { DateTime dt = DateTime.Now; int i = dt.Year - 1; //txtFY.Text = i.ToString(); int j = 0; do { j++; i++; lstFY.Items.Add(i.ToString()); } while (j < 5); } /*private void loadBudStatus() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveBudStatus"; cmd.Parameters.Add("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value = Session["OrgId"].ToString(); cmd.Parameters.Add("@OrgIdP", SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value = Session["OrgIdP"].ToString(); cmd.Parameters.Add("@LicenseId", SqlDbType.Int); cmd.Parameters["@LicenseId"].Value = Session["LicenseId"].ToString(); cmd.Parameters.Add("@DomainId", SqlDbType.Int); cmd.Parameters["@DomainId"].Value = Session["DomainId"].ToString(); cmd.Parameters.Add("@BRS", SqlDbType.Int); cmd.Parameters["@BRS"].Value = Int32.Parse(Session["BRS"].ToString()); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "BudStatus"); lstStatus.DataSource = ds; lstStatus.DataMember = "BudStatus"; lstStatus.DataTextField = "Name"; lstStatus.DataValueField = "Id"; lstStatus.DataBind(); }*/ private void loadCurr() { SqlCommand cmd = new SqlCommand(); cmd.Connection = this.epsDbConn; cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveCurrencies"; DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "Currencies"); lstCurr.DataSource = ds; lstCurr.DataMember = "Currencies"; lstCurr.DataTextField = "Name"; lstCurr.DataValueField = "Id"; lstCurr.DataBind(); } private void loadFunds() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="fms_RetrieveFundsAll"; cmd.Parameters.Add ("@OrgId",SqlDbType.Int); cmd.Parameters["@OrgId"].Value=Session["OrgId"].ToString(); cmd.Parameters.Add ("@OrgIdP",SqlDbType.Int); cmd.Parameters["@OrgIdP"].Value=Session["OrgIdP"].ToString(); cmd.Parameters.Add ("@LicenseId",SqlDbType.Int); cmd.Parameters["@LicenseId"].Value=Session["LicenseId"].ToString(); cmd.Parameters.Add ("@DomainId",SqlDbType.Int); cmd.Parameters["@DomainId"].Value=Session["DomainId"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Funds"); lstFunds.DataSource = ds; lstFunds.DataMember= "Funds"; lstFunds.DataTextField = "Name"; lstFunds.DataValueField = "Id"; lstFunds.DataBind(); } /* private void loadVisibility() { SqlCommand cmd=new SqlCommand(); cmd.Connection=this.epsDbConn; cmd.CommandType=CommandType.StoredProcedure; cmd.CommandText="ams_RetrieveVisibility"; cmd.Parameters.Add ("@Vis",SqlDbType.Int); cmd.Parameters["@Vis"].Value=Session["OrgVis"].ToString(); DataSet ds=new DataSet(); SqlDataAdapter da=new SqlDataAdapter (cmd); da.Fill(ds,"Visibility"); lstVisibility.DataSource = ds; lstVisibility.DataMember= "Visibility"; lstVisibility.DataTextField = "Name"; lstVisibility.DataValueField = "Id"; lstVisibility.DataBind(); }*/ protected void btnAction_Click(object sender, System.EventArgs e) { if (Session["MgrOption"].ToString() == "Budget") { if (Session["Action"].ToString() == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdateBudget"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(Session["BudgetsId"].ToString()); cmd.Parameters.Add("@FundsId", SqlDbType.Int); cmd.Parameters["@FundsId"].Value = lstFunds.SelectedItem.Value; cmd.Parameters.Add("@Amt", SqlDbType.Decimal); if (txtAmt.Text != "") { cmd.Parameters["@Amt"].Value = decimal.Parse(txtAmt.Text, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands); } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } else if (Session["Action"].ToString() == "Add") { //string Str = txtFY.Text.Trim(); //double Num; //bool isNum = double.TryParse(Str, out Num); //if (isNum) SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_RetrieveBudgetFY"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@FundsId", SqlDbType.Int); cmd.Parameters["@FundsId"].Value = lstFunds.SelectedItem.Value; cmd.Parameters.Add("@FY", SqlDbType.Int); cmd.Parameters["@FY"].Value = lstFY.SelectedItem.Value; cmd.Parameters.Add("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString()); DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(cmd); da.Fill(ds, "FY"); if (ds.Tables["FY"].Rows.Count == 0) { addBudget(); Done(); } else { lblFY.Text = "Budget against the above Source of Funds has already been created for this FY. Select " + " a different FY or else press 'OK' to return to previous form."; //lstStatus.SelectedIndex = GetIndexOfStatus(ds.Tables["Budget"].Rows[0][1].ToString()); } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } } else //i.e. if Funds { DateTime date1, date2; bool date1OK, date2OK; date1 = new DateTime(1, 1, 1); date2 = new DateTime(1, 1, 1); try { date1 = Convert.ToDateTime(txtStartDate.Text); date1OK = true; } catch { date1OK = false; lblStart.Text = "Please enter date in form mm/dd/yyyy"; txtStartDate.Focus(); } try { date2 = Convert.ToDateTime(txtEndDate.Text); date2OK = true; } catch { date2OK = false; lblEnd.Text = "Please enter date in form mm/dd/yyyy"; lblEnd.Focus(); } if (date1OK && date2OK) { if (date1.CompareTo(date2) > -1) { lblStart.Text = ""; lblEnd.Text = "End date must be after start date"; } else { if (Session["Action"].ToString() == "Update") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_UpdateFund"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Id", SqlDbType.Int); cmd.Parameters["@Id"].Value = Int32.Parse(Session["FundsId"].ToString()); cmd.Parameters.Add("@Name", SqlDbType.NVarChar); cmd.Parameters["@Name"].Value = txtName.Text; cmd.Parameters.Add("@Status", SqlDbType.Int); cmd.Parameters["@Status"].Value = lstStatus.SelectedItem.Value; cmd.Parameters.Add("@CurrenciesId", SqlDbType.Int); cmd.Parameters["@CurrenciesId"].Value = lstCurr.SelectedItem.Value; cmd.Parameters.Add("@Amt", SqlDbType.Decimal); if (txtAmt.Text != "") { cmd.Parameters["@Amt"].Value = decimal.Parse(txtAmt.Text, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands); } cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime); if (txtStartDate.Text != "") { cmd.Parameters["@StartDate"].Value = txtStartDate.Text; } cmd.Parameters.Add("@EndDate", SqlDbType.SmallDateTime); if (txtEndDate.Text != "") { cmd.Parameters["@EndDate"].Value = txtEndDate.Text; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } else if (Session["Action"].ToString() == "Add") { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_AddFund"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@Name", SqlDbType.NVarChar); cmd.Parameters["@Name"].Value = txtName.Text; cmd.Parameters.Add("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString()); cmd.Parameters.Add("@CurrenciesId", SqlDbType.Int); cmd.Parameters["@CurrenciesId"].Value = lstCurr.SelectedItem.Value; cmd.Parameters.Add("@Status", SqlDbType.Int); cmd.Parameters["@Status"].Value = lstStatus.SelectedItem.Value; cmd.Parameters.Add("@Amt", SqlDbType.Decimal); if (txtAmt.Text != "") { cmd.Parameters["@Amt"].Value = decimal.Parse(txtAmt.Text, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands); } cmd.Parameters.Add("@StartDate", SqlDbType.SmallDateTime); if (txtStartDate.Text != "") { cmd.Parameters["@StartDate"].Value = txtStartDate.Text; } cmd.Parameters.Add("@EndDate", SqlDbType.SmallDateTime); if (txtEndDate.Text != "") { cmd.Parameters["@EndDate"].Value = txtEndDate.Text; } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); Done(); } } } } } private void addBudget() { SqlCommand cmd = new SqlCommand(); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandText = "fms_AddBudget"; cmd.Connection = this.epsDbConn; cmd.Parameters.Add("@OrgId", SqlDbType.Int); cmd.Parameters["@OrgId"].Value = Int32.Parse(Session["OrgId"].ToString()); cmd.Parameters.Add("@FundsId", SqlDbType.Int); cmd.Parameters["@FundsId"].Value = lstFunds.SelectedItem.Value; cmd.Parameters.Add("@FY", SqlDbType.Int); cmd.Parameters["@FY"].Value = lstFY.SelectedItem.Value;//Int32.Parse(txtFY.Text); cmd.Parameters.Add("@Status", SqlDbType.Int); cmd.Parameters["@Status"].Value = lstStatus.SelectedItem.Value; cmd.Parameters.Add("@Amt", SqlDbType.Decimal); if (txtAmt.Text != "") { cmd.Parameters["@Amt"].Value = decimal.Parse(txtAmt.Text, System.Globalization.NumberStyles.AllowDecimalPoint | System.Globalization.NumberStyles.AllowThousands); } cmd.Connection.Open(); cmd.ExecuteNonQuery(); cmd.Connection.Close(); } private void Done() { Session["BudgetsId"] = null; Response.Redirect(strURL + Session["CUpdBudget"].ToString() + ".aspx?"); } protected void btnCancel_Click(object sender, System.EventArgs e) { Done(); } protected void btnAdd_Click(object sender, EventArgs e) { } /*private void SwitchBud() { lblFunction.Text = Session["Action"].ToString() + " Budget"; btnAction.Text = Session["Action"].ToString(); lblStartDate.Visible = false; txtStartDate.Visible = false; lblEndDate.Visible = false; txtEndDate.Visible = false; btnFunds.Visible = true; lblFY.Visible = true; txtFY.Visible = true; lblName.Text = "Budget Name"; lblCurr.Visible = false; lstCurr.Visible = false; lstFunds.Visible = true; lblFunds.Visible = true; lblStart.Visible = false; lblEnd.Visible = false; loadFunds(); }*/ } }
// 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 Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { ///////////////////////////////////////////////////////////////////////////////// // Defines the structure used when binding types // CheckConstraints options. internal enum CheckConstraintsFlags { None = 0x00, Outer = 0x01, NoDupErrors = 0x02, NoErrors = 0x04, } ///////////////////////////////////////////////////////////////////////////////// // TypeBind has static methods to accomplish most tasks. // // For some of these tasks there are also instance methods. The instance // method versions don't report not found errors (they may report others) but // instead record error information in the TypeBind instance. Call the // ReportErrors method to report recorded errors. internal static class TypeBind { // Check the constraints of any type arguments in the given Type. public static bool CheckConstraints(CSemanticChecker checker, ErrorHandling errHandling, CType type, CheckConstraintsFlags flags) { type = type.GetNakedType(false); if (type.IsNullableType()) { CType typeT = type.AsNullableType().GetAts(checker.GetErrorContext()); if (typeT != null) type = typeT; else type = type.GetNakedType(true); } if (!type.IsAggregateType()) return true; AggregateType ats = type.AsAggregateType(); if (ats.GetTypeArgsAll().size == 0) { // Common case: there are no type vars, so there are no constraints. ats.fConstraintsChecked = true; ats.fConstraintError = false; return true; } if (ats.fConstraintsChecked) { // Already checked. if (!ats.fConstraintError || (flags & CheckConstraintsFlags.NoDupErrors) != 0) { // No errors or no need to report errors again. return !ats.fConstraintError; } } TypeArray typeVars = ats.getAggregate().GetTypeVars(); TypeArray typeArgsThis = ats.GetTypeArgsThis(); TypeArray typeArgsAll = ats.GetTypeArgsAll(); Debug.Assert(typeVars.size == typeArgsThis.size); if (!ats.fConstraintsChecked) { ats.fConstraintsChecked = true; ats.fConstraintError = false; } // Check the outer type first. If CheckConstraintsFlags.Outer is not specified and the // outer type has already been checked then don't bother checking it. if (ats.outerType != null && ((flags & CheckConstraintsFlags.Outer) != 0 || !ats.outerType.fConstraintsChecked)) { CheckConstraints(checker, errHandling, ats.outerType, flags); ats.fConstraintError |= ats.outerType.fConstraintError; } if (typeVars.size > 0) ats.fConstraintError |= !CheckConstraintsCore(checker, errHandling, ats.getAggregate(), typeVars, typeArgsThis, typeArgsAll, null, (flags & CheckConstraintsFlags.NoErrors)); // Now check type args themselves. for (int i = 0; i < typeArgsThis.size; i++) { CType arg = typeArgsThis.Item(i).GetNakedType(true); if (arg.IsAggregateType() && !arg.AsAggregateType().fConstraintsChecked) { CheckConstraints(checker, errHandling, arg.AsAggregateType(), flags | CheckConstraintsFlags.Outer); if (arg.AsAggregateType().fConstraintError) ats.fConstraintError = true; } } return !ats.fConstraintError; } //////////////////////////////////////////////////////////////////////////////// // Check the constraints on the method instantiation. public static void CheckMethConstraints(CSemanticChecker checker, ErrorHandling errCtx, MethWithInst mwi) { Debug.Assert(mwi.Meth() != null && mwi.GetType() != null && mwi.TypeArgs != null); Debug.Assert(mwi.Meth().typeVars.size == mwi.TypeArgs.size); Debug.Assert(mwi.GetType().getAggregate() == mwi.Meth().getClass()); if (mwi.TypeArgs.size > 0) { CheckConstraintsCore(checker, errCtx, mwi.Meth(), mwi.Meth().typeVars, mwi.TypeArgs, mwi.GetType().GetTypeArgsAll(), mwi.TypeArgs, CheckConstraintsFlags.None); } } //////////////////////////////////////////////////////////////////////////////// // Check whether typeArgs satisfies the constraints of typeVars. The // typeArgsCls and typeArgsMeth are used for substitution on the bounds. The // tree and symErr are used for error reporting. private static bool CheckConstraintsCore(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeArray typeVars, TypeArray typeArgs, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags) { Debug.Assert(typeVars.size == typeArgs.size); Debug.Assert(typeVars.size > 0); Debug.Assert(flags == CheckConstraintsFlags.None || flags == CheckConstraintsFlags.NoErrors); bool fError = false; for (int i = 0; i < typeVars.size; i++) { // Empty bounds should be set to object. TypeParameterType var = typeVars.ItemAsTypeParameterType(i); CType arg = typeArgs.Item(i); bool fOK = CheckSingleConstraint(checker, errHandling, symErr, var, arg, typeArgsCls, typeArgsMeth, flags); fError |= !fOK; } return !fError; } private static bool CheckSingleConstraint(CSemanticChecker checker, ErrorHandling errHandling, Symbol symErr, TypeParameterType var, CType arg, TypeArray typeArgsCls, TypeArray typeArgsMeth, CheckConstraintsFlags flags) { bool fReportErrors = 0 == (flags & CheckConstraintsFlags.NoErrors); if (arg.IsOpenTypePlaceholderType()) { return true; } if (arg.IsErrorType()) { // Error should have been reported previously. return false; } if (checker.CheckBogus(arg)) { if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_BogusType, arg); } return false; } if (arg.IsPointerType() || arg.isSpecialByRefType()) { if (fReportErrors) { errHandling.Error(ErrorCode.ERR_BadTypeArgument, arg); } return false; } if (arg.isStaticClass()) { if (fReportErrors) { checker.ReportStaticClassError(null, arg, ErrorCode.ERR_GenericArgIsStaticClass); } return false; } bool fError = false; if (var.HasRefConstraint() && !arg.IsRefType()) { if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_RefConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg); } fError = true; } TypeArray bnds = checker.GetSymbolLoader().GetTypeManager().SubstTypeArray(var.GetBounds(), typeArgsCls, typeArgsMeth); int itypeMin = 0; if (var.HasValConstraint()) { // If we have a type variable that is constrained to a value type, then we // want to check if its a nullable type, so that we can report the // constraint error below. In order to do this however, we need to check // that either the type arg is not a value type, or it is a nullable type. // // To check whether or not its a nullable type, we need to get the resolved // bound from the type argument and check against that. bool bIsValueType = arg.IsValType(); bool bIsNullable = arg.IsNullableType(); if (bIsValueType && arg.IsTypeParameterType()) { TypeArray pArgBnds = arg.AsTypeParameterType().GetBounds(); if (pArgBnds.size > 0) { bIsNullable = pArgBnds.Item(0).IsNullableType(); } } if (!bIsValueType || bIsNullable) { if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_ValConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg); } fError = true; } // Since FValCon() is set it is redundant to check System.ValueType as well. if (bnds.size != 0 && bnds.Item(0).isPredefType(PredefinedType.PT_VALUE)) { itypeMin = 1; } } for (int j = itypeMin; j < bnds.size; j++) { CType typeBnd = bnds.Item(j); if (!SatisfiesBound(checker, arg, typeBnd)) { if (fReportErrors) { // The bound isn't satisfied because of a constraint type. Explain to the user why not. // There are 4 main cases, based on the type of the supplied type argument: // - reference type, or type parameter known to be a reference type // - nullable type, from which there is a boxing conversion to the constraint type(see below for details) // - type variable // - value type // These cases are broken out because: a) The sets of conversions which can be used // for constraint satisfaction is different based on the type argument supplied, // and b) Nullable is one funky type, and user's can use all the help they can get // when using it. ErrorCode error; if (arg.IsRefType()) { // A reference type can only satisfy bounds to types // to which they have an implicit reference conversion error = ErrorCode.ERR_GenericConstraintNotSatisfiedRefType; } else if (arg.IsNullableType() && checker.GetSymbolLoader().HasBaseConversion(arg.AsNullableType().GetUnderlyingType(), typeBnd)) // This is inlining FBoxingConv { // nullable types do not satisfy bounds to every type that they are boxable to // They only satisfy bounds of object and ValueType if (typeBnd.isPredefType(PredefinedType.PT_ENUM) || arg.AsNullableType().GetUnderlyingType() == typeBnd) { // Nullable types don't satisfy bounds of EnumType, or the underlying type of the enum // even though the conversion from Nullable to these types is a boxing conversion // This is a rare case, because these bounds can never be directly stated ... // These bounds can only occur when one type paramter is constrained to a second type parameter // and the second type parameter is instantiated with Enum or the underlying type of the first type // parameter error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableEnum; } else { // Nullable types don't satisfy the bounds of any interface type // even when there is a boxing conversion from the Nullable type to // the interface type. This will be a relatively common scenario // so we cal it out separately from the previous case. Debug.Assert(typeBnd.isInterfaceType()); error = ErrorCode.ERR_GenericConstraintNotSatisfiedNullableInterface; } } else if (arg.IsTypeParameterType()) { // Type variables can satisfy bounds through boxing and type variable conversions Debug.Assert(!arg.IsRefType()); error = ErrorCode.ERR_GenericConstraintNotSatisfiedTyVar; } else { // Value types can only satisfy bounds through boxing conversions. // Note that the exceptional case of Nullable types and boxing is handled above. error = ErrorCode.ERR_GenericConstraintNotSatisfiedValType; } errHandling.Error(error, new ErrArgRef(symErr), new ErrArg(typeBnd, ErrArgFlags.Unique), var, new ErrArgRef(arg, ErrArgFlags.Unique)); } fError = true; } } // Check the newable constraint. if (!var.HasNewConstraint() || arg.IsValType()) { return !fError; } if (arg.isClassType()) { AggregateSymbol agg = arg.AsAggregateType().getAggregate(); // Due to late binding nature of IDE created symbols, the AggregateSymbol might not // have all the information necessary yet, if it is not fully bound. // by calling LookupAggMember, it will ensure that we will update all the // information necessary at least for the given method. checker.GetSymbolLoader().LookupAggMember(checker.GetNameManager().GetPredefName(PredefinedName.PN_CTOR), agg, symbmask_t.MASK_ALL); if (agg.HasPubNoArgCtor() && !agg.IsAbstract()) { return !fError; } } else if (arg.IsTypeParameterType() && arg.AsTypeParameterType().HasNewConstraint()) { return !fError; } if (fReportErrors) { errHandling.ErrorRef(ErrorCode.ERR_NewConstraintNotSatisfied, symErr, new ErrArgNoRef(var), arg); } return false; } //////////////////////////////////////////////////////////////////////////////// // Determine whether the arg type satisfies the typeBnd constraint. Note that // typeBnd could be just about any type (since we added naked type parameter // constraints). private static bool SatisfiesBound(CSemanticChecker checker, CType arg, CType typeBnd) { if (typeBnd == arg) return true; switch (typeBnd.GetTypeKind()) { default: Debug.Assert(false, "Unexpected type."); return false; case TypeKind.TK_VoidType: case TypeKind.TK_PointerType: case TypeKind.TK_ErrorType: return false; case TypeKind.TK_ArrayType: case TypeKind.TK_TypeParameterType: break; case TypeKind.TK_NullableType: typeBnd = typeBnd.AsNullableType().GetAts(checker.GetErrorContext()); if (null == typeBnd) return true; break; case TypeKind.TK_AggregateType: break; } Debug.Assert(typeBnd.IsAggregateType() || typeBnd.IsTypeParameterType() || typeBnd.IsArrayType()); switch (arg.GetTypeKind()) { default: return false; case TypeKind.TK_ErrorType: case TypeKind.TK_PointerType: return false; case TypeKind.TK_NullableType: arg = arg.AsNullableType().GetAts(checker.GetErrorContext()); if (null == arg) return true; // Fall through. goto case TypeKind.TK_TypeParameterType; case TypeKind.TK_TypeParameterType: case TypeKind.TK_ArrayType: case TypeKind.TK_AggregateType: return checker.GetSymbolLoader().HasBaseConversion(arg, typeBnd); } } } }
/*************************************************************************** copyright : (C) 2005 by Brian Nickel email : brian.nickel@gmail.com based on : mpegheader.cpp from TagLib ***************************************************************************/ /*************************************************************************** * This library is free software; you can redistribute it and/or modify * * it under the terms of the GNU Lesser General Public License version * * 2.1 as published by the Free Software Foundation. * * * * This library is distributed in the hope that it will be useful, but * * WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with this library; if not, write to the Free Software * * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * * USA * ***************************************************************************/ using System.Collections; using System; namespace TagLib.Mpeg { public enum Version { Version1 = 0, // MPEG Version 1 Version2 = 1, // MPEG Version 2 Version2_5 = 2 // MPEG Version 2.5 } public enum ChannelMode { Stereo = 0, // Stereo JointStereo = 1, // Stereo DualChannel = 2, // Dual Mono SingleChannel = 3 // Mono }; public class Header { ////////////////////////////////////////////////////////////////////////// // private properties ////////////////////////////////////////////////////////////////////////// private Version version; private int layer; private bool protection_enabled; private int bitrate; private int sample_rate; private bool is_padded; private ChannelMode channel_mode; private bool is_copyrighted; private bool is_original; private int frame_length; private long position; ////////////////////////////////////////////////////////////////////////// // public methods ////////////////////////////////////////////////////////////////////////// public Header (ByteVector data, long offset) { version = Version.Version1; layer = 0; protection_enabled = false; bitrate = 0; sample_rate = 0; is_padded = false; channel_mode = ChannelMode.Stereo; is_copyrighted = false; is_original = false; frame_length = 0; position = offset; Parse (data); } public Header (Header header) { version = header.Version; layer = header.Layer; protection_enabled = header.ProtectionEnabled; bitrate = header.Bitrate; sample_rate = header.SampleRate; is_padded = header.IsPadded; channel_mode = header.ChannelMode; is_copyrighted = header.IsCopyrighted; is_original = header.IsOriginal; frame_length = header.FrameLength; position = -1; } ////////////////////////////////////////////////////////////////////////// // public properties ////////////////////////////////////////////////////////////////////////// public Version Version {get {return version;}} public int Layer {get {return layer;}} public bool ProtectionEnabled {get {return protection_enabled;}} public int Bitrate {get {return bitrate;}} public int SampleRate {get {return sample_rate;}} public bool IsPadded {get {return is_padded;}} public ChannelMode ChannelMode {get {return channel_mode;}} public bool IsCopyrighted {get {return is_copyrighted;}} public bool IsOriginal {get {return is_original;}} public int FrameLength {get {return frame_length;}} public long Position {get {return position;}} ////////////////////////////////////////////////////////////////////////// // private methods ////////////////////////////////////////////////////////////////////////// private void Parse (ByteVector data) { if(data.Count < 4 || data [0] != 0xff) throw new CorruptFileException ("First byte did not mactch MPEG synch."); uint flags = data.ToUInt(); // Check for the second byte's part of the MPEG synch if ((flags & 0xFFE00000) != 0xFFE00000) throw new CorruptFileException ("Second byte did not mactch MPEG synch."); // Set the MPEG version switch ((flags >> 19) & 0x03) { case 0: version = Version.Version2_5; break; case 2: version = Version.Version2; break; case 3: version = Version.Version1; break; } // Set the MPEG layer switch ((flags >> 17) & 0x03) { case 1: layer = 3; break; case 2: layer = 2; break; case 3: layer = 1; break; } protection_enabled = ((flags >>16) & 1) == 0; // Set the bitrate int [,,] bitrates = new int [2,3,16] { { // Version 1 { 0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, -1 }, // layer 1 { 0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, -1 }, // layer 2 { 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, -1 } // layer 3 }, { // Version 2 or 2.5 { 0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, -1 }, // layer 1 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1 }, // layer 2 { 0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, -1 } // layer 3 } }; int version_index = version == Version.Version1 ? 0 : 1; int layer_index = layer > 0 ? layer - 1 : 0; // The bitrate index is encoded as the first 4 bits of the 3rd byte, // i.e. 1111xxxx int i = (int) (flags >> 12) & 0x0F; bitrate = bitrates [version_index,layer_index,i]; if (bitrate < 0) throw new CorruptFileException ("Header uses invalid bitrate index."); // Set the sample rate int [,] sample_rates = new int [3,4] { { 44100, 48000, 32000, 0 }, // Version 1 { 22050, 24000, 16000, 0 }, // Version 2 { 11025, 12000, 8000, 0 } // Version 2.5 }; // The sample rate index is encoded as two bits in the 3nd byte, // i.e. xxxx11xx i = (int) (flags >> 10) & 0x03; sample_rate = sample_rates [(int) version,i]; if(sample_rate == 0) throw new CorruptFileException ("Invalid sample rate."); // The channel mode is encoded as a 2 bit value at the end of the 3nd // byte, i.e. xxxxxx11 channel_mode = (ChannelMode)((data[3] & 0xC0) >> 6); // TODO: Add mode extension for completeness is_original = ((flags >> 2) & 1) == 1; is_copyrighted = ((flags >> 3) & 1) == 1; is_padded = ((flags >> 9) & 1) == 1; // Calculate the frame length if(layer == 1) frame_length = (((12000 * bitrate) / sample_rate) + (IsPadded ? 1 : 0))*4; else if (layer == 2) frame_length = (144000 * bitrate) / sample_rate + (IsPadded ? 1 : 0); else if (layer == 3) frame_length = (((144000 * bitrate) / sample_rate) / (version == Version.Version1 ? 1 : 2)) + (IsPadded ? 1 : 0); } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections.Generic; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Newtonsoft.Json.Utilities { internal static class BufferUtils { public static char[] RentBuffer(IArrayPool<char> bufferPool, int minSize) { if (bufferPool == null) { return new char[minSize]; } char[] buffer = bufferPool.Rent(minSize); return buffer; } public static void ReturnBuffer(IArrayPool<char> bufferPool, char[] buffer) { if (bufferPool == null) { return; } bufferPool.Return(buffer); } public static char[] EnsureBufferSize(IArrayPool<char> bufferPool, int size, char[] buffer) { if (bufferPool == null) { return new char[size]; } if (buffer != null) { bufferPool.Return(buffer); } return bufferPool.Rent(size); } } internal static class JavaScriptUtils { internal static readonly bool[] SingleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] DoubleQuoteCharEscapeFlags = new bool[128]; internal static readonly bool[] HtmlCharEscapeFlags = new bool[128]; private const int UnicodeTextLength = 6; static JavaScriptUtils() { IList<char> escapeChars = new List<char> { '\n', '\r', '\t', '\\', '\f', '\b', }; for (int i = 0; i < ' '; i++) { escapeChars.Add((char)i); } foreach (var escapeChar in escapeChars.Union(new[] { '\'' })) { SingleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"' })) { DoubleQuoteCharEscapeFlags[escapeChar] = true; } foreach (var escapeChar in escapeChars.Union(new[] { '"', '\'', '<', '>', '&' })) { HtmlCharEscapeFlags[escapeChar] = true; } } private const string EscapedUnicodeText = "!"; public static bool[] GetCharEscapeFlags(StringEscapeHandling stringEscapeHandling, char quoteChar) { if (stringEscapeHandling == StringEscapeHandling.EscapeHtml) { return HtmlCharEscapeFlags; } if (quoteChar == '"') { return DoubleQuoteCharEscapeFlags; } return SingleQuoteCharEscapeFlags; } public static bool ShouldEscapeJavaScriptString(string s, bool[] charEscapeFlags) { if (s == null) { return false; } foreach (char c in s) { if (c >= charEscapeFlags.Length || charEscapeFlags[c]) { return true; } } return false; } public static void WriteEscapedJavaScriptString(TextWriter writer, string s, char delimiter, bool appendDelimiters, bool[] charEscapeFlags, StringEscapeHandling stringEscapeHandling, IArrayPool<char> bufferPool, ref char[] writeBuffer) { // leading delimiter if (appendDelimiters) { writer.Write(delimiter); } if (s != null) { int lastWritePosition = 0; for (int i = 0; i < s.Length; i++) { var c = s[i]; if (c < charEscapeFlags.Length && !charEscapeFlags[c]) { continue; } string escapedValue; switch (c) { case '\t': escapedValue = @"\t"; break; case '\n': escapedValue = @"\n"; break; case '\r': escapedValue = @"\r"; break; case '\f': escapedValue = @"\f"; break; case '\b': escapedValue = @"\b"; break; case '\\': escapedValue = @"\\"; break; case '\u0085': // Next Line escapedValue = @"\u0085"; break; case '\u2028': // Line Separator escapedValue = @"\u2028"; break; case '\u2029': // Paragraph Separator escapedValue = @"\u2029"; break; default: if (c < charEscapeFlags.Length || stringEscapeHandling == StringEscapeHandling.EscapeNonAscii) { if (c == '\'' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\'"; } else if (c == '"' && stringEscapeHandling != StringEscapeHandling.EscapeHtml) { escapedValue = @"\"""; } else { if (writeBuffer == null || writeBuffer.Length < UnicodeTextLength) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, UnicodeTextLength, writeBuffer); } StringUtils.ToCharAsUnicode(c, writeBuffer); // slightly hacky but it saves multiple conditions in if test escapedValue = EscapedUnicodeText; } } else { escapedValue = null; } break; } if (escapedValue == null) { continue; } bool isEscapedUnicodeText = string.Equals(escapedValue, EscapedUnicodeText); if (i > lastWritePosition) { int length = i - lastWritePosition + ((isEscapedUnicodeText) ? UnicodeTextLength : 0); int start = (isEscapedUnicodeText) ? UnicodeTextLength : 0; if (writeBuffer == null || writeBuffer.Length < length) { char[] newBuffer = BufferUtils.RentBuffer(bufferPool, length); // the unicode text is already in the buffer // copy it over when creating new buffer if (isEscapedUnicodeText) { Array.Copy(writeBuffer, newBuffer, UnicodeTextLength); } BufferUtils.ReturnBuffer(bufferPool, writeBuffer); writeBuffer = newBuffer; } s.CopyTo(lastWritePosition, writeBuffer, start, length - start); // write unchanged chars before writing escaped text writer.Write(writeBuffer, start, length - start); } lastWritePosition = i + 1; if (!isEscapedUnicodeText) { writer.Write(escapedValue); } else { writer.Write(writeBuffer, 0, UnicodeTextLength); } } if (lastWritePosition == 0) { // no escaped text, write entire string writer.Write(s); } else { int length = s.Length - lastWritePosition; if (writeBuffer == null || writeBuffer.Length < length) { writeBuffer = BufferUtils.EnsureBufferSize(bufferPool, length, writeBuffer); } s.CopyTo(lastWritePosition, writeBuffer, 0, length); // write remaining text writer.Write(writeBuffer, 0, length); } } // trailing delimiter if (appendDelimiters) { writer.Write(delimiter); } } public static string ToEscapedJavaScriptString(string value, char delimiter, bool appendDelimiters, StringEscapeHandling stringEscapeHandling) { bool[] charEscapeFlags = GetCharEscapeFlags(stringEscapeHandling, delimiter); using (StringWriter w = StringUtils.CreateStringWriter(value?.Length ?? 16)) { char[] buffer = null; WriteEscapedJavaScriptString(w, value, delimiter, appendDelimiters, charEscapeFlags, stringEscapeHandling, null, ref buffer); return w.ToString(); } } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CodeFixes.Suppression; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor; using Microsoft.CodeAnalysis.Editor.Host; using Microsoft.CodeAnalysis.Editor.Implementation.Suggestions; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.TableDataSource; using Microsoft.VisualStudio.LanguageServices.Implementation.TaskList; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell.TableControl; using Roslyn.Utilities; using Task = System.Threading.Tasks.Task; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Suppression { /// <summary> /// Service to compute and apply bulk suppression fixes. /// </summary> [Export(typeof(IVisualStudioSuppressionFixService))] internal sealed class VisualStudioSuppressionFixService : IVisualStudioSuppressionFixService { private readonly VisualStudioWorkspaceImpl _workspace; private readonly IWpfTableControl _tableControl; private readonly IDiagnosticAnalyzerService _diagnosticService; private readonly ExternalErrorDiagnosticUpdateSource _buildErrorDiagnosticService; private readonly ICodeFixService _codeFixService; private readonly IFixMultipleOccurrencesService _fixMultipleOccurencesService; private readonly ICodeActionEditHandlerService _editHandlerService; private readonly VisualStudioDiagnosticListSuppressionStateService _suppressionStateService; private readonly IWaitIndicator _waitIndicator; [ImportingConstructor] public VisualStudioSuppressionFixService( SVsServiceProvider serviceProvider, VisualStudioWorkspaceImpl workspace, IDiagnosticAnalyzerService diagnosticService, ExternalErrorDiagnosticUpdateSource buildErrorDiagnosticService, ICodeFixService codeFixService, ICodeActionEditHandlerService editHandlerService, IVisualStudioDiagnosticListSuppressionStateService suppressionStateService, IWaitIndicator waitIndicator) { _workspace = workspace; _diagnosticService = diagnosticService; _buildErrorDiagnosticService = buildErrorDiagnosticService; _codeFixService = codeFixService; _suppressionStateService = (VisualStudioDiagnosticListSuppressionStateService)suppressionStateService; _editHandlerService = editHandlerService; _waitIndicator = waitIndicator; _fixMultipleOccurencesService = workspace.Services.GetService<IFixMultipleOccurrencesService>(); var errorList = serviceProvider.GetService(typeof(SVsErrorList)) as IErrorList; _tableControl = errorList?.TableControl; } public bool AddSuppressions(IVsHierarchy projectHierarchyOpt) { if (_tableControl == null) { return false; } Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt); // Apply suppressions fix in global suppressions file for non-compiler diagnostics and // in source only for compiler diagnostics. var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly: false, isAddSuppression: true); if (!ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: false)) { return false; } return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: false, isAddSuppression: true, isSuppressionInSource: true, onlyCompilerDiagnostics: true, showPreviewChangesDialog: false); } public bool AddSuppressions(bool selectedErrorListEntriesOnly, bool suppressInSource, IVsHierarchy projectHierarchyOpt) { if (_tableControl == null) { return false; } Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt); return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: true, isSuppressionInSource: suppressInSource, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true); } public bool RemoveSuppressions(bool selectedErrorListEntriesOnly, IVsHierarchy projectHierarchyOpt) { if (_tableControl == null) { return false; } Func<Project, bool> shouldFixInProject = GetShouldFixInProjectDelegate(_workspace, projectHierarchyOpt); return ApplySuppressionFix(shouldFixInProject, selectedErrorListEntriesOnly, isAddSuppression: false, isSuppressionInSource: false, onlyCompilerDiagnostics: false, showPreviewChangesDialog: true); } private static Func<Project, bool> GetShouldFixInProjectDelegate(VisualStudioWorkspaceImpl workspace, IVsHierarchy projectHierarchyOpt) { if (projectHierarchyOpt == null) { return p => true; } else { var projectIdsForHierarchy = (workspace.DeferredState?.ProjectTracker.ImmutableProjects ?? ImmutableArray<AbstractProject>.Empty) .Where(p => p.Language == LanguageNames.CSharp || p.Language == LanguageNames.VisualBasic) .Where(p => p.Hierarchy == projectHierarchyOpt) .Select(p => workspace.CurrentSolution.GetProject(p.Id).Id) .ToImmutableHashSet(); return p => projectIdsForHierarchy.Contains(p.Id); } } private async Task<ImmutableArray<DiagnosticData>> GetAllBuildDiagnosticsAsync(Func<Project, bool> shouldFixInProject, CancellationToken cancellationToken) { var builder = ArrayBuilder<DiagnosticData>.GetInstance(); var buildDiagnostics = _buildErrorDiagnosticService.GetBuildErrors().Where(d => d.ProjectId != null && d.Severity != DiagnosticSeverity.Hidden); var solution = _workspace.CurrentSolution; foreach (var diagnosticsByProject in buildDiagnostics.GroupBy(d => d.ProjectId)) { cancellationToken.ThrowIfCancellationRequested(); if (diagnosticsByProject.Key == null) { // Diagnostics with no projectId cannot be suppressed. continue; } var project = solution.GetProject(diagnosticsByProject.Key); if (project != null && shouldFixInProject(project)) { var diagnosticsByDocument = diagnosticsByProject.GroupBy(d => d.DocumentId); foreach (var group in diagnosticsByDocument) { var documentId = group.Key; if (documentId == null) { // Project diagnostics, just add all of them. builder.AddRange(group); continue; } // For document diagnostics, build does not have the computed text span info. // So we explicitly calculate the text span from the source text for the diagnostics. var document = project.GetDocument(documentId); if (document != null) { var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false); var text = await tree.GetTextAsync(cancellationToken).ConfigureAwait(false); foreach (var diagnostic in group) { builder.Add(diagnostic.WithCalculatedSpan(text)); } } } } } return builder.ToImmutableAndFree(); } private static string GetFixTitle(bool isAddSuppression) { return isAddSuppression ? ServicesVSResources.Suppress_diagnostics : ServicesVSResources.Remove_suppressions; } private static string GetWaitDialogMessage(bool isAddSuppression) { return isAddSuppression ? ServicesVSResources.Computing_suppressions_fix : ServicesVSResources.Computing_remove_suppressions_fix; } private IEnumerable<DiagnosticData> GetDiagnosticsToFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression) { var diagnosticsToFix = ImmutableHashSet<DiagnosticData>.Empty; Action<IWaitContext> computeDiagnosticsToFix = context => { var cancellationToken = context.CancellationToken; // If we are fixing selected diagnostics in error list, then get the diagnostics from error list entry snapshots. // Otherwise, get all diagnostics from the diagnostic service. var diagnosticsToFixTask = selectedEntriesOnly ? _suppressionStateService.GetSelectedItemsAsync(isAddSuppression, cancellationToken) : GetAllBuildDiagnosticsAsync(shouldFixInProject, cancellationToken); diagnosticsToFix = diagnosticsToFixTask.WaitAndGetResult(cancellationToken).ToImmutableHashSet(); }; var title = GetFixTitle(isAddSuppression); var waitDialogMessage = GetWaitDialogMessage(isAddSuppression); var result = InvokeWithWaitDialog(computeDiagnosticsToFix, title, waitDialogMessage); // Bail out if the user cancelled. if (result == WaitIndicatorResult.Canceled) { return null; } return diagnosticsToFix; } private bool ApplySuppressionFix(Func<Project, bool> shouldFixInProject, bool selectedEntriesOnly, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog) { var diagnosticsToFix = GetDiagnosticsToFix(shouldFixInProject, selectedEntriesOnly, isAddSuppression); return ApplySuppressionFix(diagnosticsToFix, shouldFixInProject, selectedEntriesOnly, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics, showPreviewChangesDialog); } private bool ApplySuppressionFix(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics, bool showPreviewChangesDialog) { if (diagnosticsToFix == null) { return false; } diagnosticsToFix = FilterDiagnostics(diagnosticsToFix, isAddSuppression, isSuppressionInSource, onlyCompilerDiagnostics); if (diagnosticsToFix.IsEmpty()) { // Nothing to fix. return true; } ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap = null; ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap = null; var title = GetFixTitle(isAddSuppression); var waitDialogMessage = GetWaitDialogMessage(isAddSuppression); var noDiagnosticsToFix = false; var cancelled = false; var newSolution = _workspace.CurrentSolution; HashSet<string> languages = null; Action<IWaitContext> computeDiagnosticsAndFix = context => { var cancellationToken = context.CancellationToken; cancellationToken.ThrowIfCancellationRequested(); documentDiagnosticsToFixMap = GetDocumentDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken) .WaitAndGetResult(cancellationToken); cancellationToken.ThrowIfCancellationRequested(); projectDiagnosticsToFixMap = isSuppressionInSource ? ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty : GetProjectDiagnosticsToFixAsync(diagnosticsToFix, shouldFixInProject, filterStaleDiagnostics: filterStaleDiagnostics, cancellationToken: cancellationToken) .WaitAndGetResult(cancellationToken); if (documentDiagnosticsToFixMap == null || projectDiagnosticsToFixMap == null || (documentDiagnosticsToFixMap.IsEmpty && projectDiagnosticsToFixMap.IsEmpty)) { // Nothing to fix. noDiagnosticsToFix = true; return; } cancellationToken.ThrowIfCancellationRequested(); // Equivalence key determines what fix will be applied. // Make sure we don't include any specific diagnostic ID, as we want all of the given diagnostics (which can have varied ID) to be fixed. var equivalenceKey = isAddSuppression ? (isSuppressionInSource ? FeaturesResources.in_Source : FeaturesResources.in_Suppression_File) : FeaturesResources.Remove_Suppression; // We have different suppression fixers for every language. // So we need to group diagnostics by the containing project language and apply fixes separately. languages = new HashSet<string>(projectDiagnosticsToFixMap.Select(p => p.Key.Language).Concat(documentDiagnosticsToFixMap.Select(kvp => kvp.Key.Project.Language))); foreach (var language in languages) { // Use the Fix multiple occurrences service to compute a bulk suppression fix for the specified document and project diagnostics, // show a preview changes dialog and then apply the fix to the workspace. cancellationToken.ThrowIfCancellationRequested(); var documentDiagnosticsPerLanguage = GetDocumentDiagnosticsMappedToNewSolution(documentDiagnosticsToFixMap, newSolution, language); if (!documentDiagnosticsPerLanguage.IsEmpty) { var suppressionFixer = GetSuppressionFixer(documentDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService); if (suppressionFixer != null) { var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider(); newSolution = _fixMultipleOccurencesService.GetFix( documentDiagnosticsPerLanguage, _workspace, suppressionFixer, suppressionFixAllProvider, equivalenceKey, title, waitDialogMessage, cancellationToken); if (newSolution == null) { // User cancelled or fixer threw an exception, so we just bail out. cancelled = true; return; } } } var projectDiagnosticsPerLanguage = GetProjectDiagnosticsMappedToNewSolution(projectDiagnosticsToFixMap, newSolution, language); if (!projectDiagnosticsPerLanguage.IsEmpty) { var suppressionFixer = GetSuppressionFixer(projectDiagnosticsPerLanguage.SelectMany(kvp => kvp.Value), language, _codeFixService); if (suppressionFixer != null) { var suppressionFixAllProvider = suppressionFixer.GetFixAllProvider(); newSolution = _fixMultipleOccurencesService.GetFix( projectDiagnosticsPerLanguage, _workspace, suppressionFixer, suppressionFixAllProvider, equivalenceKey, title, waitDialogMessage, cancellationToken); if (newSolution == null) { // User cancelled or fixer threw an exception, so we just bail out. cancelled = true; return; } } } } }; var result = InvokeWithWaitDialog(computeDiagnosticsAndFix, title, waitDialogMessage); // Bail out if the user cancelled. if (cancelled || result == WaitIndicatorResult.Canceled) { return false; } else if (noDiagnosticsToFix || newSolution == _workspace.CurrentSolution) { // No changes. return true; } if (showPreviewChangesDialog) { newSolution = FixAllGetFixesService.PreviewChanges( _workspace.CurrentSolution, newSolution, fixAllPreviewChangesTitle: title, fixAllTopLevelHeader: title, languageOpt: languages?.Count == 1 ? languages.Single() : null, workspace: _workspace); if (newSolution == null) { return false; } } waitDialogMessage = isAddSuppression ? ServicesVSResources.Applying_suppressions_fix : ServicesVSResources.Applying_remove_suppressions_fix; Action<IWaitContext> applyFix = context => { var operations = ImmutableArray.Create<CodeActionOperation>(new ApplyChangesOperation(newSolution)); var cancellationToken = context.CancellationToken; _editHandlerService.ApplyAsync( _workspace, fromDocument: null, operations: operations, title: title, progressTracker: context.ProgressTracker, cancellationToken: cancellationToken).Wait(cancellationToken); }; result = InvokeWithWaitDialog(applyFix, title, waitDialogMessage); if (result == WaitIndicatorResult.Canceled) { return false; } // Kick off diagnostic re-analysis for affected projects so that diagnostics gets refreshed. Task.Run(() => { var reanalyzeDocuments = diagnosticsToFix.Where(d => d.DocumentId != null).Select(d => d.DocumentId).Distinct(); _diagnosticService.Reanalyze(_workspace, documentIds: reanalyzeDocuments, highPriority: true); }); return true; } private static IEnumerable<DiagnosticData> FilterDiagnostics(IEnumerable<DiagnosticData> diagnostics, bool isAddSuppression, bool isSuppressionInSource, bool onlyCompilerDiagnostics) { foreach (var diagnostic in diagnostics) { var isCompilerDiagnostic = SuppressionHelpers.IsCompilerDiagnostic(diagnostic); if (onlyCompilerDiagnostics && !isCompilerDiagnostic) { continue; } if (isAddSuppression) { // Compiler diagnostics can only be suppressed in source. if (!diagnostic.IsSuppressed && (isSuppressionInSource || !isCompilerDiagnostic)) { yield return diagnostic; } } else if (diagnostic.IsSuppressed) { yield return diagnostic; } } } private WaitIndicatorResult InvokeWithWaitDialog( Action<IWaitContext> action, string waitDialogTitle, string waitDialogMessage) { var cancelled = false; var result = _waitIndicator.Wait( waitDialogTitle, waitDialogMessage, allowCancel: true, showProgress: true, action: waitContext => { try { action(waitContext); } catch (OperationCanceledException) { cancelled = true; } }); return cancelled ? WaitIndicatorResult.Canceled : result; } private static ImmutableDictionary<Document, ImmutableArray<Diagnostic>> GetDocumentDiagnosticsMappedToNewSolution(ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentDiagnosticsToFixMap, Solution newSolution, string language) { ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Builder builder = null; foreach (var kvp in documentDiagnosticsToFixMap) { if (kvp.Key.Project.Language != language) { continue; } var document = newSolution.GetDocument(kvp.Key.Id); if (document != null) { builder = builder ?? ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>(); builder.Add(document, kvp.Value); } } return builder != null ? builder.ToImmutable() : ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty; } private static ImmutableDictionary<Project, ImmutableArray<Diagnostic>> GetProjectDiagnosticsMappedToNewSolution(ImmutableDictionary<Project, ImmutableArray<Diagnostic>> projectDiagnosticsToFixMap, Solution newSolution, string language) { ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Builder projectDiagsBuilder = null; foreach (var kvp in projectDiagnosticsToFixMap) { if (kvp.Key.Language != language) { continue; } var project = newSolution.GetProject(kvp.Key.Id); if (project != null) { projectDiagsBuilder = projectDiagsBuilder ?? ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>(); projectDiagsBuilder.Add(project, kvp.Value); } } return projectDiagsBuilder != null ? projectDiagsBuilder.ToImmutable() : ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty; } private static CodeFixProvider GetSuppressionFixer(IEnumerable<Diagnostic> diagnostics, string language, ICodeFixService codeFixService) { // Fetch the suppression fixer to apply the fix. return codeFixService.GetSuppressionFixer(language, diagnostics.Select(d => d.Id)); } private async Task<ImmutableDictionary<Document, ImmutableArray<Diagnostic>>> GetDocumentDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken) { Func<DiagnosticData, bool> isDocumentDiagnostic = d => d.DataLocation != null && d.HasTextSpan; var builder = ImmutableDictionary.CreateBuilder<DocumentId, List<DiagnosticData>>(); foreach (var diagnosticData in diagnosticsToFix.Where(isDocumentDiagnostic)) { if (!builder.TryGetValue(diagnosticData.DocumentId, out var diagnosticsPerDocument)) { diagnosticsPerDocument = new List<DiagnosticData>(); builder[diagnosticData.DocumentId] = diagnosticsPerDocument; } diagnosticsPerDocument.Add(diagnosticData); } if (builder.Count == 0) { return ImmutableDictionary<Document, ImmutableArray<Diagnostic>>.Empty; } var finalBuilder = ImmutableDictionary.CreateBuilder<Document, ImmutableArray<Diagnostic>>(); var latestDocumentDiagnosticsMapOpt = filterStaleDiagnostics ? new Dictionary<DocumentId, ImmutableHashSet<DiagnosticData>>() : null; foreach (var group in builder.GroupBy(kvp => kvp.Key.ProjectId)) { var projectId = group.Key; var project = _workspace.CurrentSolution.GetProject(projectId); if (project == null || !shouldFixInProject(project)) { continue; } if (filterStaleDiagnostics) { var uniqueDiagnosticIds = group.SelectMany(kvp => kvp.Value.Select(d => d.Id)).ToImmutableHashSet(); var latestProjectDiagnostics = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken) .ConfigureAwait(false)).Where(isDocumentDiagnostic); latestDocumentDiagnosticsMapOpt.Clear(); foreach (var kvp in latestProjectDiagnostics.Where(d => d.DocumentId != null).GroupBy(d => d.DocumentId)) { latestDocumentDiagnosticsMapOpt.Add(kvp.Key, kvp.ToImmutableHashSet()); } } foreach (var documentDiagnostics in group) { var document = project.GetDocument(documentDiagnostics.Key); if (document == null) { continue; } IEnumerable<DiagnosticData> documentDiagnosticsToFix; if (filterStaleDiagnostics) { if (!latestDocumentDiagnosticsMapOpt.TryGetValue(document.Id, out var latestDocumentDiagnostics)) { // Ignore stale diagnostics in error list. latestDocumentDiagnostics = ImmutableHashSet<DiagnosticData>.Empty; } // Filter out stale diagnostics in error list. documentDiagnosticsToFix = documentDiagnostics.Value.Where(d => latestDocumentDiagnostics.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d)); } else { documentDiagnosticsToFix = documentDiagnostics.Value; } if (documentDiagnosticsToFix.Any()) { var diagnostics = await documentDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); finalBuilder.Add(document, diagnostics); } } } return finalBuilder.ToImmutableDictionary(); } private async Task<ImmutableDictionary<Project, ImmutableArray<Diagnostic>>> GetProjectDiagnosticsToFixAsync(IEnumerable<DiagnosticData> diagnosticsToFix, Func<Project, bool> shouldFixInProject, bool filterStaleDiagnostics, CancellationToken cancellationToken) { Func<DiagnosticData, bool> isProjectDiagnostic = d => d.DataLocation == null && d.ProjectId != null; var builder = ImmutableDictionary.CreateBuilder<ProjectId, List<DiagnosticData>>(); foreach (var diagnosticData in diagnosticsToFix.Where(isProjectDiagnostic)) { if (!builder.TryGetValue(diagnosticData.ProjectId, out var diagnosticsPerProject)) { diagnosticsPerProject = new List<DiagnosticData>(); builder[diagnosticData.ProjectId] = diagnosticsPerProject; } diagnosticsPerProject.Add(diagnosticData); } if (builder.Count == 0) { return ImmutableDictionary<Project, ImmutableArray<Diagnostic>>.Empty; } var finalBuilder = ImmutableDictionary.CreateBuilder<Project, ImmutableArray<Diagnostic>>(); var latestDiagnosticsToFixOpt = filterStaleDiagnostics ? new HashSet<DiagnosticData>() : null; foreach (var kvp in builder) { var projectId = kvp.Key; var project = _workspace.CurrentSolution.GetProject(projectId); if (project == null || !shouldFixInProject(project)) { continue; } var diagnostics = kvp.Value; IEnumerable<DiagnosticData> projectDiagnosticsToFix; if (filterStaleDiagnostics) { var uniqueDiagnosticIds = diagnostics.Select(d => d.Id).ToImmutableHashSet(); var latestDiagnosticsFromDiagnosticService = (await _diagnosticService.GetDiagnosticsForIdsAsync(project.Solution, project.Id, diagnosticIds: uniqueDiagnosticIds, includeSuppressedDiagnostics: true, cancellationToken: cancellationToken) .ConfigureAwait(false)); latestDiagnosticsToFixOpt.Clear(); latestDiagnosticsToFixOpt.AddRange(latestDiagnosticsFromDiagnosticService.Where(isProjectDiagnostic)); // Filter out stale diagnostics in error list. projectDiagnosticsToFix = diagnostics.Where(d => latestDiagnosticsFromDiagnosticService.Contains(d) || SuppressionHelpers.IsSynthesizedExternalSourceDiagnostic(d)); } else { projectDiagnosticsToFix = diagnostics; } if (projectDiagnosticsToFix.Any()) { var projectDiagnostics = await projectDiagnosticsToFix.ToDiagnosticsAsync(project, cancellationToken).ConfigureAwait(false); finalBuilder.Add(project, projectDiagnostics); } } return finalBuilder.ToImmutableDictionary(); } } }
using UnityEngine; using Stratus; using Stratus.Utilities; using System; using System.Linq; using System.Collections.Generic; namespace Stratus.Gameplay { /// <summary> /// A representation of a skill attack /// </summary> [RequireComponent(typeof(Collider))] [RequireComponent(typeof(MeshRenderer))] public class StratusSkillTelegraphBehaviour : StratusBehaviour { //------------------------------------------------------------------------/ // Declarations //------------------------------------------------------------------------/ public enum Delivery { [Tooltip("The telegraph is placed directly on top of the source")] Source, [Tooltip("The telegraph is placed directly on top of the target")] Target, [Tooltip("The telegraph is projected from the source to the target")] Projection } /// <summary> /// How the telegraph should be rendered /// </summary> [Serializable] public class Configuration { public GameObject Prefab; [Tooltip("How the skill should be delivered to the target")] public Delivery Delivery = Delivery.Target; public Material Material; public Color Color = Color.red; public Vector3 Scale = new Vector3(5f, 0.5f, 5f); [Tooltip("How closely the telegraph follows the target. if at all")] [Range(0f, 1f)] public float Damping = 1f; } /// <summary> /// Where the telegraph should be rendered /// </summary> public struct Placement { public Transform Source; public Vector3 Target; public Vector3 Rotation; public Placement(Transform source, Vector3 position, Vector3 rotation) { Source = source; Target = position; Rotation = rotation; } } //------------------------------------------------------------------------/ // Properties //------------------------------------------------------------------------/ public Configuration CurrentConfiguration = new Configuration(); //------------------------------------------------------------------------/ // Fields //------------------------------------------------------------------------/ private List<StratusCombatController> TargetsInsideArea = new List<StratusCombatController>(); //------------------------------------------------------------------------/ // Construction //------------------------------------------------------------------------/ public static StratusSkillTelegraphBehaviour Construct(Configuration config, Placement targeting) { var go = GameObject.Instantiate(config.Prefab); var telegraph = go.GetComponent<StratusSkillTelegraphBehaviour>(); //telegraph.conf telegraph.Configure(config, targeting); return telegraph; } //------------------------------------------------------------------------/ // Messages //------------------------------------------------------------------------/ /// <summary> /// Start with this telegraph being invisible. /// </summary> private void Start() { //Collider = GetComponent<Collider>(); //Trace.Script("Telegraph started!", this); //StartCoroutine(Routines.Fade(this.gameObject, 0f, 0f)); } private void Update() { } private void OnTriggerEnter(Collider other) { var target = other.gameObject.GetComponent<StratusCombatController>(); if (target != null) { //Trace.Script(target.name + " has entered the area!", this); TargetsInsideArea.Add(target); } } private void OnTriggerExit(Collider other) { var target = other.gameObject.GetComponent<StratusCombatController>(); if (target != null) { //Trace.Script(target.name + " has exited the area!", this); TargetsInsideArea.Remove(target); } } //------------------------------------------------------------------------/ // Routines //------------------------------------------------------------------------/ /// <summary> /// Fades in this telegraph. /// </summary> /// <param name="duration"></param> public void Start(float duration) { //Trace.Script("Displaying telegraph over " + duration + " seconds!", this); StartCoroutine(StratusRoutines.Fade(this.gameObject, 1f, duration)); } /// <summary> /// Fades out this telegraph. It will destroy it shortly after its been completely faded out. /// </summary> /// <param name="fadeSpeed"></param> public void End(float fadeSpeed, float destroySpeed = 0.0f) { //Trace.Script("Hiding telegraph over " + duration + " seconds!", this); StartCoroutine(StratusRoutines.Fade(this.gameObject, 0f, fadeSpeed)); if (destroySpeed > 0.0f) GameObject.Destroy(this.gameObject, destroySpeed); } /// <summary> /// Places this telegraph in the proper position /// </summary> /// <param name="placement"></param> public void Place(Placement placement, bool instant = false) { // Position if (CurrentConfiguration.Delivery == Delivery.Projection) ProjectFromSource(placement, instant); else if (CurrentConfiguration.Delivery == Delivery.Target) ProjectOnTarget(placement.Target, instant); else if (CurrentConfiguration.Delivery == Delivery.Source) transform.position = placement.Source.position; // Rotation transform.rotation = Quaternion.LookRotation(placement.Rotation); } /// <summary> /// Projects the telegraph so it emanates from the source towards the target /// </summary> /// <param name="placement"></param> void ProjectFromSource(Placement placement, bool instant) { // For the first part of the offset we will use the scale of the object var sourceOffset = placement.Source.localScale.magnitude; // For the second part we will add half the size of the depth (z) of the object. var telegraphOffset = CurrentConfiguration.Scale.z / 2; // Calculate the target position var target = placement.Source.position + (placement.Source.transform.forward * (sourceOffset + telegraphOffset)); if (instant) { transform.position = target; return; } // Interpolate to the new target position transform.position = Vector3.Lerp(transform.position, target, Time.fixedDeltaTime * CurrentConfiguration.Damping * 3); } /// <summary> /// Projects the telegraph directly on top of the target /// </summary> /// <param name="target"></param> void ProjectOnTarget(Vector3 target, bool instant) { if (instant) { transform.position = target; return; } // Interpolate to the new target position transform.position = Vector3.Lerp(transform.position, target, Time.fixedDeltaTime * CurrentConfiguration.Damping * 3); } void Configure(Configuration config, Placement placement) { CurrentConfiguration = config; // Rendering var renderer = GetComponent<MeshRenderer>(); renderer.material = config.Material; renderer.material.color = config.Color; renderer.material.color = renderer.material.color.ScaleAlpha(0f); // TRS transform.localScale = config.Scale; // Start with the telegraph on the target? Place(placement, true); } /// <summary> /// Finds all targets within the current telegraph object /// </summary> /// <param name="user"></param> /// <param name="target"></param> /// <param name="telegraphData"></param> /// <param name="type"></param> /// <returns></returns> public StratusCombatController[] FindTargetsWithinBoundary() { return TargetsInsideArea.ToArray(); } } }
// // Copyright (C) Microsoft. All rights reserved. // using System; using System.IO; using System.Reflection; using System.ComponentModel; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Management.Automation; using System.Management.Automation.Provider; using System.Xml; using System.Collections; using System.Collections.Generic; using System.Management.Automation.Runspaces; using System.Diagnostics.CodeAnalysis; using Dbg = System.Management.Automation; using System.Globalization; namespace Microsoft.WSMan.Management { #region Get-WSManInstance /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsCommon.Get, "WSManInstance", DefaultParameterSetName = "GetInstance", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141444")] public class GetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { #region parameter /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "GetInstance")] [Parameter(ParameterSetName = "Enumerate")] public String ApplicationName { get { return applicationname; } set { { applicationname = value; } } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "BasePropertiesOnly". /// Enumerate only those properties that are part of the base class /// specification in the Resource URI. When /// Shallow is specified then this flag has no effect /// </summary> [Parameter(ParameterSetName = "Enumerate")] [Alias("UBPO", "Base")] public SwitchParameter BasePropertiesOnly { get { return basepropertiesonly; } set { { basepropertiesonly = value; } } } private SwitchParameter basepropertiesonly; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "GetInstance")] [Parameter(ParameterSetName = "Enumerate")] [Alias("CN")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and Prefix, needed to connect to the /// remote machine. The format of this string is: /// transport://server:port/Prefix. /// </summary> [Parameter( ParameterSetName = "GetInstance")] [Parameter( ParameterSetName = "Enumerate")] [Alias("CURI", "CU")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { { connectionuri = value; } } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "Dialect". /// Defines the dialect for the filter predicate /// </summary> [Parameter] public Uri Dialect { get { return dialect; } set { { dialect = value; } } } private Uri dialect; /// <summary> /// The following is the definition of the input parameter "Enumerate". /// Switch indicates list all instances of a management resource. Equivalent to /// WSManagement Enumerate /// </summary> [Parameter(Mandatory = true, ParameterSetName = "Enumerate")] public SwitchParameter Enumerate { get { return enumerate; } set { { enumerate = value; } } } private SwitchParameter enumerate; /// <summary> /// The following is the definition of the input parameter "Filter". /// Indicates the filter expression for the enumeration /// </summary> [Parameter(ParameterSetName = "Enumerate")] [ValidateNotNullOrEmpty] public String Filter { get { return filter; } set { { filter = value; } } } private String filter; /// <summary> /// The following is the definition of the input parameter "Fragment". /// Specifies a section inside the instance that is to be updated or retrieved /// for the given operation /// </summary> [Parameter(ParameterSetName = "GetInstance")] [ValidateNotNullOrEmpty] public String Fragment { get { return fragment; } set { { fragment = value; } } } private String fragment; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hashtable and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter(ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] [Alias("OS")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable OptionSet { get { return optionset; } set { { optionset = value; } } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "Enumerate")] [Parameter(ParameterSetName = "GetInstance")] public Int32 Port { get { return port; } set { { port = value; } } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "Associations". /// Associations indicates retrieval of association instances as opposed to /// associated instances. This can only be used when specifying the Dialect as /// Association /// </summary> [Parameter(ParameterSetName = "Enumerate")] public SwitchParameter Associations { get { return associations; } set { { associations = value; } } } private SwitchParameter associations; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation /// </summary> [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [Alias("RURI")] public Uri ResourceURI { get { return resourceuri; } set { { resourceuri = value; } } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "ReturnType". /// Indicates the type of data returned. Possible options are 'Object', 'EPR', /// and 'ObjectAndEPR'. Default is Object. /// If Object is specified or if this parameter is absent then only the objects /// are returned /// If EPR is specified then only the EPRs of the objects /// are returned. EPRs contain information about the Resource URI and selectors /// for the instance /// If ObjectAndEPR is specified, then both the object and the associated EPRs /// are returned /// </summary> [Parameter(ParameterSetName = "Enumerate")] [ValidateNotNullOrEmpty] [ValidateSetAttribute(new string[] { "object", "epr", "objectandepr" })] [Alias("RT")] public String ReturnType { get { return returntype; } set { { returntype = value; } } } private String returntype="object"; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are are more than 1 instance of the resource /// class /// </summary> [Parameter( ParameterSetName = "GetInstance")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable SelectorSet { get { return selectorset; } set { { selectorset = value; } } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This can be /// created by using the cmdlet New-WSManSessionOption /// </summary> [Parameter] [ValidateNotNullOrEmpty] [Alias("SO")] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public SessionOption SessionOption { get { return sessionoption; } set { { sessionoption = value; } } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "Shallow". /// Enumerate only instances of the base class specified in the resource URI. If /// this flag is not specified, instances of the base class specified in the URI /// and all its derived classes are returned /// </summary> [Parameter(ParameterSetName = "Enumerate")] public SwitchParameter Shallow { get { return shallow; } set { { shallow = value; } } } private SwitchParameter shallow; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "GetInstance")] [Parameter(ParameterSetName = "Enumerate")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] [Alias("SSL")] public SwitchParameter UseSSL { get { return usessl; } set { { usessl = value; } } } private SwitchParameter usessl; #endregion parameter # region private WSManHelper helper; private string GetFilter() { string name; string value; string[] Split = filter.Trim().Split(new Char[] { '=', ';' }); if ((Split.Length)%2 != 0) { //mismatched property name/value pair return null; } filter = "<wsman:SelectorSet xmlns:wsman='http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd'>"; for (int i = 0; i<Split.Length; i+=2) { value = Split[i+1].Substring(1, Split[i+1].Length - 2); name = Split[i]; filter = filter + "<wsman:Selector Name='" + name + "'>" + value + "</wsman:Selector>"; } filter = filter + "</wsman:SelectorSet>"; return (filter.ToString()); } private void ReturnEnumeration(IWSManEx wsmanObject, IWSManResourceLocator wsmanResourceLocator, IWSManSession wsmanSession) { string fragment; try { int flags = 0; IWSManEnumerator obj; if (returntype != null) { if (returntype.Equals("object", StringComparison.CurrentCultureIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnObject(); } else if (returntype.Equals("epr", StringComparison.CurrentCultureIgnoreCase)) { flags = wsmanObject.EnumerationFlagReturnEPR(); } else { flags = wsmanObject.EnumerationFlagReturnObjectAndEPR(); } } if (shallow) { flags |= wsmanObject.EnumerationFlagHierarchyShallow(); } else if (basepropertiesonly) { flags |= wsmanObject.EnumerationFlagHierarchyDeepBasePropsOnly(); } else { flags |= wsmanObject.EnumerationFlagHierarchyDeep(); } if (dialect != null && filter != null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_WQL_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_ASSOCIATION_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { if (associations) { flags |= wsmanObject.EnumerationFlagAssociationInstance(); } else { flags |= wsmanObject.EnumerationFlagAssociatedInstance(); } fragment = helper.URI_ASSOCIATION_DIALECT; dialect = new Uri(fragment); } else if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase) || dialect.ToString().Equals(helper.URI_SELECTOR_DIALECT, StringComparison.CurrentCultureIgnoreCase)) { filter = GetFilter(); fragment = helper.URI_SELECTOR_DIALECT; dialect = new Uri(fragment); } obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else if (filter != null) { fragment = helper.URI_WQL_DIALECT; dialect = new Uri(fragment); obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, dialect.ToString(), flags); } else { obj = (IWSManEnumerator)wsmanSession.Enumerate(wsmanResourceLocator, filter, null, flags); } while (!obj.AtEndOfStream) { XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(obj.ReadItem()); WriteObject(xmldoc.FirstChild); } } catch (Exception ex) { ErrorRecord er = new ErrorRecord(ex, "Exception", ErrorCategory.InvalidOperation, null); WriteError(er); } } # endregion private # region override /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { IWSManSession m_session = null; IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); helper = new WSManHelper(this); helper.WSManOp = "Get"; string connectionStr = null; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { //in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } try { IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); if (!enumerate) { XmlDocument xmldoc = new XmlDocument(); try { xmldoc.LoadXml(m_session.Get(m_resource, 0)); } catch(XmlException ex) { helper.AssertError(ex.Message, false, computername); } if (!string.IsNullOrEmpty(fragment)) { WriteObject(xmldoc.FirstChild.LocalName + "=" + xmldoc.FirstChild.InnerText); } else { WriteObject(xmldoc.FirstChild); } } else { try { ReturnEnumeration(m_wsmanObject, m_resource, m_session); } catch (Exception ex) { helper.AssertError(ex.Message, false, computername); } } } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } } #endregion override #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void EndProcessing() { helper.CleanUp(); } } #endregion #region Set-WsManInstance /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsCommon.Set, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141458")] public class SetWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { #region Parameters /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public String ApplicationName { get { return applicationname; } set { applicationname = value; } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "Dialect". /// Defines the dialect for the filter predicate /// </summary> [Parameter] [ValidateNotNullOrEmpty] public Uri Dialect { get { return dialect; } set { dialect = value; } } private Uri dialect; /// <summary> /// The following is the definition of the input parameter "FilePath". /// Updates the management resource specified by the ResourceURI and SelectorSet /// via this input file /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [ValidateNotNullOrEmpty] public string FilePath { get { return filepath; } set { filepath = value; } } private string filepath; /// <summary> /// The following is the definition of the input parameter "Fragment". /// Specifies a section inside the instance that is to be updated or retrieved /// for the given operation /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] public String Fragment { get { return fragment; } set { fragment = value; } } private String fragment; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hahs table which help modify or refine the nature of the /// request. These are similar to switches used in command line shells in that /// they are service-specific /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] [ValidateNotNullOrEmpty] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] [Parameter(Mandatory = true, Position = 0)] [Alias("ruri")] [ValidateNotNullOrEmpty] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are are more than 1 instance of the resource /// class /// </summary> [Parameter(Position = 1, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [ValidateNotNullOrEmpty] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This can be created /// by using the cmdlet New-WSManSessionOption /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] [ValidateNotNullOrEmpty] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] [Alias("ssl")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; /// <summary> /// The following is the definition of the input parameter "ValueSet". /// ValueSet is a hash table which helps to modify resource represented by the /// ResourceURI and SelectorSet. /// </summary> [Parameter(ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [ValidateNotNullOrEmpty] public Hashtable ValueSet { get { return valueset; } set { valueset = value; } } private Hashtable valueset; #endregion private WSManHelper helper ; /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); helper = new WSManHelper(this); helper.WSManOp = "set"; IWSManSession m_session = null; if (dialect != null) { if (dialect.ToString().Equals(helper.ALIAS_WQL, StringComparison.CurrentCultureIgnoreCase)) dialect = new Uri(helper.URI_WQL_DIALECT); if (dialect.ToString().Equals(helper.ALIAS_SELECTOR, StringComparison.CurrentCultureIgnoreCase)) dialect = new Uri(helper.URI_SELECTOR_DIALECT); if (dialect.ToString().Equals(helper.ALIAS_ASSOCIATION, StringComparison.CurrentCultureIgnoreCase)) dialect = new Uri(helper.URI_ASSOCIATION_DIALECT); } try { string connectionStr = String.Empty; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { //in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, fragment, dialect, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); XmlDocument xmldoc = new XmlDocument(); try { xmldoc.LoadXml(m_session.Put(m_resource, input, 0)); } catch(XmlException ex) { helper.AssertError(ex.Message, false, computername); } if (!string.IsNullOrEmpty(fragment)) { if (xmldoc.DocumentElement.ChildNodes.Count > 0) { foreach (XmlNode node in xmldoc.DocumentElement.ChildNodes) { if (node.Name.Equals(fragment, StringComparison.CurrentCultureIgnoreCase)) WriteObject(node.Name + " = " + node.InnerText); } } } else WriteObject(xmldoc.DocumentElement); } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } }//End ProcessRecord() #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// BeginProcessing method. /// </summary> protected override void EndProcessing() { helper.CleanUp(); } } #endregion #region Remove-WsManInstance /// <summary> /// Executes action on a target object specified by RESOURCE_URI, where /// parameters are specified by key value pairs. /// eg., Call StartService method on the spooler service /// Set-WSManInstance -Action StartService -ResourceURI wmicimv2/Win32_Service /// -SelectorSet {Name=Spooler} /// </summary> [Cmdlet(VerbsCommon.Remove, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141453")] public class RemoveWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { #region Parameters /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public String ApplicationName { get { return applicationname; } set { applicationname = value; } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hahs table which help modify or refine the nature of the /// request. These are similar to switches used in command line shells in that /// they are service-specific /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] [ValidateNotNullOrEmpty] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation /// </summary> [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Resourceuri")] [Parameter(Mandatory = true, Position = 0)] [Alias("ruri")] [ValidateNotNullOrEmpty] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are are more than 1 instance of the resource /// class /// </summary> [Parameter(Position = 1, Mandatory = true, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [ValidateNotNullOrEmpty] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. This can be created /// by using the cmdlet New-WSManSessionOption /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] [ValidateNotNullOrEmpty] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] [Alias("ssl")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; #endregion /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { WSManHelper helper = new WSManHelper(this); IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); helper.WSManOp = "remove"; IWSManSession m_session = null; try { string connectionStr = String.Empty; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { //in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string ResourceURI = helper.GetURIWithFilter(resourceuri.ToString(), null, selectorset, helper.WSManOp); try { ((IWSManSession)m_session).Delete(ResourceURI, 0); } catch (Exception ex) { helper.AssertError(ex.Message, false, computername); } } finally { if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (m_session != null) Dispose(m_session); } }//End ProcessRecord() #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members } #endregion #region New-WsManInstance /// <summary> /// Creates an instance of a management resource identified by the resource URI /// using specified ValueSet or input File /// </summary> [Cmdlet(VerbsCommon.New, "WSManInstance", DefaultParameterSetName = "ComputerName", HelpUri = "https://go.microsoft.com/fwlink/?LinkId=141448")] public class NewWSManInstanceCommand : AuthenticatingWSManCommand, IDisposable { /// <summary> /// The following is the definition of the input parameter "ApplicationName". /// ApplicationName identifies the remote endpoint. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] public String ApplicationName { get { return applicationname; } set { applicationname = value; } } private String applicationname = null; /// <summary> /// The following is the definition of the input parameter "ComputerName". /// Executes the management operation on the specified computer(s). The default /// is the local computer. Type the fully qualified domain name, NETBIOS name or /// IP address to indicate the remote host(s) /// </summary> [Parameter(ParameterSetName = "ComputerName")] [Alias("cn")] public String ComputerName { get { return computername; } set { computername = value; if ((string.IsNullOrEmpty(computername)) || (computername.Equals(".", StringComparison.CurrentCultureIgnoreCase))) { computername = "localhost"; } } } private String computername = null; /// <summary> /// The following is the definition of the input parameter "ConnectionURI". /// Specifies the transport, server, port, and ApplicationName of the new /// runspace. The format of this string is: /// transport://server:port/ApplicationName. /// </summary> [Parameter(ParameterSetName = "URI")] [ValidateNotNullOrEmpty] [Alias("CURI", "CU")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ConnectionURI { get { return connectionuri; } set { connectionuri = value; } } private Uri connectionuri; /// <summary> /// The following is the definition of the input parameter "FilePath". /// Updates the management resource specified by the ResourceURI and SelectorSet /// via this input file /// </summary> [Parameter] [ValidateNotNullOrEmpty] public String FilePath { get { return filepath; } set { filepath = value; } } private String filepath; /// <summary> /// The following is the definition of the input parameter "OptionSet". /// OptionSet is a hash table and is used to pass a set of switches to the /// service to modify or refine the nature of the request. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("os")] public Hashtable OptionSet { get { return optionset; } set { optionset = value; } } private Hashtable optionset; /// <summary> /// The following is the definition of the input parameter "Port". /// Specifies the port to be used when connecting to the ws management service. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [ValidateNotNullOrEmpty] [ValidateRange(1, Int32.MaxValue)] public Int32 Port { get { return port; } set { port = value; } } private Int32 port = 0; /// <summary> /// The following is the definition of the input parameter "ResourceURI". /// URI of the resource class/instance representation /// </summary> [Parameter(Mandatory = true, Position = 0)] [ValidateNotNullOrEmpty] [Alias("ruri")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "URI")] public Uri ResourceURI { get { return resourceuri; } set { resourceuri = value; } } private Uri resourceuri; /// <summary> /// The following is the definition of the input parameter "SelectorSet". /// SelectorSet is a hash table which helps in identify an instance of the /// management resource if there are are more than 1 instance of the resource /// class /// </summary> [Parameter(Mandatory = true, Position = 1, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable SelectorSet { get { return selectorset; } set { selectorset = value; } } private Hashtable selectorset; /// <summary> /// The following is the definition of the input parameter "SessionOption". /// Defines a set of extended options for the WSMan session. /// </summary> [Parameter] [ValidateNotNullOrEmpty] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] [Alias("so")] public SessionOption SessionOption { get { return sessionoption; } set { sessionoption = value; } } private SessionOption sessionoption; /// <summary> /// The following is the definition of the input parameter "UseSSL". /// Uses the Secure Sockets Layer (SSL) protocol to establish a connection to /// the remote computer. If SSL is not available on the port specified by the /// Port parameter, the command fails. /// </summary> [Parameter(ParameterSetName = "ComputerName")] [SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "SSL")] public SwitchParameter UseSSL { get { return usessl; } set { usessl = value; } } private SwitchParameter usessl; /// <summary> /// The following is the definition of the input parameter "ValueSet". /// ValueSet is a hash table which helps to modify resource represented by the /// ResourceURI and SelectorSet. /// </summary> [Parameter] [SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public Hashtable ValueSet { get { return valueset; } set { valueset = value; } } private Hashtable valueset; private WSManHelper helper; IWSManEx m_wsmanObject = (IWSManEx)new WSManClass(); IWSManSession m_session = null; string connectionStr = String.Empty; /// <summary> /// BeginProcessing method. /// </summary> protected override void BeginProcessing() { helper = new WSManHelper(this ); helper.WSManOp = "new"; connectionStr = helper.CreateConnectionString(connectionuri, port, computername, applicationname); if (connectionuri != null) { try { //in the format http(s)://server[:port/applicationname] string[] constrsplit = connectionuri.OriginalString.Split(new string[] { ":" + port + "/" + applicationname }, StringSplitOptions.None); string[] constrsplit1 = constrsplit[0].Split(new string[] { "//" }, StringSplitOptions.None); computername = constrsplit1[1].Trim(); } catch (IndexOutOfRangeException) { helper.AssertError(helper.GetResourceMsgFromResourcetext("NotProperURI"), false, connectionuri); } } }//End BeginProcessing() /// <summary> /// ProcessRecord method. /// </summary> protected override void ProcessRecord() { try { IWSManResourceLocator m_resource = helper.InitializeResourceLocator(optionset, selectorset, null, null, m_wsmanObject, resourceuri); //create the session object m_session = helper.CreateSessionObject(m_wsmanObject, Authentication, sessionoption, Credential, connectionStr, CertificateThumbprint, usessl.IsPresent); string rootNode = helper.GetRootNodeName(helper.WSManOp, m_resource.ResourceUri, null); string input = helper.ProcessInput(m_wsmanObject, filepath, helper.WSManOp, rootNode, valueset, m_resource, m_session); try { string resultXml = m_session.Create(m_resource, input, 0); XmlDocument xmldoc = new XmlDocument(); xmldoc.LoadXml(resultXml); WriteObject(xmldoc.DocumentElement); } catch (Exception ex) { helper.AssertError(ex.Message, false, computername); } } finally { if (!String.IsNullOrEmpty(m_wsmanObject.Error)) { helper.AssertError(m_wsmanObject.Error, true, resourceuri); } if (!String.IsNullOrEmpty(m_session.Error)) { helper.AssertError(m_session.Error, true, resourceuri); } if (m_session != null) { Dispose(m_session); } } }//End ProcessRecord() #region IDisposable Members /// <summary> /// public dispose method /// </summary> public void Dispose() { //CleanUp(); GC.SuppressFinalize(this); } /// <summary> /// public dispose method /// </summary> public void Dispose(IWSManSession sessionObject) { sessionObject = null; this.Dispose(); } #endregion IDisposable Members /// <summary> /// EndProcessing method. /// </summary> protected override void EndProcessing() { helper.CleanUp(); }//End EndProcessing() }//End Class #endregion }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class ErrorEvent : PortsTest { //Maximum time to wait for all of the expected events to be firered private const int MAX_TIME_WAIT = 5000; private const int NUM_TRYS = 5; #region Test Cases /* This was already commented-out in the code which came to CoreFx from legacy public bool ErrorEvent_TXFull() { SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); int elapsedTime; Debug.WriteLine("Verifying TXFull event"); com1.Handshake = Handshake.RequestToSend; com1.Open(); com2.Open(); com1.ErrorEvent += new SerialErrorEventHandler(errEventHandler.HandleEvent); com1.BaseStream.BeginWrite(new byte[32767], 0, 32767, null, null); elapsedTime = 0; while(1 > errEventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); elapsedTime += ITERATION_TIME_WAIT; } retValue &= errEventHandler.Validate(SerialErrors.TxFull, com1.ReceivedBytesThreshold, 0); if(!retValue) { Debug.WriteLine("Err_001!!! Verifying TXFull event FAILED"); } if(com1.IsOpen) com1.Close(); if(com2.IsOpen) com2.Close(); return retValue; } */ [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void ErrorEvent_RxOver() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); Debug.WriteLine("Verifying RxOver event"); com1.Handshake = Handshake.RequestToSend; com1.BaudRate = 115200; com2.BaudRate = 115200; com1.Open(); com2.Open(); //This might not be necessary but it will clear the RTS pin when the buffer is too full com1.Handshake = Handshake.RequestToSend; com1.ErrorReceived += errEventHandler.HandleEvent; //This is overkill should find a more reasonable amount of bytes to write com2.BaseStream.Write(new byte[32767], 0, 32767); Assert.True(errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1), "Event never occurred"); while (0 < errEventHandler.NumEventsHandled) { errEventHandler.Validate(SerialError.RXOver, -1); } lock (com1) { if (com1.IsOpen) com1.Close(); } } } /* This was already commented-out in the code which came to CoreFx from legacy public bool ErrorEvent_Overrun() { SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName); SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName); ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); int elapsedTime; Debug.WriteLine("Verifying Overrun event"); com1.Handshake = Handshake.RequestToSend; com1.BaudRate = 115200; com2.BaudRate = 115200; com1.Open(); com2.Open(); com1.ErrorEvent += new SerialErrorEventHandler(errEventHandler.HandleEvent); com2.BaseStream.Write(new byte[32767], 0, 32767); elapsedTime = 0; while(1 > errEventHandler.NumEventsHandled && elapsedTime < MAX_TIME_WAIT) { System.Threading.Thread.Sleep(ITERATION_TIME_WAIT); elapsedTime += ITERATION_TIME_WAIT; } retValue &= errEventHandler.Validate(SerialErrors.Overrun, com1.ReceivedBytesThreshold, 0); if(!retValue) { Debug.WriteLine("Err_003!!! Verifying Overrun event FAILED"); } if(com1.IsOpen) com1.Close(); if(com2.IsOpen) com2.Close(); return retValue; } */ [ConditionalFact(nameof(HasNullModem))] public void ErrorEvent_RxParity() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); Debug.WriteLine("Verifying RxParity event"); com1.DataBits = 7; com1.Parity = Parity.Mark; com1.Open(); com2.Open(); com1.ErrorReceived += errEventHandler.HandleEvent; for (int i = 0; i < NUM_TRYS; i++) { Debug.WriteLine("Verifying RxParity event try: {0}", i); com2.BaseStream.Write(new byte[8], 0, 8); Assert.True(errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)); while (0 < errEventHandler.NumEventsHandled) { errEventHandler.Validate(SerialError.RXParity, -1); } } lock (com1) { if (com1.IsOpen) com1.Close(); } } } [ConditionalFact(nameof(HasNullModem))] public void ErrorEvent_Frame() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); Debug.WriteLine("Verifying Frame event"); com1.DataBits = 7; //com1.StopBits = StopBits.Two; com1.Open(); com2.Open(); com1.ErrorReceived += errEventHandler.HandleEvent; //This should cause a frame error since the 8th bit is not set //and com1 is set to 7 data bits ao the 8th bit will +12v where //com1 expects the stop bit at the 8th bit to be -12v var frameErrorBytes = new byte[] { 0x01 }; for (int i = 0; i < NUM_TRYS; i++) { Debug.WriteLine("Verifying Frame event try: {0}", i); com2.BaseStream.Write(frameErrorBytes, 0, 1); errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); while (0 < errEventHandler.NumEventsHandled) { errEventHandler.Validate(SerialError.Frame, -1); } } lock (com1) { if (com1.IsOpen) com1.Close(); } } } #endregion #region Verification for Test Cases private class ErrorEventHandler : TestEventHandler<SerialError> { public ErrorEventHandler(SerialPort com) : base(com, false, false) { } public void HandleEvent(object source, SerialErrorReceivedEventArgs e) { HandleEvent(source, e.EventType); } } #endregion } }
// Copyright (c) 2010-2014, Eric Maupin // 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 Gablarski nor the names of its // contributors may be used to endorse or promote products // or services derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS // AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Gablarski.Audio; using Gablarski.Messages; using Tempest; using Tempest.Providers.Network; namespace Gablarski.Client { public class GablarskiClient : IGablarskiClientContext { public static async Task<QueryResults> QueryAsync (RSAAsymmetricKey key, Target target, TimeSpan timeout) { if (key == null) throw new ArgumentNullException ("key"); if (target == null) throw new ArgumentNullException ("target"); var tcs = new TaskCompletionSource<QueryResults>(); var connection = new UdpClientConnection (GablarskiProtocol.Instance, key); connection.Start (MessageTypes.Unreliable); var cancelSources = new CancellationTokenSource (timeout); cancelSources.Token.Register (() => { tcs.TrySetCanceled(); connection.Dispose(); }); connection.ConnectionlessMessageReceived += (sender, args) => { var results = args.Message as QueryServerResultMessage; if (results == null) return; tcs.TrySetResult (new QueryResults (results.ServerInfo, results.Channels, results.Users)); connection.Dispose(); }; await connection.SendConnectionlessMessageAsync (new QueryServerMessage(), target).ConfigureAwait (false); return await tcs.Task.ConfigureAwait (false); } public GablarskiClient (RSAAsymmetricKey key) { if (key == null) throw new ArgumentNullException ("key"); Setup (new UdpClientConnection (GablarskiProtocol.Instance, key), null, null, null, null); } /// <summary> /// The client has connected to the server. /// </summary> public event EventHandler Connected; /// <summary> /// The connection to the server has been rejected. /// </summary> public event EventHandler<RejectedConnectionEventArgs> ConnectionRejected; /// <summary> /// Permission was denied to requested action. /// </summary> public event EventHandler<PermissionDeniedEventArgs> PermissionDenied; /// <summary> /// The connection to the server has been lost (or forcibly closed.) /// </summary> public event EventHandler<DisconnectedEventArgs> Disconnected; /// <summary> /// Gets whether the client is currently trying to connect or reconnect. /// </summary> public bool IsConnecting { get { return this.connecting; } } public bool IsConnected { get { return this.formallyConnected; } } /// <summary> /// Gets the channel manager for this client. /// </summary> public ClientChannelManager Channels { get; private set; } /// <summary> /// Gets the user manager for this client. /// </summary> public IClientUserHandler Users { get; private set; } /// <summary> /// Gets the source manager for this client. /// </summary> public IClientSourceHandler Sources { get; private set; } /// <summary> /// Gets the audio engine responsible for playback and capture /// </summary> public IAudioEngine Audio { get; private set; } /// <summary> /// Gets the current user. /// </summary> public ICurrentUserHandler CurrentUser { get; private set; } /// <summary> /// Gets the current channel the user is in. /// </summary> public IChannelInfo CurrentChannel { get { return this.Channels[this.CurrentUser.CurrentChannelId]; } } /// <summary> /// Gets the <see cref="ServerInfo"/> for the currently connected server. <c>null</c> if not connected. /// </summary> public ServerInfo ServerInfo { get { return this.serverInfo; } } private bool reconnectAutomatically = true; /// <summary> /// Gets or sets whether to reconnect automatically on disconnection. <c>true</c> by default. /// </summary> /// <seealso cref="ReconnectAttemptFrequency"/> public bool ReconnectAutomatically { get { return reconnectAutomatically; } set { reconnectAutomatically = value; } } private int reconnectAttemptFrequency = 2000; private bool formallyConnected; /// <summary> /// Gets or sets the frequency (ms) at which to attempt reconnection. (2s default). /// </summary> public int ReconnectAttemptFrequency { get { return reconnectAttemptFrequency; } set { reconnectAttemptFrequency = value; } } public Task<ClientConnectionResult> ConnectAsync (Target target) { this.previousTarget = target; this.running = true; return this.client.ConnectAsync (target); } public Task DisconnectAsync() { return this.client.DisconnectAsync (ConnectionResult.Custom, DisconnectReasonRequested); } IIndexedEnumerable<int, IChannelInfo> IGablarskiClientContext.Channels { get { return this.Channels; } } private void Setup (IClientConnection connection, IAudioEngine audioEngine, IClientUserHandler userHandler, IClientSourceHandler sourceHandler, ClientChannelManager channelManager) { this.client = new TempestClient (connection, MessageTypes.All); this.client.Connected += OnClientConnected; this.client.Disconnected += OnClientDisconnected; this.CurrentUser = new CurrentUser (this); this.Audio = (audioEngine ?? new AudioEngine()); this.Users = (userHandler ?? new ClientUserHandler (this, new ClientUserManager())); this.Sources = (sourceHandler ?? new ClientSourceHandler (this, new ClientSourceManager (this))); this.Channels = (channelManager ?? new ClientChannelManager (this)); this.RegisterMessageHandler<PermissionDeniedMessage> (OnPermissionDeniedMessage); this.RegisterMessageHandler<RedirectMessage> (OnRedirectMessage); this.RegisterMessageHandler<ServerInfoMessage> (OnServerInfoReceivedMessage); //this.RegisterMessageHandler<ConnectionRejectedMessage> (OnConnectionRejectedMessage); this.RegisterMessageHandler<DisconnectMessage> (OnDisconnectedMessage); } private Target previousTarget; protected readonly object StateSync = new object(); protected ServerInfo serverInfo; protected readonly bool DebugLogging; private int redirectLimit = 20; private int redirectCount; private IPEndPoint originalEndPoint; private int disconnectedInChannelId; private string originalHost; private int reconnectAttempt; private bool connecting, running; private TempestClient client; protected void OnConnected (object sender, EventArgs e) { this.connecting = false; Interlocked.Exchange (ref this.reconnectAttempt, 0); var connected = this.Connected; if (connected != null) connected (this, e); } protected void OnDisconnected (object sender, DisconnectedEventArgs e) { var disconnected = this.Disconnected; if (disconnected != null) disconnected (this, e); } protected void OnConnectionRejected (RejectedConnectionEventArgs e) { this.connecting = false; e.Reconnect = (e.Reason == ConnectionRejectedReason.CouldNotConnect || e.Reason == ConnectionRejectedReason.Unknown); var rejected = this.ConnectionRejected; if (rejected != null) rejected (this, e); DisconnectCore (DisconnectionReason.Rejected, this.client.Connection, e.Reconnect, false); } protected void OnPermissionDenied (PermissionDeniedEventArgs e) { var denied = this.PermissionDenied; if (denied != null) denied (this, e); } private void OnDisconnectedMessage (MessageEventArgs<DisconnectMessage> e) { DisconnectCore (e.Message.Reason, (IClientConnection)e.Connection, (GetHandlingForReason (e.Message.Reason) == DisconnectHandling.Reconnect), true); } private void OnPermissionDeniedMessage (MessageEventArgs<PermissionDeniedMessage> e) { OnPermissionDenied (new PermissionDeniedEventArgs (e.Message.DeniedMessage)); } private void OnServerInfoReceivedMessage (MessageEventArgs<ServerInfoMessage> e) { this.serverInfo = e.Message.ServerInfo; this.formallyConnected = true; OnConnected (this, EventArgs.Empty); } private void OnRedirectMessage (MessageEventArgs<RedirectMessage> e) { int count = Interlocked.Increment (ref this.redirectCount); DisconnectCore (DisconnectionReason.Redirected, this.client.Connection); if (count > redirectLimit) return; ConnectAsync (new Target (e.Message.Host, e.Message.Port)); } private enum DisconnectHandling { None, Reconnect } private DisconnectHandling GetHandlingForReason (DisconnectionReason reason) { if (!ReconnectAutomatically) return DisconnectHandling.None; switch (reason) { case DisconnectionReason.Unknown: return DisconnectHandling.Reconnect; default: return DisconnectHandling.None; } } private void DisconnectCore (DisconnectionReason reason, IClientConnection connection) { DisconnectCore (reason, connection, GetHandlingForReason (reason) == DisconnectHandling.Reconnect, true); } private void DisconnectCore (DisconnectionReason reason, IClientConnection connection, bool reconnect, bool fireEvent) { lock (StateSync) { disconnectedInChannelId = CurrentUser.CurrentChannelId; this.connecting = false; this.running = false; this.formallyConnected = false; CurrentUser = new CurrentUser (this); this.Users.Reset(); this.Channels.Clear(); this.Sources.Reset(); this.Audio.Stop(); connection.DisconnectAsync(); if (fireEvent) OnDisconnected (this, new DisconnectedEventArgs (reason)); if (reconnect) { this.connecting = true; ThreadPool.QueueUserWorkItem (Reconnect); } } } private void Reconnect (object state) { Interlocked.Increment (ref this.reconnectAttempt); Thread.Sleep (ReconnectAttemptFrequency); lock (StateSync) { if (!this.running && !this.connecting) return; } CurrentUser.ReceivedJoinResult += ReconnectJoinedResult; ConnectAsync (this.previousTarget); } private void ReconnectJoinedResult (object sender, ReceivedJoinResultEventArgs e) { if (e.Result != LoginResultState.Success) return; IChannelInfo channel = this.Channels[this.disconnectedInChannelId]; if (channel != null) this.Users.Move (this.CurrentUser, channel); this.disconnectedInChannelId = 0; } private const string DisconnectReasonRequested = "Requested"; private void OnClientDisconnected (object sender, ClientDisconnectedEventArgs e) { DisconnectionReason reason = DisconnectionReason.Unknown; if (e.Reason == ConnectionResult.Custom) { switch (e.CustomReason) { case DisconnectReasonRequested: reason = DisconnectionReason.Requested; break; } } DisconnectCore (reason, this.client.Connection); } private void OnClientConnected (object sender, ClientConnectionEventArgs e) { lock (StateSync) { if (!this.running) { this.client.DisconnectAsync(); return; } client.Connection.SendAsync (new ConnectMessage { ProtocolVersion = 14 }); //Host = this.originalHost, Port = this.originalEndPoint.Port if (Audio.AudioSender == null) Audio.AudioSender = Sources; if (Audio.AudioReceiver == null) Audio.AudioReceiver = Sources; Audio.Context = this; Audio.Start(); } } void IContext.LockHandlers() { this.client.LockHandlers(); } void IContext.RegisterConnectionlessMessageHandler (Protocol protocol, ushort messageType, Action<ConnectionlessMessageEventArgs> handler) { this.client.RegisterConnectionlessMessageHandler (protocol, messageType, handler); } void IContext.RegisterMessageHandler (Protocol protocol, ushort messageType, Action<MessageEventArgs> handler) { this.client.RegisterMessageHandler (protocol, messageType, handler); } IClientConnection IClientContext.Connection { get { return this.client.Connection; } } } #region Event Args public class PermissionDeniedEventArgs : EventArgs { public PermissionDeniedEventArgs (GablarskiMessageType messageType) { DeniedMessage = messageType; } /// <summary> /// Gets the message type that was denied. /// </summary> public GablarskiMessageType DeniedMessage { get; private set; } } public class RejectedConnectionEventArgs : EventArgs { public RejectedConnectionEventArgs (ConnectionRejectedReason reason, int reconnectAttempt) { this.Reason = reason; ReconnectAttempt = reconnectAttempt; Reconnect = true; } /// <summary> /// Gets the reason for rejecting the connection. /// </summary> public ConnectionRejectedReason Reason { get; private set; } /// <summary> /// Gets the reconnect attempt number. 0 = not an attempt. /// </summary> public int ReconnectAttempt { get; private set; } /// <summary> /// Gets whether this was a reconnect attempt failing or not. /// </summary> public bool Reconnecting { get { return ReconnectAttempt != 0; } } /// <summary> /// Gets or sets whether to attempt to reconnect. /// </summary> public bool Reconnect { get; set; } } public class ReceivedListEventArgs<T> : EventArgs { public ReceivedListEventArgs (IEnumerable<T> data) { this.Data = data; } public IEnumerable<T> Data { get; private set; } } /// <summary> /// Holds data for the <see cref="GablarskiClient.Disconnected"/> event. /// </summary> public class DisconnectedEventArgs : EventArgs { public DisconnectedEventArgs (DisconnectionReason reason) { Reason = reason; } public DisconnectionReason Reason { get; private set; } } #endregion }
/* * Copyright (c) 2018 Algolia * http://www.algolia.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using System; using System.Collections; using System.Globalization; using System.Linq; using System.Reflection; using System.Threading; using System.Threading.Tasks; namespace Algolia.Search.Test { internal static class TestHelper { internal static string ApplicationId1 = Environment.GetEnvironmentVariable("ALGOLIA_APPLICATION_ID_1"); internal static string AdminKey1 = Environment.GetEnvironmentVariable("ALGOLIA_ADMIN_KEY_1"); internal static string SearchKey1 = Environment.GetEnvironmentVariable("ALGOLIA_SEARCH_KEY_1"); internal static string ApplicationId2 = Environment.GetEnvironmentVariable("ALGOLIA_APPLICATION_ID_2"); internal static string AdminKey2 = Environment.GetEnvironmentVariable("ALGOLIA_ADMIN_KEY_2"); internal static string McmApplicationId = Environment.GetEnvironmentVariable("ALGOLIA_APPLICATION_ID_MCM"); internal static string McmAdminKey = Environment.GetEnvironmentVariable("ALGOLIA_ADMIN_KEY_MCM"); /// <summary> /// Check env variable before starting tests suite /// </summary> internal static void CheckEnvironmentVariable() { if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_APPLICATION_ID_1"))) { throw new ArgumentNullException("Please set the following environment variable : ALGOLIA_ADMIN_KEY_1"); } if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_ADMIN_KEY_1"))) { throw new ArgumentNullException("Please set the following environment variable : ALGOLIA_ADMIN_KEY_1"); } if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_SEARCH_KEY_1"))) { throw new ArgumentNullException("Please set the following environment variable : ALGOLIA_SEARCH_KEY_1"); } if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_APPLICATION_ID_2"))) { throw new ArgumentNullException("Please set the following environment variable : ALGOLIA_ADMIN_KEY_2"); } if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_ADMIN_KEY_2"))) { throw new ArgumentNullException("Please set the following environment variable : ALGOLIA_ADMIN_KEY_2"); } if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_APPLICATION_ID_MCM"))) { throw new ArgumentNullException( "Please set the following environment variable : ALGOLIA_APPLICATION_ID_MCM"); } if (string.IsNullOrWhiteSpace(Environment.GetEnvironmentVariable("ALGOLIA_ADMIN_KEY_MCM"))) { throw new ArgumentNullException( "Please set the following environment variable : ALGOLIA_ADMIN_KEY_MCM"); } } internal static string GetTestIndexName(string testName) { var date = DateTime.UtcNow.ToString("yyyy-MM-dd_HH:mm:ss", CultureInfo.InvariantCulture); return $"csharp_{Environment.OSVersion.Platform}_{date}_{Environment.UserName}_{testName}"; } internal static string GetMcmUserId() { var date = DateTime.UtcNow.ToString("yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture); return $"csharp-{date}-{Environment.UserName}"; } /// <summary> /// https://www.cyotek.com/blog/comparing-the-properties-of-two-objects-via-reflection /// Compares the properties of two objects of the same type and returns if all properties are equal. /// </summary> /// <param name="objectA">The first object to compare.</param> /// <param name="objectB">The second object to compre.</param> /// <param name="ignoreList">A list of property names to ignore from the comparison.</param> /// <returns><c>true</c> if all property values are equal, otherwise <c>false</c>.</returns> internal static bool AreObjectsEqual(object objectA, object objectB, params string[] ignoreList) { bool result; if (objectA != null && objectB != null) { var objectType = objectA.GetType(); result = true; // assume by default they are equal foreach (PropertyInfo propertyInfo in objectType .GetProperties(BindingFlags.Public | BindingFlags.Instance) .Where(p => p.CanRead && !ignoreList.Contains(p.Name))) { var valueA = propertyInfo.GetValue(objectA, null); var valueB = propertyInfo.GetValue(objectB, null); // if it is a primative type, value type or implements IComparable, just directly try and compare the value if (CanDirectlyCompare(propertyInfo.PropertyType)) { if (!AreValuesEqual(valueA, valueB)) { Console.WriteLine("Mismatch with property '{0}.{1}' found.", objectType.FullName, propertyInfo.Name); result = false; } } // if it implements IEnumerable, then scan any items else if (typeof(IEnumerable).IsAssignableFrom(propertyInfo.PropertyType)) { // null check if (valueA == null && valueB != null || valueA != null && valueB == null) { Console.WriteLine("Mismatch with property '{0}.{1}' found.", objectType.FullName, propertyInfo.Name); result = false; } else if (valueA != null) { var collectionItems1 = ((IEnumerable)valueA).Cast<object>(); var collectionItems2 = ((IEnumerable)valueB).Cast<object>(); var collectionItemsCount1 = collectionItems1.Count(); var collectionItemsCount2 = collectionItems2.Count(); // check the counts to ensure they match if (collectionItemsCount1 != collectionItemsCount2) { Console.WriteLine("Collection counts for property '{0}.{1}' do not match.", objectType.FullName, propertyInfo.Name); result = false; } // and if they do, compare each item... this assumes both collections have the same order else { for (int i = 0; i < collectionItemsCount1; i++) { var collectionItem1 = collectionItems1.ElementAt(i); var collectionItem2 = collectionItems2.ElementAt(i); var collectionItemType = collectionItem1.GetType(); if (CanDirectlyCompare(collectionItemType)) { if (!AreValuesEqual(collectionItem1, collectionItem2)) { Console.WriteLine( "Item {0} in property collection '{1}.{2}' does not match.", i, objectType.FullName, propertyInfo.Name); result = false; } } else if (!AreObjectsEqual(collectionItem1, collectionItem2, ignoreList)) { Console.WriteLine("Item {0} in property collection '{1}.{2}' does not match.", i, objectType.FullName, propertyInfo.Name); result = false; } } } } } else if (propertyInfo.PropertyType.IsClass) { if (!AreObjectsEqual(propertyInfo.GetValue(objectA, null), propertyInfo.GetValue(objectB, null), ignoreList)) { Console.WriteLine("Mismatch with property '{0}.{1}' found.", objectType.FullName, propertyInfo.Name); result = false; } } else { Console.WriteLine("Cannot compare property '{0}.{1}'.", objectType.FullName, propertyInfo.Name); result = false; } } } else result = Equals(objectA, objectB); return result; } /// <summary> /// Determines whether value instances of the specified type can be directly compared. /// </summary> /// <param name="type">The type.</param> /// <returns> /// <c>true</c> if this value instances of the specified type can be directly compared; otherwise, <c>false</c>. /// </returns> private static bool CanDirectlyCompare(Type type) { return typeof(IComparable).IsAssignableFrom(type) || type.IsPrimitive || type.IsValueType; } /// <summary> /// Compares two values and returns if they are the same. /// </summary> /// <param name="valueA">The first value to compare.</param> /// <param name="valueB">The second value to compare.</param> /// <returns><c>true</c> if both values match, otherwise <c>false</c>.</returns> private static bool AreValuesEqual(object valueA, object valueB) { bool result; if (valueA == null && valueB != null || valueA != null && valueB == null) result = false; // one of the values is null else if (valueA is IComparable selfValueComparer && selfValueComparer.CompareTo(valueB) != 0) result = false; // the comparison using IComparable failed else if (!Equals(valueA, valueB)) result = false; // the comparison using Equals failed else result = true; // match return result; } internal static void Retry(Func<Task<bool>> func, TimeSpan delay, int maxNbRetries) { for (int i = 0; i < maxNbRetries; i++) { bool shouldRetry = func().GetAwaiter().GetResult(); if (!shouldRetry) { return; } Thread.Sleep((int)delay.TotalMilliseconds); } throw new Exception("reached the maximum number of retries"); } } }
using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Baseline; using LamarCodeGeneration; using LamarCodeGeneration.Frames; using LamarCodeGeneration.Model; using LamarCompiler; using Marten.Events.Archiving; using Marten.Events.Operations; using Marten.Events.Querying; using Marten.Events.Schema; using Marten.Internal; using Marten.Internal.CodeGeneration; using Marten.Schema; using Marten.Storage; using Marten.Storage.Metadata; using Npgsql; using Weasel.Postgresql; namespace Marten.Events.CodeGeneration { internal static class EventDocumentStorageGenerator { private const string StreamStateSelectorTypeName = "GeneratedStreamStateQueryHandler"; private const string InsertStreamOperationName = "GeneratedInsertStream"; private const string UpdateStreamVersionOperationName = "GeneratedStreamVersionOperation"; private const string EventDocumentStorageTypeName = "GeneratedEventDocumentStorage"; public static (EventDocumentStorage, string) GenerateStorage(StoreOptions options) { var assembly = new GeneratedAssembly(new GenerationRules(SchemaConstants.MartenGeneratedNamespace)); var builderType = AssembleTypes(options, assembly); var compiler = new AssemblyGenerator(); compiler.ReferenceAssembly(typeof(IMartenSession).Assembly); compiler.Compile(assembly); var writer = new StringWriter(); foreach (var generatedType in assembly.GeneratedTypes) { writer.WriteLine($" // {generatedType.TypeName}"); writer.WriteLine(generatedType.SourceCode); writer.WriteLine(); } var code = writer.ToString(); var storage = (EventDocumentStorage) Activator.CreateInstance(builderType.CompiledType, options); return (storage, code); } public static DocumentProvider<IEvent> BuildProvider(StoreOptions options) { var (storage, code) = GenerateStorage(options); return new DocumentProvider<IEvent> { DirtyTracking = storage, Lightweight = storage, IdentityMap = storage, QueryOnly = storage, SourceCode = code }; } public static DocumentProvider<IEvent> BuildProviderFromAssembly(Assembly assembly, StoreOptions options) { var storageType = assembly.GetExportedTypes().FirstOrDefault(x => x.CanBeCastTo<IEventStorage>()); if (storageType == null) { Console.WriteLine($"Unable to find a pre-built storage type for {nameof(IEventStorage)}"); return null; } var storage = (EventDocumentStorage)Activator.CreateInstance(storageType, options); return new DocumentProvider<IEvent> { DirtyTracking = storage, Lightweight = storage, IdentityMap = storage, QueryOnly = storage, SourceCode = storageType.FullNameInCode() }; } public static GeneratedType AssembleTypes(StoreOptions options, GeneratedAssembly assembly) { assembly.ReferenceAssembly(typeof(EventGraph).Assembly); var builderType = assembly.AddType(EventDocumentStorageTypeName, typeof(EventDocumentStorage)); buildSelectorMethods(options, builderType); buildAppendEventOperation(options.EventGraph, assembly); builderType.MethodFor(nameof(EventDocumentStorage.AppendEvent)) .Frames.Code($"return new Marten.Generated.AppendEventOperation(stream, e);"); buildInsertStream(builderType, assembly, options.EventGraph); buildStreamQueryHandlerType(options.EventGraph, assembly); buildQueryForStreamMethod(options.EventGraph, builderType); buildUpdateStreamVersion(builderType, assembly, options.EventGraph); return builderType; } private static void buildSelectorMethods(StoreOptions options, GeneratedType builderType) { var sync = builderType.MethodFor(nameof(EventDocumentStorage.ApplyReaderDataToEvent)); var async = builderType.MethodFor(nameof(EventDocumentStorage.ApplyReaderDataToEventAsync)); // The json data column has to go first var table = new EventsTable(options.EventGraph); var columns = table.SelectColumns(); for (var i = 3; i < columns.Count; i++) { columns[i].GenerateSelectorCodeSync(sync, options.EventGraph, i); columns[i].GenerateSelectorCodeAsync(async, options.EventGraph, i); } } private static GeneratedType buildUpdateStreamVersion(GeneratedType builderType, GeneratedAssembly assembly, EventGraph graph) { var operationType = assembly.AddType(UpdateStreamVersionOperationName, typeof(UpdateStreamVersion)); var sql = $"update {graph.DatabaseSchemaName}.mt_streams set version = ? where id = ? and version = ?"; if (graph.TenancyStyle == TenancyStyle.Conjoined) { sql += $" and {TenantIdColumn.Name} = ?"; } var configureCommand = operationType.MethodFor("ConfigureCommand"); configureCommand.DerivedVariables.Add(new Variable(typeof(StreamAction), nameof(UpdateStreamVersion.Stream))); configureCommand.Frames.Code($"var parameters = {{0}}.{nameof(CommandBuilder.AppendWithParameters)}(\"{sql}\");", Use.Type<CommandBuilder>()); configureCommand.SetParameterFromMember<StreamAction>(0, x => x.Version); if (graph.StreamIdentity == StreamIdentity.AsGuid) { configureCommand.SetParameterFromMember<StreamAction>(1, x => x.Id); } else { configureCommand.SetParameterFromMember<StreamAction>(1, x => x.Key); } configureCommand.SetParameterFromMember<StreamAction>(2, x => x.ExpectedVersionOnServer); if (graph.TenancyStyle == TenancyStyle.Conjoined) { new TenantIdColumn().As<IStreamTableColumn>().GenerateAppendCode(configureCommand, 3); } builderType.MethodFor(nameof(EventDocumentStorage.UpdateStreamVersion)) .Frames.Code($"return new Marten.Generated.{UpdateStreamVersionOperationName}({{0}});", Use.Type<StreamAction>()); return operationType; } private static void buildQueryForStreamMethod(EventGraph graph, GeneratedType builderType) { var arguments = new List<string> { graph.StreamIdentity == StreamIdentity.AsGuid ? $"stream.{nameof(StreamAction.Id)}" : $"stream.{nameof(StreamAction.Key)}" }; if (graph.TenancyStyle == TenancyStyle.Conjoined) { arguments.Add($"stream.{nameof(StreamAction.TenantId)}"); } builderType.MethodFor(nameof(EventDocumentStorage.QueryForStream)) .Frames.Code($"return new Marten.Generated.{StreamStateSelectorTypeName}({arguments.Join(", ")});"); } private static GeneratedType buildStreamQueryHandlerType(EventGraph graph, GeneratedAssembly assembly) { var streamQueryHandlerType = assembly.AddType(StreamStateSelectorTypeName, typeof(StreamStateQueryHandler)); streamQueryHandlerType.AllInjectedFields.Add(graph.StreamIdentity == StreamIdentity.AsGuid ? new InjectedField(typeof(Guid), "streamId") : new InjectedField(typeof(string), "streamId")); buildConfigureCommandMethodForStreamState(graph, streamQueryHandlerType); var sync = streamQueryHandlerType.MethodFor("Resolve"); var async = streamQueryHandlerType.MethodFor("ResolveAsync"); sync.Frames.Add(new ConstructorFrame<StreamState>(() => new StreamState())); async.Frames.Add(new ConstructorFrame<StreamState>(() => new StreamState())); if (graph.StreamIdentity == StreamIdentity.AsGuid) { sync.AssignMemberFromReader<StreamState>(streamQueryHandlerType, 0, x => x.Id); async.AssignMemberFromReaderAsync<StreamState>(streamQueryHandlerType, 0, x => x.Id); } else { sync.AssignMemberFromReader<StreamState>(streamQueryHandlerType, 0, x => x.Key); async.AssignMemberFromReaderAsync<StreamState>(streamQueryHandlerType, 0, x => x.Key); } sync.AssignMemberFromReader<StreamState>(streamQueryHandlerType, 1, x => x.Version); async.AssignMemberFromReaderAsync<StreamState>(streamQueryHandlerType, 1, x => x.Version); sync.Frames.Call<StreamStateQueryHandler>(x => x.SetAggregateType(null, null, null), @call => { @call.IsLocal = true; }); #pragma warning disable 4014 async.Frames.Call<StreamStateQueryHandler>(x => x.SetAggregateTypeAsync(null, null, null, CancellationToken.None), @call => #pragma warning restore 4014 { @call.IsLocal = true; }); sync.AssignMemberFromReader<StreamState>(streamQueryHandlerType, 3, x => x.LastTimestamp); async.AssignMemberFromReaderAsync<StreamState>(streamQueryHandlerType, 3, x => x.LastTimestamp); sync.AssignMemberFromReader<StreamState>(streamQueryHandlerType, 4, x => x.Created); async.AssignMemberFromReaderAsync<StreamState>(streamQueryHandlerType, 4, x => x.Created); sync.AssignMemberFromReader<StreamState>(streamQueryHandlerType, 5, x => x.IsArchived); async.AssignMemberFromReaderAsync<StreamState>(streamQueryHandlerType, 5, x => x.IsArchived); sync.Frames.Return(typeof(StreamState)); async.Frames.Return(typeof(StreamState)); return streamQueryHandlerType; } private static void buildConfigureCommandMethodForStreamState(EventGraph graph, GeneratedType streamQueryHandlerType) { var sql = $"select id, version, type, timestamp, created as timestamp, is_archived from {graph.DatabaseSchemaName}.mt_streams where id = ?"; if (graph.TenancyStyle == TenancyStyle.Conjoined) { streamQueryHandlerType.AllInjectedFields.Add(new InjectedField(typeof(string), "tenantId")); sql += $" and {TenantIdColumn.Name} = ?"; } var configureCommand = streamQueryHandlerType.MethodFor("ConfigureCommand"); configureCommand.Frames.Call<CommandBuilder>(x => x.AppendWithParameters(""), @call => { @call.Arguments[0] = Constant.ForString(sql); @call.ReturnAction = ReturnAction.Initialize; }); var idDbType = graph.StreamIdentity == StreamIdentity.AsGuid ? DbType.Guid : DbType.String; configureCommand.Frames.Code("{0}[0].Value = _streamId;", Use.Type<NpgsqlParameter[]>()); configureCommand.Frames.Code("{0}[0].DbType = {1};", Use.Type<NpgsqlParameter[]>(), idDbType); if (graph.TenancyStyle == TenancyStyle.Conjoined) { configureCommand.Frames.Code("{0}[1].Value = _tenantId;", Use.Type<NpgsqlParameter[]>()); configureCommand.Frames.Code("{0}[1].DbType = {1};", Use.Type<NpgsqlParameter[]>(), DbType.String); } } private static GeneratedType buildAppendEventOperation(EventGraph graph, GeneratedAssembly assembly) { var operationType = assembly.AddType("AppendEventOperation", typeof(AppendEventOperationBase)); var configure = operationType.MethodFor(nameof(AppendEventOperationBase.ConfigureCommand)); configure.DerivedVariables.Add(new Variable(typeof(IEvent), nameof(AppendEventOperationBase.Event))); configure.DerivedVariables.Add(new Variable(typeof(StreamAction), nameof(AppendEventOperationBase.Stream))); var columns = new EventsTable(graph).SelectColumns() // Hokey, use an explicit model for writeable vs readable columns some day .Where(x => !(x is IsArchivedColumn)).ToList(); var sql = $"insert into {graph.DatabaseSchemaName}.mt_events ({columns.Select(x => x.Name).Join(", ")}) values ({columns.Select(_ => "?").Join(", ")})"; configure.Frames.Code($"var parameters = {{0}}.{nameof(CommandBuilder.AppendWithParameters)}(\"{sql}\");", Use.Type<CommandBuilder>()); for (var i = 0; i < columns.Count; i++) { columns[i].GenerateAppendCode(configure, graph, i); } return operationType; } private static GeneratedType buildInsertStream(GeneratedType builderType, GeneratedAssembly generatedAssembly, EventGraph graph) { var operationType = generatedAssembly.AddType(InsertStreamOperationName, typeof(InsertStreamBase)); var columns = new StreamsTable(graph) .Columns .OfType<IStreamTableColumn>() .Where(x => x.Writes) .ToArray(); var sql = $"insert into {graph.DatabaseSchemaName}.mt_streams ({columns.Select(x => x.Name).Join(", ")}) values ({columns.Select(_ => "?").Join(", ")})"; var configureCommand = operationType.MethodFor("ConfigureCommand"); configureCommand.DerivedVariables.Add(new Variable(typeof(StreamAction), nameof(InsertStreamBase.Stream))); configureCommand.Frames.Code($"var parameters = {{0}}.{nameof(CommandBuilder.AppendWithParameters)}(\"{sql}\");", Use.Type<CommandBuilder>()); for (var i = 0; i < columns.Length; i++) { columns[i].GenerateAppendCode(configureCommand, i); } builderType.MethodFor(nameof(EventDocumentStorage.InsertStream)) .Frames.Code($"return new Marten.Generated.{InsertStreamOperationName}(stream);"); return operationType; } } }
// // Orbit.cs // // Copyright (c) 2005-2012 Michael F. Henry // Version 06/2012 // using System; namespace Zeptomoby.OrbitTools { /// <summary> /// This class accepts a single satellite's NORAD two-line element /// set and provides information regarding the satellite's orbit /// such as period, axis length, ECI coordinates, velocity, etc. /// </summary> public class Orbit { // Caching variables private TimeSpan m_Period = new TimeSpan(0, 0, 0, -1); // TLE caching variables private double m_Inclination; private double m_Eccentricity; private double m_RAAN; private double m_ArgPerigee; private double m_BStar; private double m_Drag; private double m_MeanAnomaly; private double m_TleMeanMotion; // Caching variables recovered from the input TLE elements private double m_aeAxisSemiMajorRec; // semimajor axis, in AE units private double m_aeAxisSemiMinorRec; // semiminor axis, in AE units private double m_rmMeanMotionRec; // radians per minute private double m_kmPerigeeRec; // perigee, in km private double m_kmApogeeRec; // apogee, in km #region Properties private Tle Tle { get; set; } private NoradBase NoradModel { get; set; } public Julian Epoch { get; private set; } public DateTime EpochTime { get { return Epoch.ToTime(); }} // "Recovered" from the input elements public double SemiMajor { get { return m_aeAxisSemiMajorRec; }} public double SemiMinor { get { return m_aeAxisSemiMinorRec; }} public double MeanMotion { get { return m_rmMeanMotionRec; }} public double Major { get { return 2.0 * SemiMajor; }} public double Minor { get { return 2.0 * SemiMinor; }} public double Perigee { get { return m_kmPerigeeRec; }} public double Apogee { get { return m_kmApogeeRec; }} public double Inclination { get { return m_Inclination; }} public double Eccentricity { get { return m_Eccentricity; }} public double RAAN { get { return m_RAAN; }} public double ArgPerigee { get { return m_ArgPerigee; }} public double BStar { get { return m_BStar; }} public double Drag { get { return m_Drag; }} public double MeanAnomaly { get { return m_MeanAnomaly; }} private double TleMeanMotion { get { return m_TleMeanMotion; }} public string SatNoradId { get { return Tle.NoradNumber; }} public string SatName { get { return Tle.Name; }} public string SatNameLong { get { return SatName + " #" + SatNoradId; }} public TimeSpan Period { get { if (m_Period.TotalSeconds < 0.0) { // Calculate the period using the recovered mean motion. if (MeanMotion == 0) { m_Period = new TimeSpan(0, 0, 0); } else { double secs = (Globals.TwoPi / MeanMotion) * 60.0; int msecs = (int)((secs - (int)secs) * 1000); m_Period = new TimeSpan(0, 0, 0, (int)secs, msecs); } } return m_Period; } } #endregion #region Construction /// <summary> /// Standard constructor. /// </summary> /// <param name="tle">Two-line element orbital parameters.</param> public Orbit(Tle tle) { Tle = tle; Epoch = Tle.EpochJulian; m_Inclination = GetRad(Tle.Field.Inclination); m_Eccentricity = Tle.GetField(Tle.Field.Eccentricity); m_RAAN = GetRad(Tle.Field.Raan); m_ArgPerigee = GetRad(Tle.Field.ArgPerigee); m_BStar = Tle.GetField(Tle.Field.BStarDrag); m_Drag = Tle.GetField(Tle.Field.MeanMotionDt); m_MeanAnomaly = GetRad(Tle.Field.MeanAnomaly); m_TleMeanMotion = Tle.GetField(Tle.Field.MeanMotion); // Recover the original mean motion and semimajor axis from the // input elements. double mm = TleMeanMotion; double rpmin = mm * Globals.TwoPi / Globals.MinPerDay; // rads per minute double a1 = Math.Pow(Globals.Xke / rpmin, 2.0 / 3.0); double e = Eccentricity; double i = Inclination; double temp = (1.5 * Globals.Ck2 * (3.0 * Globals.Sqr(Math.Cos(i)) - 1.0) / Math.Pow(1.0 - e * e, 1.5)); double delta1 = temp / (a1 * a1); double a0 = a1 * (1.0 - delta1 * ((1.0 / 3.0) + delta1 * (1.0 + 134.0 / 81.0 * delta1))); double delta0 = temp / (a0 * a0); m_rmMeanMotionRec = rpmin / (1.0 + delta0); m_aeAxisSemiMajorRec = a0 / (1.0 - delta0); m_aeAxisSemiMinorRec = m_aeAxisSemiMajorRec * Math.Sqrt(1.0 - (e * e)); m_kmPerigeeRec = Globals.Xkmper * (m_aeAxisSemiMajorRec * (1.0 - e) - Globals.Ae); m_kmApogeeRec = Globals.Xkmper * (m_aeAxisSemiMajorRec * (1.0 + e) - Globals.Ae); if (Period.TotalMinutes >= 225.0) { // SDP4 - period >= 225 minutes. NoradModel = new NoradSDP4(this); } else { // SGP4 - period < 225 minutes NoradModel = new NoradSGP4(this); } } #endregion #region Get Position /// <summary> /// Calculate satellite ECI position/velocity for a given time. /// </summary> /// <param name="tsince">Target time, in minutes past the TLE epoch.</param> /// <returns>Kilometer-based position/velocity ECI coordinates.</returns> public EciTime GetPosition(double minutesPastEpoch) { EciTime eci = NoradModel.GetPosition(minutesPastEpoch); // Convert ECI vector units from AU to kilometers double radiusAe = Globals.Xkmper / Globals.Ae; eci.ScalePosVector(radiusAe); // km eci.ScaleVelVector(radiusAe * (Globals.MinPerDay / 86400)); // km/sec return eci; } /// <summary> /// Calculate ECI position/velocity for a given time. /// </summary> /// <param name="utc">Target time (UTC).</param> /// <returns>Kilometer-based position/velocity ECI coordinates.</returns> public EciTime GetPosition(DateTime utc) { return GetPosition(TPlusEpoch(utc).TotalMinutes); } #endregion // /////////////////////////////////////////////////////////////////////////// // Returns elapsed time from epoch to given time. // Note: "Predicted" TLEs can have epochs in the future. public TimeSpan TPlusEpoch(DateTime utc) { return (utc - EpochTime); } // /////////////////////////////////////////////////////////////////////////// // Returns elapsed time from epoch to current time. // Note: "Predicted" TLEs can have epochs in the future. public TimeSpan TPlusEpoch() { return TPlusEpoch(DateTime.UtcNow); } #region Utility // /////////////////////////////////////////////////////////////////// protected double GetRad(Tle.Field fld) { return Tle.GetField(fld, Tle.Unit.Radians); } // /////////////////////////////////////////////////////////////////// protected double GetDeg(Tle.Field fld) { return Tle.GetField(fld, Tle.Unit.Degrees); } #endregion } }
// // ObjectQueryContextTests.cs // // Author: // Scott Thomas <lunchtimemama@gmail.com> // // Copyright (c) 2010 Scott Thomas // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using NUnit.Framework; using Mono.Upnp.Dcp.MediaServer1.ContentDirectory1; using Mono.Upnp.Xml; namespace Mono.Upnp.Dcp.MediaServer1.Tests { [TestFixture] public class ObjectQueryContextTests { const string bar = "www.bar.org"; class ElementTestClass { [XmlElement] public string Foo { get; set; } } [Test] public void Element () { var context = new ObjectQueryContext (typeof (ElementTestClass)); Assert.IsTrue (context.PropertyExists ("Foo", new ElementTestClass ())); var foo = new ElementTestClass { Foo = "bar" }; Assert.IsTrue (context.PropertyExists ("Foo", foo)); Assert.IsFalse (context.PropertyExists ("Bar", foo)); var equality = false; context.VisitProperty ("Foo", foo, value => equality = value.Equals ("bar")); Assert.IsTrue (equality); equality = false; context.VisitProperty ("Foo", new ElementTestClass (), value => equality = value == null); Assert.IsTrue (equality); } class OmitIfNullElementTestClass { [XmlElement (OmitIfNull = true)] public string Foo { get; set; } } [Test] public void OmitIfNullElement () { var context = new ObjectQueryContext (typeof (OmitIfNullElementTestClass)); Assert.IsFalse (context.PropertyExists ("Foo", new OmitIfNullElementTestClass ())); Assert.IsTrue (context.PropertyExists ("Foo", new OmitIfNullElementTestClass { Foo = "bar" })); } class NamedElementTestClass { [XmlElement ("foo")] public string Foo { get; set; } } [Test] public void NamedElement () { var context = new ObjectQueryContext (typeof (NamedElementTestClass)); Assert.IsTrue (context.PropertyExists ("foo", new NamedElementTestClass ())); } class PrefixedElementTestClass { [XmlElement ("foo", bar, "bar")] public string Foo { get; set; } } [Test] public void PrefixedElement () { var context = new ObjectQueryContext (typeof (PrefixedElementTestClass)); Assert.IsTrue (context.PropertyExists ("bar:foo", new PrefixedElementTestClass ())); } class AttributeTestClass { [XmlAttribute] public string Foo { get; set; } } [Test] public void Attribute () { var context = new ObjectQueryContext (typeof (AttributeTestClass)); Assert.IsTrue (context.PropertyExists ("@Foo", new AttributeTestClass ())); var foo = new AttributeTestClass { Foo = "bar" }; Assert.IsTrue (context.PropertyExists ("@Foo", foo)); Assert.IsFalse (context.PropertyExists ("@Bar", foo)); var equality = false; context.VisitProperty ("@Foo", foo, value => equality = value.Equals ("bar")); Assert.IsTrue (equality); equality = false; context.VisitProperty ("@Foo", new AttributeTestClass (), value => equality = value == null); Assert.IsTrue (equality); } class OmitIfNullAttributeTestClass { [XmlAttribute (OmitIfNull = true)] public string Foo { get; set; } } [Test] public void OmitIfNullAttribute () { var context = new ObjectQueryContext (typeof (OmitIfNullAttributeTestClass)); Assert.IsFalse (context.PropertyExists ("@Foo", new OmitIfNullAttributeTestClass ())); Assert.IsTrue (context.PropertyExists ("@Foo", new OmitIfNullAttributeTestClass { Foo = "bar" })); } class NamedAttributeTestClass { [XmlAttribute ("foo")] public string Foo { get; set; } } [Test] public void NamedAttribute () { var context = new ObjectQueryContext (typeof (NamedAttributeTestClass)); Assert.IsTrue (context.PropertyExists ("@foo", new NamedAttributeTestClass ())); } class PrefixedAttributeTestClass { [XmlAttribute ("foo", bar, "bar")] public string Foo { get; set; } } [Test] public void PrefixedAttribute () { var context = new ObjectQueryContext (typeof (PrefixedAttributeTestClass)); Assert.IsTrue (context.PropertyExists ("@bar:foo", new PrefixedAttributeTestClass ())); } class NestedTestClass { [XmlElement] public AttributeTestClass Attribute { get; set; } [XmlElement] public OmitIfNullAttributeTestClass OmitIfNullAttribute { get; set; } [XmlElement] public NamedAttributeTestClass NamedAttribute { get; set; } [XmlElement] public PrefixedAttributeTestClass PrefixedAttribute { get; set; } [XmlElement ("prefixedNestedAttribute", bar, "bar")] public AttributeTestClass PrefixedNestedAttribute { get; set; } [XmlElement ("prefixedNestedPrefixedAttribute", bar, "bar")] public PrefixedAttributeTestClass PrefixedNestedPrefixedAttribute { get; set; } } [Test] public void NestedElements () { var context = new ObjectQueryContext (typeof (NestedTestClass)); var test = new NestedTestClass { Attribute = new AttributeTestClass (), OmitIfNullAttribute = new OmitIfNullAttributeTestClass (), NamedAttribute = new NamedAttributeTestClass (), PrefixedAttribute = new PrefixedAttributeTestClass (), PrefixedNestedAttribute = new AttributeTestClass (), PrefixedNestedPrefixedAttribute = new PrefixedAttributeTestClass () }; Assert.IsTrue (context.PropertyExists ("Attribute", test)); Assert.IsTrue (context.PropertyExists ("Attribute@Foo", test)); Assert.IsTrue (context.PropertyExists ("OmitIfNullAttribute", test)); Assert.IsFalse (context.PropertyExists ("OmitIfNullAttribute@Foo", test)); Assert.IsTrue (context.PropertyExists ("NamedAttribute", test)); Assert.IsTrue (context.PropertyExists ("NamedAttribute@foo", test)); Assert.IsTrue (context.PropertyExists ("PrefixedAttribute", test)); Assert.IsTrue (context.PropertyExists ("PrefixedAttribute@bar:foo", test)); Assert.IsTrue (context.PropertyExists ("bar:prefixedNestedAttribute", test)); Assert.IsTrue (context.PropertyExists ("bar:prefixedNestedAttribute@Foo", test)); Assert.IsTrue (context.PropertyExists ("bar:prefixedNestedPrefixedAttribute", test)); Assert.IsTrue (context.PropertyExists ("bar:prefixedNestedPrefixedAttribute@bar:foo", test)); test.OmitIfNullAttribute.Foo = "bar"; Assert.IsTrue (context.PropertyExists ("OmitIfNullAttribute@Foo", test)); var equality = false; context.VisitProperty ("OmitIfNullAttribute@Foo", test, value => equality = value.Equals ("bar")); Assert.IsTrue (equality); } class ArrayItemTestClass { [XmlArrayItem] public IEnumerable<string> Foo { get; set; } } [Test] public void ArrayItem () { var context = new ObjectQueryContext (typeof (ArrayItemTestClass)); Assert.IsFalse (context.PropertyExists ("Foo", new ArrayItemTestClass ())); Assert.IsFalse (context.PropertyExists ("Foo", new ArrayItemTestClass { Foo = new string[0] })); var foos = new[] { "foo", "bar", "bat", "baz" }; var test = new ArrayItemTestClass { Foo = foos }; Assert.IsTrue (context.PropertyExists ("Foo", test)); var i = 0; var inequality = false; context.VisitProperty ("Foo", test, value => inequality |= !value.Equals (foos[i++])); Assert.IsFalse (inequality); } class NamedArrayItemTestClass { [XmlArrayItem ("foo")] public IEnumerable<string> Foo { get; set; } } [Test] public void NamedArrayItem () { var context = new ObjectQueryContext (typeof (NamedArrayItemTestClass)); Assert.IsTrue (context.PropertyExists ("foo", new NamedArrayItemTestClass { Foo = new[] { "bar" } })); } class PrefixedArrayItemTestClass { [XmlArrayItem ("foo", bar, "bar")] public IEnumerable<string> Foo { get; set; } } [Test] public void PrefixedArrayItem () { var context = new ObjectQueryContext (typeof (PrefixedArrayItemTestClass)); Assert.IsTrue (context.PropertyExists ("bar:foo", new PrefixedArrayItemTestClass { Foo = new[] { "bar" } })); } class NestedArrayItemTestClass { [XmlElement] public IEnumerable<AttributeTestClass> Foo { get; set; } } [Test] public void NestedArrayTestClass () { var context = new ObjectQueryContext (typeof (NestedArrayItemTestClass)); var attributes = new[] { "foo", "bar", "bat", "baz" }; var foos = new[] { new AttributeTestClass { Foo = "foo" }, new AttributeTestClass { Foo = "bar" }, new AttributeTestClass { Foo = "bat" }, new AttributeTestClass { Foo = "baz" } }; var test = new NestedArrayItemTestClass { Foo = foos }; var i = 0; var inequality = false; context.VisitProperty ("Foo@Foo", test, value => inequality |= !value.Equals (attributes[i++])); Assert.IsFalse (inequality); } class ElementTestSubclass : ElementTestClass { [XmlElement] public string Bar { get; set; } } [Test] public void SuperclassLookup () { var superclass_context = new ObjectQueryContext (typeof (ElementTestClass)); var subclass_context = new ObjectQueryContext (typeof (ElementTestSubclass), superclass_context); var test = new ElementTestSubclass (); Assert.IsTrue (superclass_context.PropertyExists ("Foo", test)); Assert.IsFalse (superclass_context.PropertyExists ("Bar", test)); Assert.IsTrue (subclass_context.PropertyExists ("Foo", test)); Assert.IsTrue (subclass_context.PropertyExists ("Bar", test)); Assert.IsFalse (new ObjectQueryContext (typeof (ElementTestSubclass)).PropertyExists ("Foo", test)); } class NullableElementTestClass { [XmlElement (OmitIfNull = true)] public int? Foo { get; set; } } [Test] public void NullableElement () { var context = new ObjectQueryContext (typeof (NullableElementTestClass)); Assert.IsTrue (context.PropertyExists ("Foo", new NullableElementTestClass { Foo = 42 })); Assert.IsFalse (context.PropertyExists ("Foo", new NullableElementTestClass ())); } class NullableAttributeTestClass { [XmlAttribute (OmitIfNull = true)] public int? Foo { get; set; } } [Test] public void NullableAttribute () { var context = new ObjectQueryContext (typeof (NullableAttributeTestClass)); Assert.IsTrue (context.PropertyExists ("@Foo", new NullableAttributeTestClass { Foo = 42 })); Assert.IsFalse (context.PropertyExists ("@Foo", new NullableAttributeTestClass ())); } } }
using UnityEngine; using System.Collections.Generic; using Pathfinding.Util; namespace Pathfinding { [AddComponentMenu ("Pathfinding/Modifiers/Simple Smooth")] [System.Serializable] /** Modifier which smooths the path. This modifier can smooth a path by either moving the points closer together (Simple) or using Bezier curves (Bezier).\n * \ingroup modifiers * Attach this component to the same GameObject as a Seeker component. * \n * This component will hook in to the Seeker's path post-processing system and will post process any paths it searches for. * Take a look at the Modifier Priorities settings on the Seeker component to determine where in the process this modifier should process the path. * \n * \n * Several smoothing types are available, here follows a list of them and a short description of what they do, and how they work. * But the best way is really to experiment with them yourself.\n * * - <b>Simple</b> Smooths the path by drawing all points close to each other. This results in paths that might cut corners if you are not careful. * It will also subdivide the path to create more more points to smooth as otherwise it would still be quite rough. * \shadowimage{smooth_simple.png} * - <b>Bezier</b> Smooths the path using Bezier curves. This results a smooth path which will always pass through all points in the path, but make sure it doesn't turn too quickly. * \shadowimage{smooth_bezier.png} * - <b>OffsetSimple</b> An alternative to Simple smooth which will offset the path outwards in each step to minimize the corner-cutting. * But be careful, if too high values are used, it will turn into loops and look really ugly. * - <b>Curved Non Uniform</b> \shadowimage{smooth_curved_nonuniform.png} * * \note Modifies vectorPath array * \todo Make the smooth modifier take the world geometry into account when smoothing * */ public class SimpleSmoothModifier : MonoModifier { #if UNITY_EDITOR [UnityEditor.MenuItem ("CONTEXT/Seeker/Add Simple Smooth Modifier")] public static void AddComp (UnityEditor.MenuCommand command) { (command.context as Component).gameObject.AddComponent (typeof(SimpleSmoothModifier)); } #endif public override ModifierData input { get { return ModifierData.All; } } public override ModifierData output { get { ModifierData result = ModifierData.VectorPath; if (iterations == 0 && smoothType == SimpleSmoothModifier.SmoothType.Simple && !uniformLength) { result |= ModifierData.StrictVectorPath; } return result; } } /** Type of smoothing to use */ public SmoothType smoothType = SmoothType.Simple; /** Number of times to subdivide when not using a uniform length */ public int subdivisions = 2; /** Number of times to apply smoothing */ public int iterations = 2; /** The strength of the smoothing. A value from 0 to 1 is recommended, but values larger than 1 works too.*/ public float strength = 0.5F; /** Toggle to divide all lines in equal length segments. * \see #maxSegmentLength */ public bool uniformLength = true; /** The length of the segments in the smoothed path when using #uniformLength. * A high value yields rough paths and low value yields very smooth paths, but is slower */ public float maxSegmentLength = 2F; /** Length factor of the bezier curves' tangents' */ public float bezierTangentLength = 0.4F; /** Offset to apply in each smoothing iteration when using Offset Simple. \see #smoothType */ public float offset = 0.2F; /** Roundness factor used for CurvedNonuniform */ public float factor = 0.1F; public enum SmoothType { Simple, Bezier, OffsetSimple, CurvedNonuniform } public override void Apply (Path p, ModifierData source) { //This should never trigger unless some other modifier has messed stuff up if (p.vectorPath == null) { Debug.LogWarning ("Can't process NULL path (has another modifier logged an error?)"); return; } List<Vector3> path = null; switch (smoothType) { case SmoothType.Simple: path = SmoothSimple (p.vectorPath); break; case SmoothType.Bezier: path = SmoothBezier (p.vectorPath); break; case SmoothType.OffsetSimple: path = SmoothOffsetSimple (p.vectorPath); break; case SmoothType.CurvedNonuniform: path = CurvedNonuniform (p.vectorPath); break; } if (path != p.vectorPath) { ListPool<Vector3>.Release (p.vectorPath); p.vectorPath = path; } //.vectorPath.Clear (); //p.vectorPath.AddRange (path); } public List<Vector3> CurvedNonuniform (List<Vector3> path) { if (maxSegmentLength <= 0) { Debug.LogWarning ("Max Segment Length is <= 0 which would cause DivByZero-exception or other nasty errors (avoid this)"); return path; } int pointCounter = 0; for (int i=0;i<path.Count-1;i++) { //pointCounter += Mathf.FloorToInt ((path[i]-path[i+1]).magnitude / maxSegmentLength)+1; float dist = (path[i]-path[i+1]).magnitude; //In order to avoid floating point errors as much as possible, and in lack of a better solution //loop through it EXACTLY as the other code further down will for (float t=0;t<=dist;t+=maxSegmentLength) { pointCounter++; } } List<Vector3> subdivided = ListPool<Vector3>.Claim (pointCounter); //Set first velocity Vector3 preEndVel = (path[1]-path[0]).normalized; for (int i=0;i<path.Count-1;i++) { //subdivided[counter] = path[i]; //counter++; float dist = (path[i]-path[i+1]).magnitude; Vector3 startVel1 = preEndVel; Vector3 endVel1 = i < path.Count-2 ? ((path[i+2]-path[i+1]).normalized - (path[i]-path[i+1]).normalized).normalized : (path[i+1]-path[i]).normalized; Vector3 startVel = startVel1 * dist * factor; Vector3 endVel = endVel1 * dist * factor; Vector3 start = path[i]; Vector3 end = path[i+1]; //Vector3 p1 = start + startVel; //Vector3 p2 = end - endVel; float onedivdist = 1F / dist; for (float t=0;t<=dist;t+=maxSegmentLength) { float t2 = t * onedivdist; subdivided.Add (GetPointOnCubic(start,end,startVel,endVel,t2)); //counter++; } preEndVel = endVel1; } subdivided[subdivided.Count-1] = path[path.Count-1]; return subdivided; } public static Vector3 GetPointOnCubic (Vector3 a, Vector3 b, Vector3 tan1, Vector3 tan2, float t) { float t2 = t*t, t3 = t2*t; //float s = (float)t / (float)steps; // scale s to go from 0 to 1 float h1 = 2*t3 - 3*t2 + 1; // calculate basis function 1 float h2 = -2*t3 + 3*t2; // calculate basis function 2 float h3 = t3 - 2*t2 + t; // calculate basis function 3 float h4 = t3 - t2; // calculate basis function 4 return h1*a + // multiply and sum all funtions h2*b + // together to build the interpolated h3*tan1 + // point along the curve. h4*tan2; //return //(b*(3*t*t-2*t*t*t)+c*(t-2*t*t+t*t*t)+d*(-t*t+t*t*t)+a*(1-3*t*t+2*t*t*t)); //float mt = 1-t; //return start*mt*mt*mt + (start+startVel)*3*t*mt*mt + 3*mt*t*t*(end-endVel) + t*t*t*end; //return start*t*t*t + (start+startVel)*t*t + (end-endVel)*t + end; //return start*t*t*t + start*t*t + startVel*t*t + end*t + endVel*t + end; } public List<Vector3> SmoothOffsetSimple (List<Vector3> path) { if (path.Count <= 2 || iterations <= 0) { return path; } if (iterations > 12) { Debug.LogWarning ("A very high iteration count was passed, won't let this one through"); return path; } int maxLength = (path.Count-2)*(int)Mathf.Pow(2,iterations)+2; List<Vector3> subdivided = ListPool<Vector3>.Claim (maxLength); //new Vector3[(path.Length-2)*(int)Mathf.Pow(2,iterations)+2]; List<Vector3> subdivided2 = ListPool<Vector3>.Claim (maxLength); //new Vector3[(path.Length-2)*(int)Mathf.Pow(2,iterations)+2]; for (int i=0;i<maxLength;i++) { subdivided.Add (Vector3.zero); subdivided2.Add (Vector3.zero); } for (int i=0;i<path.Count;i++) { subdivided[i] = path[i]; } for (int iteration=0;iteration < iterations; iteration++) { int currentPathLength = (path.Count-2)*(int)Mathf.Pow(2,iteration)+2; //Switch the arrays List<Vector3> tmp = subdivided; subdivided = subdivided2; subdivided2 = tmp; const float nextMultiplier = 1F; for (int i=0;i<currentPathLength-1;i++) { Vector3 current = subdivided2[i]; Vector3 next = subdivided2[i+1]; Vector3 normal = Vector3.Cross (next-current,Vector3.up); normal = normal.normalized; //This didn't work very well, made the path jaggy /*Vector3 dir = next-current; dir *= strength*0.5F; current += dir; next -= dir;*/ bool firstRight = false; bool secondRight = false; bool setFirst = false; bool setSecond = false; if (i != 0 && !Polygon.IsColinear (current,next, subdivided2[i-1])) { setFirst = true; firstRight = Polygon.Left (current,next, subdivided2[i-1]); } if (i < currentPathLength-1 && !Polygon.IsColinear (current,next, subdivided2[i+2])) { setSecond = true; secondRight = Polygon.Left (current,next,subdivided2[i+2]); } if (setFirst) { subdivided[i*2] = current + (firstRight ? normal*offset*nextMultiplier : -normal*offset*nextMultiplier); } else { subdivided[i*2] = current; } //Didn't work very well /*if (setFirst && setSecond) { if (firstRight != secondRight) { nextMultiplier = 0.5F; } else { nextMultiplier = 1F; } }*/ if (setSecond) { subdivided[i*2+1] = next + (secondRight ? normal*offset*nextMultiplier : -normal*offset*nextMultiplier); } else { subdivided[i*2+1] = next; } } subdivided[(path.Count-2)*(int)Mathf.Pow(2,iteration+1)+2-1] = subdivided2[currentPathLength-1]; } ListPool<Vector3>.Release (subdivided2); return subdivided; } public List<Vector3> SmoothSimple (List<Vector3> path) { if (path.Count < 2) { return path; } if (uniformLength) { int numSegments = 0; maxSegmentLength = maxSegmentLength < 0.005F ? 0.005F : maxSegmentLength; for (int i=0;i<path.Count-1;i++) { float length = Vector3.Distance (path[i],path[i+1]); numSegments += Mathf.FloorToInt (length / maxSegmentLength); } List<Vector3> subdivided = ListPool<Vector3>.Claim (numSegments+1); int c = 0; float carry = 0; for (int i=0;i<path.Count-1;i++) { float length = Vector3.Distance (path[i],path[i+1]); int numSegmentsForSegment = Mathf.FloorToInt ((length + carry) / maxSegmentLength); float carryOffset = carry/length; //float t = 1F / numSegmentsForSegment; Vector3 dir = path[i+1] - path[i]; for (int q=0;q<numSegmentsForSegment;q++) { //Debug.Log (q+" "+c+" "+numSegments+" "+length+" "+numSegmentsForSegment); subdivided.Add (dir*(System.Math.Max (0, (float)q/numSegmentsForSegment - carryOffset)) + path[i]); c++; } carry = (length + carry) % maxSegmentLength; } subdivided.Add (path[path.Count-1]); if (strength != 0) { for (int it = 0; it < iterations; it++) { Vector3 prev = subdivided[0]; for (int i=1;i<subdivided.Count-1;i++) { Vector3 tmp = subdivided[i]; subdivided[i] = Vector3.Lerp (tmp, (prev+subdivided[i+1])/2F,strength); prev = tmp; } } } return subdivided; } else { List<Vector3> subdivided = ListPool<Vector3>.Claim (); //Polygon.Subdivide (path,subdivisions); if (subdivisions < 0) subdivisions = 0; int steps = 1 << subdivisions; for (int i=0;i<path.Count-1;i++) for (int j=0;j<steps;j++) subdivided.Add (Vector3.Lerp (path[i],path[i+1],(float)j / steps)); for (int it = 0; it < iterations; it++) { Vector3 prev = subdivided[0]; for (int i=1;i<subdivided.Count-1;i++) { Vector3 tmp = subdivided[i]; subdivided[i] = Vector3.Lerp (tmp, (prev+subdivided[i+1])/2F,strength); prev = tmp; } } return subdivided; } } public List<Vector3> SmoothBezier (List<Vector3> path) { if (subdivisions < 0) subdivisions = 0; int subMult = 1 << subdivisions; List<Vector3> subdivided = ListPool<Vector3>.Claim (); for (int i=0;i<path.Count-1;i++) { Vector3 tangent1; Vector3 tangent2; if (i == 0) { tangent1 = path[i+1]-path[i]; } else { tangent1 = path[i+1]-path[i-1]; } if (i == path.Count-2) { tangent2 = path[i]-path[i+1]; } else { tangent2 = path[i]-path[i+2]; } tangent1 *= bezierTangentLength; tangent2 *= bezierTangentLength; Vector3 v1 = path[i]; Vector3 v2 = v1+tangent1; Vector3 v4 = path[i+1]; Vector3 v3 = v4+tangent2; for (int j=0;j<subMult;j++) { subdivided.Add (AstarMath.CubicBezier (v1,v2,v3,v4, (float)j/subMult)); } } //Assign the last point subdivided.Add (path[path.Count-1]); return subdivided; } } }
using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Text; using System.Threading; using OpenHome.Net.Core; using OpenHome.Net.ControlPoint; namespace OpenHome.Net.ControlPoint.Proxies { public interface ICpProxyAvOpenhomeOrgExakt1 : ICpProxy, IDisposable { void SyncDeviceList(out String aList); void BeginDeviceList(CpProxy.CallbackAsyncComplete aCallback); void EndDeviceList(IntPtr aAsyncHandle, out String aList); void SyncDeviceSettings(String aDeviceId, out String aSettings); void BeginDeviceSettings(String aDeviceId, CpProxy.CallbackAsyncComplete aCallback); void EndDeviceSettings(IntPtr aAsyncHandle, out String aSettings); void SyncConnectionStatus(out String aConnectionStatus); void BeginConnectionStatus(CpProxy.CallbackAsyncComplete aCallback); void EndConnectionStatus(IntPtr aAsyncHandle, out String aConnectionStatus); void SyncSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist); void BeginSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist, CpProxy.CallbackAsyncComplete aCallback); void EndSet(IntPtr aAsyncHandle); void SyncReprogram(String aDeviceId, String aFileUri); void BeginReprogram(String aDeviceId, String aFileUri, CpProxy.CallbackAsyncComplete aCallback); void EndReprogram(IntPtr aAsyncHandle); void SyncReprogramFallback(String aDeviceId, String aFileUri); void BeginReprogramFallback(String aDeviceId, String aFileUri, CpProxy.CallbackAsyncComplete aCallback); void EndReprogramFallback(IntPtr aAsyncHandle); void SetPropertyDeviceListChanged(System.Action aDeviceListChanged); String PropertyDeviceList(); void SetPropertyConnectionStatusChanged(System.Action aConnectionStatusChanged); String PropertyConnectionStatus(); } internal class SyncDeviceListAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; private String iList; public SyncDeviceListAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } public String List() { return iList; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndDeviceList(aAsyncHandle, out iList); } }; internal class SyncDeviceSettingsAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; private String iSettings; public SyncDeviceSettingsAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } public String Settings() { return iSettings; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndDeviceSettings(aAsyncHandle, out iSettings); } }; internal class SyncConnectionStatusAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; private String iConnectionStatus; public SyncConnectionStatusAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } public String ConnectionStatus() { return iConnectionStatus; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndConnectionStatus(aAsyncHandle, out iConnectionStatus); } }; internal class SyncSetAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; public SyncSetAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndSet(aAsyncHandle); } }; internal class SyncReprogramAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; public SyncReprogramAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndReprogram(aAsyncHandle); } }; internal class SyncReprogramFallbackAvOpenhomeOrgExakt1 : SyncProxyAction { private CpProxyAvOpenhomeOrgExakt1 iService; public SyncReprogramFallbackAvOpenhomeOrgExakt1(CpProxyAvOpenhomeOrgExakt1 aProxy) { iService = aProxy; } protected override void CompleteRequest(IntPtr aAsyncHandle) { iService.EndReprogramFallback(aAsyncHandle); } }; /// <summary> /// Proxy for the av.openhome.org:Exakt:1 UPnP service /// </summary> public class CpProxyAvOpenhomeOrgExakt1 : CpProxy, IDisposable, ICpProxyAvOpenhomeOrgExakt1 { private OpenHome.Net.Core.Action iActionDeviceList; private OpenHome.Net.Core.Action iActionDeviceSettings; private OpenHome.Net.Core.Action iActionConnectionStatus; private OpenHome.Net.Core.Action iActionSet; private OpenHome.Net.Core.Action iActionReprogram; private OpenHome.Net.Core.Action iActionReprogramFallback; private PropertyString iDeviceList; private PropertyString iConnectionStatus; private System.Action iDeviceListChanged; private System.Action iConnectionStatusChanged; private Mutex iPropertyLock; /// <summary> /// Constructor /// </summary> /// <remarks>Use CpProxy::[Un]Subscribe() to enable/disable querying of state variable and reporting of their changes.</remarks> /// <param name="aDevice">The device to use</param> public CpProxyAvOpenhomeOrgExakt1(ICpDevice aDevice) : base("av-openhome-org", "Exakt", 1, aDevice) { OpenHome.Net.Core.Parameter param; List<String> allowedValues = new List<String>(); iActionDeviceList = new OpenHome.Net.Core.Action("DeviceList"); param = new ParameterString("List", allowedValues); iActionDeviceList.AddOutputParameter(param); iActionDeviceSettings = new OpenHome.Net.Core.Action("DeviceSettings"); param = new ParameterString("DeviceId", allowedValues); iActionDeviceSettings.AddInputParameter(param); param = new ParameterString("Settings", allowedValues); iActionDeviceSettings.AddOutputParameter(param); iActionConnectionStatus = new OpenHome.Net.Core.Action("ConnectionStatus"); param = new ParameterString("ConnectionStatus", allowedValues); iActionConnectionStatus.AddOutputParameter(param); iActionSet = new OpenHome.Net.Core.Action("Set"); param = new ParameterString("DeviceId", allowedValues); iActionSet.AddInputParameter(param); param = new ParameterUint("BankId"); iActionSet.AddInputParameter(param); param = new ParameterString("FileUri", allowedValues); iActionSet.AddInputParameter(param); param = new ParameterBool("Mute"); iActionSet.AddInputParameter(param); param = new ParameterBool("Persist"); iActionSet.AddInputParameter(param); iActionReprogram = new OpenHome.Net.Core.Action("Reprogram"); param = new ParameterString("DeviceId", allowedValues); iActionReprogram.AddInputParameter(param); param = new ParameterString("FileUri", allowedValues); iActionReprogram.AddInputParameter(param); iActionReprogramFallback = new OpenHome.Net.Core.Action("ReprogramFallback"); param = new ParameterString("DeviceId", allowedValues); iActionReprogramFallback.AddInputParameter(param); param = new ParameterString("FileUri", allowedValues); iActionReprogramFallback.AddInputParameter(param); iDeviceList = new PropertyString("DeviceList", DeviceListPropertyChanged); AddProperty(iDeviceList); iConnectionStatus = new PropertyString("ConnectionStatus", ConnectionStatusPropertyChanged); AddProperty(iConnectionStatus); iPropertyLock = new Mutex(); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aList"></param> public void SyncDeviceList(out String aList) { SyncDeviceListAvOpenhomeOrgExakt1 sync = new SyncDeviceListAvOpenhomeOrgExakt1(this); BeginDeviceList(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aList = sync.List(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndDeviceList().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginDeviceList(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionDeviceList, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionDeviceList.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aList"></param> public void EndDeviceList(IntPtr aAsyncHandle, out String aList) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aList = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aSettings"></param> public void SyncDeviceSettings(String aDeviceId, out String aSettings) { SyncDeviceSettingsAvOpenhomeOrgExakt1 sync = new SyncDeviceSettingsAvOpenhomeOrgExakt1(this); BeginDeviceSettings(aDeviceId, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aSettings = sync.Settings(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndDeviceSettings().</remarks> /// <param name="aDeviceId"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginDeviceSettings(String aDeviceId, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionDeviceSettings, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionDeviceSettings.InputParameter(inIndex++), aDeviceId)); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionDeviceSettings.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aSettings"></param> public void EndDeviceSettings(IntPtr aAsyncHandle, out String aSettings) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aSettings = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aConnectionStatus"></param> public void SyncConnectionStatus(out String aConnectionStatus) { SyncConnectionStatusAvOpenhomeOrgExakt1 sync = new SyncConnectionStatusAvOpenhomeOrgExakt1(this); BeginConnectionStatus(sync.AsyncComplete()); sync.Wait(); sync.ReportError(); aConnectionStatus = sync.ConnectionStatus(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndConnectionStatus().</remarks> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginConnectionStatus(CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionConnectionStatus, aCallback); int outIndex = 0; invocation.AddOutput(new ArgumentString((ParameterString)iActionConnectionStatus.OutputParameter(outIndex++))); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> /// <param name="aConnectionStatus"></param> public void EndConnectionStatus(IntPtr aAsyncHandle, out String aConnectionStatus) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } uint index = 0; aConnectionStatus = Invocation.OutputString(aAsyncHandle, index++); } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aBankId"></param> /// <param name="aFileUri"></param> /// <param name="aMute"></param> /// <param name="aPersist"></param> public void SyncSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist) { SyncSetAvOpenhomeOrgExakt1 sync = new SyncSetAvOpenhomeOrgExakt1(this); BeginSet(aDeviceId, aBankId, aFileUri, aMute, aPersist, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndSet().</remarks> /// <param name="aDeviceId"></param> /// <param name="aBankId"></param> /// <param name="aFileUri"></param> /// <param name="aMute"></param> /// <param name="aPersist"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginSet(String aDeviceId, uint aBankId, String aFileUri, bool aMute, bool aPersist, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionSet, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionSet.InputParameter(inIndex++), aDeviceId)); invocation.AddInput(new ArgumentUint((ParameterUint)iActionSet.InputParameter(inIndex++), aBankId)); invocation.AddInput(new ArgumentString((ParameterString)iActionSet.InputParameter(inIndex++), aFileUri)); invocation.AddInput(new ArgumentBool((ParameterBool)iActionSet.InputParameter(inIndex++), aMute)); invocation.AddInput(new ArgumentBool((ParameterBool)iActionSet.InputParameter(inIndex++), aPersist)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndSet(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> public void SyncReprogram(String aDeviceId, String aFileUri) { SyncReprogramAvOpenhomeOrgExakt1 sync = new SyncReprogramAvOpenhomeOrgExakt1(this); BeginReprogram(aDeviceId, aFileUri, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndReprogram().</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginReprogram(String aDeviceId, String aFileUri, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionReprogram, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionReprogram.InputParameter(inIndex++), aDeviceId)); invocation.AddInput(new ArgumentString((ParameterString)iActionReprogram.InputParameter(inIndex++), aFileUri)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndReprogram(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Invoke the action synchronously /// </summary> /// <remarks>Blocks until the action has been processed /// on the device and sets any output arguments</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> public void SyncReprogramFallback(String aDeviceId, String aFileUri) { SyncReprogramFallbackAvOpenhomeOrgExakt1 sync = new SyncReprogramFallbackAvOpenhomeOrgExakt1(this); BeginReprogramFallback(aDeviceId, aFileUri, sync.AsyncComplete()); sync.Wait(); sync.ReportError(); } /// <summary> /// Invoke the action asynchronously /// </summary> /// <remarks>Returns immediately and will run the client-specified callback when the action /// later completes. Any output arguments can then be retrieved by calling /// EndReprogramFallback().</remarks> /// <param name="aDeviceId"></param> /// <param name="aFileUri"></param> /// <param name="aCallback">Delegate to run when the action completes. /// This is guaranteed to be run but may indicate an error</param> public void BeginReprogramFallback(String aDeviceId, String aFileUri, CallbackAsyncComplete aCallback) { Invocation invocation = iService.Invocation(iActionReprogramFallback, aCallback); int inIndex = 0; invocation.AddInput(new ArgumentString((ParameterString)iActionReprogramFallback.InputParameter(inIndex++), aDeviceId)); invocation.AddInput(new ArgumentString((ParameterString)iActionReprogramFallback.InputParameter(inIndex++), aFileUri)); iService.InvokeAction(invocation); } /// <summary> /// Retrieve the output arguments from an asynchronously invoked action. /// </summary> /// <remarks>This may only be called from the callback set in the above Begin function.</remarks> /// <param name="aAsyncHandle">Argument passed to the delegate set in the above Begin function</param> public void EndReprogramFallback(IntPtr aAsyncHandle) { uint code; string desc; if (Invocation.Error(aAsyncHandle, out code, out desc)) { throw new ProxyError(code, desc); } } /// <summary> /// Set a delegate to be run when the DeviceList state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgExakt1 instance will not overlap.</remarks> /// <param name="aDeviceListChanged">The delegate to run when the state variable changes</param> public void SetPropertyDeviceListChanged(System.Action aDeviceListChanged) { lock (iPropertyLock) { iDeviceListChanged = aDeviceListChanged; } } private void DeviceListPropertyChanged() { lock (iPropertyLock) { ReportEvent(iDeviceListChanged); } } /// <summary> /// Set a delegate to be run when the ConnectionStatus state variable changes. /// </summary> /// <remarks>Callbacks may be run in different threads but callbacks for a /// CpProxyAvOpenhomeOrgExakt1 instance will not overlap.</remarks> /// <param name="aConnectionStatusChanged">The delegate to run when the state variable changes</param> public void SetPropertyConnectionStatusChanged(System.Action aConnectionStatusChanged) { lock (iPropertyLock) { iConnectionStatusChanged = aConnectionStatusChanged; } } private void ConnectionStatusPropertyChanged() { lock (iPropertyLock) { ReportEvent(iConnectionStatusChanged); } } /// <summary> /// Query the value of the DeviceList property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the DeviceList property</returns> public String PropertyDeviceList() { PropertyReadLock(); String val; try { val = iDeviceList.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Query the value of the ConnectionStatus property. /// </summary> /// <remarks>This function is threadsafe and can only be called if Subscribe() has been /// called and a first eventing callback received more recently than any call /// to Unsubscribe().</remarks> /// <returns>Value of the ConnectionStatus property</returns> public String PropertyConnectionStatus() { PropertyReadLock(); String val; try { val = iConnectionStatus.Value(); } finally { PropertyReadUnlock(); } return val; } /// <summary> /// Must be called for each class instance. Must be called before Core.Library.Close(). /// </summary> public void Dispose() { lock (this) { if (iHandle == IntPtr.Zero) return; DisposeProxy(); iHandle = IntPtr.Zero; } iActionDeviceList.Dispose(); iActionDeviceSettings.Dispose(); iActionConnectionStatus.Dispose(); iActionSet.Dispose(); iActionReprogram.Dispose(); iActionReprogramFallback.Dispose(); iDeviceList.Dispose(); iConnectionStatus.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.Security; using System.Diagnostics; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; namespace System.Globalization { public partial class CompareInfo { private unsafe void InitSort(CultureInfo culture) { _sortName = culture.SortName; m_name = culture._name; _sortName = culture.SortName; if (_invariantMode) { _sortHandle = IntPtr.Zero; } else { const uint LCMAP_SORTHANDLE = 0x20000000; IntPtr handle; int ret = Interop.Kernel32.LCMapStringEx(_sortName, LCMAP_SORTHANDLE, null, 0, &handle, IntPtr.Size, null, null, IntPtr.Zero); _sortHandle = ret > 0 ? handle : IntPtr.Zero; } } private static unsafe int FindStringOrdinal( uint dwFindStringOrdinalFlags, string stringSource, int offset, int cchSource, string value, int cchValue, bool bIgnoreCase) { Debug.Assert(!GlobalizationMode.Invariant); fixed (char* pSource = stringSource) fixed (char* pValue = value) { int ret = Interop.Kernel32.FindStringOrdinal( dwFindStringOrdinalFlags, pSource + offset, cchSource, pValue, cchValue, bIgnoreCase ? 1 : 0); return ret < 0 ? ret : ret + offset; } } internal static int IndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMSTART, source, startIndex, count, value, value.Length, ignoreCase); } internal static int LastIndexOfOrdinalCore(string source, string value, int startIndex, int count, bool ignoreCase) { Debug.Assert(!GlobalizationMode.Invariant); Debug.Assert(source != null); Debug.Assert(value != null); return FindStringOrdinal(FIND_FROMEND, source, startIndex - count + 1, count, value, value.Length, ignoreCase); } private unsafe int GetHashCodeOfStringCore(string source, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(source != null); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); if (source.Length == 0) { return 0; } int flags = GetNativeCompareFlags(options); int tmpHash = 0; #if CORECLR tmpHash = InternalGetGlobalizedHashCode(_sortHandle, _sortName, source, source.Length, flags); #else fixed (char* pSource = source) { if (Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_HASH | (uint)flags, pSource, source.Length, &tmpHash, sizeof(int), null, null, _sortHandle) == 0) { Environment.FailFast("LCMapStringEx failed!"); } } #endif return tmpHash; } private static unsafe int CompareStringOrdinalIgnoreCase(char* string1, int count1, char* string2, int count2) { Debug.Assert(!GlobalizationMode.Invariant); // Use the OS to compare and then convert the result to expected value by subtracting 2 return Interop.Kernel32.CompareStringOrdinal(string1, count1, string2, count2, true) - 2; } // TODO https://github.com/dotnet/coreclr/issues/13827: // This method shouldn't be necessary, as we should be able to just use the overload // that takes two spans. But due to this issue, that's adding significant overhead. private unsafe int CompareString(ReadOnlySpan<char> string1, string string2, CompareOptions options) { Debug.Assert(string2 != null); Debug.Assert(!_invariantMode); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &string2.GetRawStringData()) { int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1, string1.Length, pString2, string2.Length, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int CompareString(ReadOnlySpan<char> string1, ReadOnlySpan<char> string2, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pString1 = &MemoryMarshal.GetReference(string1)) fixed (char* pString2 = &MemoryMarshal.GetReference(string2)) { int result = Interop.Kernel32.CompareStringEx( pLocaleName, (uint)GetNativeCompareFlags(options), pString1, string1.Length, pString2, string2.Length, null, null, _sortHandle); if (result == 0) { Environment.FailFast("CompareStringEx failed"); } // Map CompareStringEx return value to -1, 0, 1. return result - 2; } } private unsafe int FindString( uint dwFindNLSStringFlags, string lpStringSource, int startSource, int cchSource, string lpStringValue, int startValue, int cchValue, int *pcchFound) { Debug.Assert(!_invariantMode); string localeName = _sortHandle != IntPtr.Zero ? null : _sortName; fixed (char* pLocaleName = localeName) fixed (char* pSource = lpStringSource) fixed (char* pValue = lpStringValue) { char* pS = pSource + startSource; char* pV = pValue + startValue; return Interop.Kernel32.FindNLSStringEx( pLocaleName, dwFindNLSStringFlags, pS, cchSource, pV, cchValue, pcchFound, null, null, _sortHandle); } } internal unsafe int IndexOfCore(String source, String target, int startIndex, int count, CompareOptions options, int* matchLengthPtr) { Debug.Assert(!_invariantMode); Debug.Assert(source != null); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); if (target.Length == 0) { if (matchLengthPtr != null) *matchLengthPtr = 0; return startIndex; } if (source.Length == 0) { return -1; } if ((options & CompareOptions.Ordinal) != 0) { int retValue = FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: false); if (retValue >= 0) { if (matchLengthPtr != null) *matchLengthPtr = target.Length; } return retValue; } else { int retValue = FindString(FIND_FROMSTART | (uint)GetNativeCompareFlags(options), source, startIndex, count, target, 0, target.Length, matchLengthPtr); if (retValue >= 0) { return retValue + startIndex; } } return -1; } private unsafe int LastIndexOfCore(string source, string target, int startIndex, int count, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(target != null); Debug.Assert((options & CompareOptions.OrdinalIgnoreCase) == 0); // TODO: Consider moving this up to the relevent APIs we need to ensure this behavior for // and add a precondition that target is not empty. if (target.Length == 0) return startIndex; // keep Whidbey compatibility if ((options & CompareOptions.Ordinal) != 0) { return FastIndexOfString(source, target, startIndex, count, target.Length, findLastIndex: true); } else { int retValue = FindString(FIND_FROMEND | (uint) GetNativeCompareFlags(options), source, startIndex - count + 1, count, target, 0, target.Length, null); if (retValue >= 0) { return retValue + startIndex - (count - 1); } } return -1; } private unsafe bool StartsWith(string source, string prefix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(prefix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_STARTSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, prefix, 0, prefix.Length, null) >= 0; } private unsafe bool EndsWith(string source, string suffix, CompareOptions options) { Debug.Assert(!_invariantMode); Debug.Assert(!string.IsNullOrEmpty(source)); Debug.Assert(!string.IsNullOrEmpty(suffix)); Debug.Assert((options & (CompareOptions.Ordinal | CompareOptions.OrdinalIgnoreCase)) == 0); return FindString(FIND_ENDSWITH | (uint)GetNativeCompareFlags(options), source, 0, source.Length, suffix, 0, suffix.Length, null) >= 0; } // PAL ends here [NonSerialized] private IntPtr _sortHandle; private const uint LCMAP_SORTKEY = 0x00000400; private const uint LCMAP_HASH = 0x00040000; private const int FIND_STARTSWITH = 0x00100000; private const int FIND_ENDSWITH = 0x00200000; private const int FIND_FROMSTART = 0x00400000; private const int FIND_FROMEND = 0x00800000; // TODO: Instead of this method could we just have upstack code call IndexOfOrdinal with ignoreCase = false? private static unsafe int FastIndexOfString(string source, string target, int startIndex, int sourceCount, int targetCount, bool findLastIndex) { int retValue = -1; int sourceStartIndex = findLastIndex ? startIndex - sourceCount + 1 : startIndex; fixed (char* pSource = source, spTarget = target) { char* spSubSource = pSource + sourceStartIndex; if (findLastIndex) { int startPattern = (sourceCount - 1) - targetCount + 1; if (startPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = startPattern; ctrSrc >= 0; ctrSrc--) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex - sourceCount + 1; } } else { int endPattern = (sourceCount - 1) - targetCount + 1; if (endPattern < 0) return -1; char patternChar0 = spTarget[0]; for (int ctrSrc = 0; ctrSrc <= endPattern; ctrSrc++) { if (spSubSource[ctrSrc] != patternChar0) continue; int ctrPat; for (ctrPat = 1; ctrPat < targetCount; ctrPat++) { if (spSubSource[ctrSrc + ctrPat] != spTarget[ctrPat]) break; } if (ctrPat == targetCount) { retValue = ctrSrc; break; } } if (retValue >= 0) { retValue += startIndex; } } } return retValue; } private unsafe SortKey CreateSortKey(String source, CompareOptions options) { Debug.Assert(!_invariantMode); if (source == null) { throw new ArgumentNullException(nameof(source)); } if ((options & ValidSortkeyCtorMaskOffFlags) != 0) { throw new ArgumentException(SR.Argument_InvalidFlag, nameof(options)); } byte [] keyData = null; if (source.Length == 0) { keyData = Array.Empty<byte>(); } else { fixed (char *pSource = source) { int result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), pSource, source.Length, null, 0, null, null, _sortHandle); if (result == 0) { throw new ArgumentException(SR.Argument_InvalidFlag, "source"); } keyData = new byte[result]; fixed (byte* pBytes = keyData) { result = Interop.Kernel32.LCMapStringEx(_sortHandle != IntPtr.Zero ? null : _sortName, LCMAP_SORTKEY | (uint) GetNativeCompareFlags(options), pSource, source.Length, pBytes, keyData.Length, null, null, _sortHandle); } } } return new SortKey(Name, source, options, keyData); } private static unsafe bool IsSortable(char* text, int length) { Debug.Assert(!GlobalizationMode.Invariant); return Interop.Kernel32.IsNLSDefinedString(Interop.Kernel32.COMPARE_STRING, 0, IntPtr.Zero, text, length); } private const int COMPARE_OPTIONS_ORDINAL = 0x40000000; // Ordinal private const int NORM_IGNORECASE = 0x00000001; // Ignores case. (use LINGUISTIC_IGNORECASE instead) private const int NORM_IGNOREKANATYPE = 0x00010000; // Does not differentiate between Hiragana and Katakana characters. Corresponding Hiragana and Katakana will compare as equal. private const int NORM_IGNORENONSPACE = 0x00000002; // Ignores nonspacing. This flag also removes Japanese accent characters. (use LINGUISTIC_IGNOREDIACRITIC instead) private const int NORM_IGNORESYMBOLS = 0x00000004; // Ignores symbols. private const int NORM_IGNOREWIDTH = 0x00020000; // Does not differentiate between a single-byte character and the same character as a double-byte character. private const int NORM_LINGUISTIC_CASING = 0x08000000; // use linguistic rules for casing private const int SORT_STRINGSORT = 0x00001000; // Treats punctuation the same as symbols. private static int GetNativeCompareFlags(CompareOptions options) { // Use "linguistic casing" by default (load the culture's casing exception tables) int nativeCompareFlags = NORM_LINGUISTIC_CASING; if ((options & CompareOptions.IgnoreCase) != 0) { nativeCompareFlags |= NORM_IGNORECASE; } if ((options & CompareOptions.IgnoreKanaType) != 0) { nativeCompareFlags |= NORM_IGNOREKANATYPE; } if ((options & CompareOptions.IgnoreNonSpace) != 0) { nativeCompareFlags |= NORM_IGNORENONSPACE; } if ((options & CompareOptions.IgnoreSymbols) != 0) { nativeCompareFlags |= NORM_IGNORESYMBOLS; } if ((options & CompareOptions.IgnoreWidth) != 0) { nativeCompareFlags |= NORM_IGNOREWIDTH; } if ((options & CompareOptions.StringSort) != 0) { nativeCompareFlags |= SORT_STRINGSORT; } // TODO: Can we try for GetNativeCompareFlags to never // take Ordinal or OrdinalIgnoreCase. This value is not part of Win32, we just handle it special // in some places. // Suffix & Prefix shouldn't use this, make sure to turn off the NORM_LINGUISTIC_CASING flag if (options == CompareOptions.Ordinal) { nativeCompareFlags = COMPARE_OPTIONS_ORDINAL; } Debug.Assert(((options & ~(CompareOptions.IgnoreCase | CompareOptions.IgnoreKanaType | CompareOptions.IgnoreNonSpace | CompareOptions.IgnoreSymbols | CompareOptions.IgnoreWidth | CompareOptions.StringSort)) == 0) || (options == CompareOptions.Ordinal), "[CompareInfo.GetNativeCompareFlags]Expected all flags to be handled"); return nativeCompareFlags; } private unsafe SortVersion GetSortVersion() { Debug.Assert(!_invariantMode); Interop.Kernel32.NlsVersionInfoEx nlsVersion = new Interop.Kernel32.NlsVersionInfoEx(); nlsVersion.dwNLSVersionInfoSize = Marshal.SizeOf(typeof(Interop.Kernel32.NlsVersionInfoEx)); Interop.Kernel32.GetNLSVersionEx(Interop.Kernel32.COMPARE_STRING, _sortName, &nlsVersion); return new SortVersion( nlsVersion.dwNLSVersion, nlsVersion.dwEffectiveId == 0 ? LCID : nlsVersion.dwEffectiveId, nlsVersion.guidCustomVersion); } #if CORECLR // Get a locale sensitive sort hash code from native code -- COMNlsInfo::InternalGetGlobalizedHashCode [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] private static extern int InternalGetGlobalizedHashCode(IntPtr handle, string localeName, string source, int length, int dwFlags); #endif } }
using System; using System.Collections.Generic; using System.Diagnostics; using hw.Helper; using JetBrains.Annotations; namespace hw.DebugFormatter { /// <summary> /// Summary description for Dumpable. /// </summary> [Dump("Dump")] [DebuggerDisplay("{DebuggerDumpString}")] public class Dumpable { sealed class MethodDumpTraceItem { public MethodDumpTraceItem(int frameCount, bool trace) { FrameCount = frameCount; Trace = trace; } internal int FrameCount {get;} internal bool Trace {get;} } static readonly Stack<MethodDumpTraceItem> MethodDumpTraceSwitches = new Stack<MethodDumpTraceItem>(); public static bool? IsMethodDumpTraceInhibited; /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] public static void NotImplementedFunction(params object[] p) { var os = Tracer.DumpMethodWithData("not implemented", null, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method start dump, /// </summary> /// <param name="name"> </param> /// <param name="value"> </param> /// <returns> </returns> [DebuggerHidden] public static void Dump(string name, object value) { if(IsMethodDumpTraceActive) { var os = Tracer.DumpData("", new[] {name, value}, 1); Tracer.Line(os); } } /// <summary> /// Method start dump, /// </summary> /// <param name="name"> </param> /// <param name="getValue"> </param> /// <returns> </returns> [DebuggerHidden] public static void Dump(string name, Func<object> getValue) { if(IsMethodDumpTraceActive) { var os = Tracer.DumpData("", new[] {name, getValue()}, 1); Tracer.Line(os); } } /// <summary> /// Method dump, /// </summary> /// <param name="rv"> </param> /// <param name="breakExecution"> </param> /// <returns> </returns> [DebuggerHidden] protected static T ReturnMethodDump<T>(T rv, bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); Tracer.Line(Tracer.MethodHeader(stackFrameDepth: 1) + "[returns] " + Tracer.Dump(rv)); if(breakExecution) Tracer.TraceBreak(); } return rv; } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void ReturnVoidMethodDump(bool breakExecution = true) { if(IsMethodDumpTraceActive) { Tracer.IndentEnd(); Tracer.Line(Tracer.MethodHeader(stackFrameDepth: 1) + "[returns]"); if(breakExecution) Tracer.TraceBreak(); } } /// <summary> /// Method dump, /// </summary> [DebuggerHidden] protected static void EndMethodDump() { if(!Debugger.IsAttached) return; CheckDumpLevel(1); MethodDumpTraceSwitches.Pop(); } static void CheckDumpLevel(int depth) { if(!Debugger.IsAttached) return; var top = MethodDumpTraceSwitches.Peek(); if(top.Trace) Tracer.Assert(top.FrameCount == Tracer.CurrentFrameCount(depth + 1)); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected static void DumpDataWithBreak(string text, params object[] p) { var os = Tracer.DumpData(text, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } static void StartMethodDump(int depth, bool trace) { if(!Debugger.IsAttached) return; var frameCount = trace ? Tracer.CurrentFrameCount(depth + 1) : 0; MethodDumpTraceSwitches.Push(new MethodDumpTraceItem(frameCount, trace)); } static bool IsMethodDumpTraceActive { get { if(IsMethodDumpTraceInhibited != null) return !IsMethodDumpTraceInhibited.Value; if(!Debugger.IsAttached) return false; //CheckDumpLevel(2); return MethodDumpTraceSwitches.Peek().Trace; } } /// <summary> /// dump string to be shown in debug windows /// </summary> [DisableDump] [UsedImplicitly] public string DebuggerDumpString => DebuggerDump().Replace("\n", "\r\n"); [DisableDump] [UsedImplicitly] // ReSharper disable once InconsistentNaming public string d => DebuggerDumpString; /// <summary> /// Gets a value indicating whether this instance is in dump. /// </summary> /// <value> /// <c>true</c> /// if this instance is in dump; otherwise, /// <c>false</c> /// . /// </value> /// created 23.09.2006 17:39 [DisableDump] public bool IsInDump {get; set;} /// <summary> /// generate dump string to be shown in debug windows /// </summary> /// <returns> </returns> public virtual string DebuggerDump() => Tracer.Dump(this); // ReSharper disable once InconsistentNaming public void t() => Tracer.Line(DebuggerDumpString); /// <summary> /// Method start dump, /// </summary> /// <param name="trace"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void StartMethodDump(bool trace, params object[] p) { StartMethodDump(1, trace); if(IsMethodDumpTraceActive) { var os = Tracer.DumpMethodWithData("", this, p, 1); Tracer.Line(os); Tracer.IndentStart(); } } [DebuggerHidden] protected void BreakExecution() { if(IsMethodDumpTraceActive) Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="text"> </param> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void DumpMethodWithBreak(string text, params object[] p) { var os = Tracer.DumpMethodWithData(text, this, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } /// <summary> /// Method dump with break, /// </summary> /// <param name="p"> </param> /// <returns> </returns> [DebuggerHidden] protected void NotImplementedMethod(params object[] p) { if(IsInDump) throw new NotImplementedException(); var os = Tracer.DumpMethodWithData("not implemented", this, p, 1); Tracer.Line(os); Tracer.TraceBreak(); } public string Dump() { var oldIsInDump = IsInDump; IsInDump = true; try { return Dump(oldIsInDump); } finally { IsInDump = oldIsInDump; } } protected virtual string Dump(bool isRecursion) { var surround = "<recursion>"; if(!isRecursion) surround = DumpData().Surround("{", "}"); return GetType().PrettyName() + surround; } public virtual string DumpData() { string result; try { result = Tracer.DumpData(this); } catch(Exception) { result = "<not implemented>"; } return result; } public void Dispose() {} } }
/* * 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; namespace Lucene.Net.Search { /* See the description in BooleanScorer.java, comparing * BooleanScorer & BooleanScorer2 */ /// <summary>An alternative to BooleanScorer that also allows a minimum number /// of optional scorers that should match. /// <br/>Implements skipTo(), and has no limitations on the numbers of added scorers. /// <br/>Uses ConjunctionScorer, DisjunctionScorer, ReqOptScorer and ReqExclScorer. /// </summary> class BooleanScorer2:Scorer { private class AnonymousClassDisjunctionSumScorer:DisjunctionSumScorer { private void InitBlock(BooleanScorer2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassDisjunctionSumScorer(BooleanScorer2 enclosingInstance, System.Collections.IList Param1, int Param2):base(Param1, Param2) { InitBlock(enclosingInstance); } private int lastScoredDoc = - 1; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). private float lastDocScore = System.Single.NaN; public override float Score() { int doc = DocID(); if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = base.Score(); lastScoredDoc = doc; } Enclosing_Instance.coordinator.nrMatchers += base.nrMatchers; } return lastDocScore; } } private class AnonymousClassConjunctionScorer:ConjunctionScorer { private void InitBlock(int requiredNrMatchers, BooleanScorer2 enclosingInstance) { this.requiredNrMatchers = requiredNrMatchers; this.enclosingInstance = enclosingInstance; } private int requiredNrMatchers; private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } internal AnonymousClassConjunctionScorer(int requiredNrMatchers, BooleanScorer2 enclosingInstance, Lucene.Net.Search.Similarity Param1, System.Collections.ICollection Param2):base(Param1, Param2) { InitBlock(requiredNrMatchers, enclosingInstance); } private int lastScoredDoc = - 1; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). private float lastDocScore = System.Single.NaN; public override float Score() { int doc = DocID(); if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = base.Score(); lastScoredDoc = doc; } Enclosing_Instance.coordinator.nrMatchers += requiredNrMatchers; } // All scorers match, so defaultSimilarity super.score() always has 1 as // the coordination factor. // Therefore the sum of the scores of the requiredScorers // is used as score. return lastDocScore; } } private System.Collections.IList requiredScorers; private System.Collections.IList optionalScorers; private System.Collections.IList prohibitedScorers; private class Coordinator { public Coordinator(BooleanScorer2 enclosingInstance) { InitBlock(enclosingInstance); } private void InitBlock(BooleanScorer2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } internal float[] coordFactors = null; internal int maxCoord = 0; // to be increased for each non prohibited scorer internal int nrMatchers; // to be increased by score() of match counting scorers. internal virtual void Init() { // use after all scorers have been added. coordFactors = new float[maxCoord + 1]; Similarity sim = Enclosing_Instance.GetSimilarity(); for (int i = 0; i <= maxCoord; i++) { coordFactors[i] = sim.Coord(i, maxCoord); } } } private Coordinator coordinator; /// <summary>The scorer to which all scoring will be delegated, /// except for computing and using the coordination factor. /// </summary> private Scorer countingSumScorer; /// <summary>The number of optionalScorers that need to match (if there are any) </summary> private int minNrShouldMatch; private int doc = - 1; /// <summary> Creates a {@link Scorer} with the given similarity and lists of required, /// prohibited and optional scorers. In no required scorers are added, at least /// one of the optional scorers will have to match during the search. /// /// </summary> /// <param name="similarity">The similarity to be used. /// </param> /// <param name="minNrShouldMatch">The minimum number of optional added scorers that should match /// during the search. In case no required scorers are added, at least /// one of the optional scorers will have to match during the search. /// </param> /// <param name="required">the list of required scorers. /// </param> /// <param name="prohibited">the list of prohibited scorers. /// </param> /// <param name="optional">the list of optional scorers. /// </param> public BooleanScorer2(Similarity similarity, int minNrShouldMatch, System.Collections.IList required, System.Collections.IList prohibited, System.Collections.IList optional):base(similarity) { if (minNrShouldMatch < 0) { throw new System.ArgumentException("Minimum number of optional scorers should not be negative"); } coordinator = new Coordinator(this); this.minNrShouldMatch = minNrShouldMatch; optionalScorers = optional; coordinator.maxCoord += optional.Count; requiredScorers = required; coordinator.maxCoord += required.Count; prohibitedScorers = prohibited; coordinator.Init(); countingSumScorer = MakeCountingSumScorer(); } /// <summary>Count a scorer as a single match. </summary> private class SingleMatchScorer:Scorer { private void InitBlock(BooleanScorer2 enclosingInstance) { this.enclosingInstance = enclosingInstance; } private BooleanScorer2 enclosingInstance; public BooleanScorer2 Enclosing_Instance { get { return enclosingInstance; } } private Scorer scorer; private int lastScoredDoc = - 1; // Save the score of lastScoredDoc, so that we don't compute it more than // once in score(). private float lastDocScore = System.Single.NaN; internal SingleMatchScorer(BooleanScorer2 enclosingInstance, Scorer scorer):base(scorer.GetSimilarity()) { InitBlock(enclosingInstance); this.scorer = scorer; } public override float Score() { int doc = DocID(); if (doc >= lastScoredDoc) { if (doc > lastScoredDoc) { lastDocScore = scorer.Score(); lastScoredDoc = doc; } Enclosing_Instance.coordinator.nrMatchers++; } return lastDocScore; } /// <deprecated> use {@link #DocID()} instead. /// </deprecated> [Obsolete("use DocID() instead. ")] public override int Doc() { return scorer.Doc(); } public override int DocID() { return scorer.DocID(); } /// <deprecated> use {@link #NextDoc()} instead. /// </deprecated> [Obsolete("use NextDoc() instead. ")] public override bool Next() { return scorer.NextDoc() != NO_MORE_DOCS; } public override int NextDoc() { return scorer.NextDoc(); } /// <deprecated> use {@link #Advance(int)} instead. /// </deprecated> [Obsolete("use Advance(int) instead. ")] public override bool SkipTo(int docNr) { return scorer.Advance(docNr) != NO_MORE_DOCS; } public override int Advance(int target) { return scorer.Advance(target); } public override Explanation Explain(int docNr) { return scorer.Explain(docNr); } } private Scorer CountingDisjunctionSumScorer(System.Collections.IList scorers, int minNrShouldMatch) { // each scorer from the list counted as a single matcher return new AnonymousClassDisjunctionSumScorer(this, scorers, minNrShouldMatch); } private static readonly Similarity defaultSimilarity; private Scorer CountingConjunctionSumScorer(System.Collections.IList requiredScorers) { // each scorer from the list counted as a single matcher int requiredNrMatchers = requiredScorers.Count; return new AnonymousClassConjunctionScorer(requiredNrMatchers, this, defaultSimilarity, requiredScorers); } private Scorer DualConjunctionSumScorer(Scorer req1, Scorer req2) { // non counting. return new ConjunctionScorer(defaultSimilarity, new Scorer[]{req1, req2}); // All scorers match, so defaultSimilarity always has 1 as // the coordination factor. // Therefore the sum of the scores of two scorers // is used as score. } /// <summary>Returns the scorer to be used for match counting and score summing. /// Uses requiredScorers, optionalScorers and prohibitedScorers. /// </summary> private Scorer MakeCountingSumScorer() { // each scorer counted as a single matcher return (requiredScorers.Count == 0)?MakeCountingSumScorerNoReq():MakeCountingSumScorerSomeReq(); } private Scorer MakeCountingSumScorerNoReq() { // No required scorers // minNrShouldMatch optional scorers are required, but at least 1 int nrOptRequired = (minNrShouldMatch < 1)?1:minNrShouldMatch; Scorer requiredCountingSumScorer; if (optionalScorers.Count > nrOptRequired) requiredCountingSumScorer = CountingDisjunctionSumScorer(optionalScorers, nrOptRequired); else if (optionalScorers.Count == 1) requiredCountingSumScorer = new SingleMatchScorer(this, (Scorer) optionalScorers[0]); else requiredCountingSumScorer = CountingConjunctionSumScorer(optionalScorers); return AddProhibitedScorers(requiredCountingSumScorer); } private Scorer MakeCountingSumScorerSomeReq() { // At least one required scorer. if (optionalScorers.Count == minNrShouldMatch) { // all optional scorers also required. System.Collections.ArrayList allReq = new System.Collections.ArrayList(requiredScorers); allReq.AddRange(optionalScorers); return AddProhibitedScorers(CountingConjunctionSumScorer(allReq)); } else { // optionalScorers.size() > minNrShouldMatch, and at least one required scorer Scorer requiredCountingSumScorer = requiredScorers.Count == 1?new SingleMatchScorer(this, (Scorer) requiredScorers[0]):CountingConjunctionSumScorer(requiredScorers); if (minNrShouldMatch > 0) { // use a required disjunction scorer over the optional scorers return AddProhibitedScorers(DualConjunctionSumScorer(requiredCountingSumScorer, CountingDisjunctionSumScorer(optionalScorers, minNrShouldMatch))); } else { // minNrShouldMatch == 0 return new ReqOptSumScorer(AddProhibitedScorers(requiredCountingSumScorer), optionalScorers.Count == 1?new SingleMatchScorer(this, (Scorer) optionalScorers[0]):CountingDisjunctionSumScorer(optionalScorers, 1)); } } } /// <summary>Returns the scorer to be used for match counting and score summing. /// Uses the given required scorer and the prohibitedScorers. /// </summary> /// <param name="requiredCountingSumScorer">A required scorer already built. /// </param> private Scorer AddProhibitedScorers(Scorer requiredCountingSumScorer) { return (prohibitedScorers.Count == 0)?requiredCountingSumScorer:new ReqExclScorer(requiredCountingSumScorer, ((prohibitedScorers.Count == 1)?(Scorer) prohibitedScorers[0]:new DisjunctionSumScorer(prohibitedScorers))); } /// <summary>Scores and collects all matching documents.</summary> /// <param name="hc">The collector to which all matching documents are passed through /// {@link HitCollector#Collect(int, float)}. /// <br/>When this method is used the {@link #Explain(int)} method should not be used. /// </param> /// <deprecated> use {@link #Score(Collector)} instead. /// </deprecated> [Obsolete("use Score(Collector) instead.")] public override void Score(HitCollector hc) { Score(new HitCollectorWrapper(hc)); } /// <summary>Scores and collects all matching documents.</summary> /// <param name="collector">The collector to which all matching documents are passed through. /// <br/>When this method is used the {@link #Explain(int)} method should not be used. /// </param> public override void Score(Collector collector) { collector.SetScorer(this); while ((doc = countingSumScorer.NextDoc()) != NO_MORE_DOCS) { collector.Collect(doc); } } /// <summary>Expert: Collects matching documents in a range. /// <br/>Note that {@link #Next()} must be called once before this method is /// called for the first time. /// </summary> /// <param name="hc">The collector to which all matching documents are passed through /// {@link HitCollector#Collect(int, float)}. /// </param> /// <param name="max">Do not score documents past this. /// </param> /// <returns> true if more matching documents may remain. /// </returns> /// <deprecated> use {@link #Score(Collector, int, int)} instead. /// </deprecated> [Obsolete("use Score(Collector, int, int) instead.")] protected internal override bool Score(HitCollector hc, int max) { return Score(new HitCollectorWrapper(hc), max, DocID()); } public /*protected internal*/ override bool Score(Collector collector, int max, int firstDocID) { doc = firstDocID; collector.SetScorer(this); while (doc < max) { collector.Collect(doc); doc = countingSumScorer.NextDoc(); } return doc != NO_MORE_DOCS; } /// <deprecated> use {@link #DocID()} instead. /// </deprecated> [Obsolete("use DocID() instead. ")] public override int Doc() { return countingSumScorer.Doc(); } public override int DocID() { return doc; } /// <deprecated> use {@link #NextDoc()} instead. /// </deprecated> [Obsolete("use NextDoc() instead. ")] public override bool Next() { return NextDoc() != NO_MORE_DOCS; } public override int NextDoc() { return doc = countingSumScorer.NextDoc(); } public override float Score() { coordinator.nrMatchers = 0; float sum = countingSumScorer.Score(); return sum * coordinator.coordFactors[coordinator.nrMatchers]; } /// <deprecated> use {@link #Advance(int)} instead. /// </deprecated> [Obsolete("use Advance(int) instead. ")] public override bool SkipTo(int target) { return Advance(target) != NO_MORE_DOCS; } public override int Advance(int target) { return doc = countingSumScorer.Advance(target); } /// <summary>Throws an UnsupportedOperationException. /// TODO: Implement an explanation of the coordination factor. /// </summary> /// <param name="doc">The document number for the explanation. /// </param> /// <throws> UnsupportedOperationException </throws> public override Explanation Explain(int doc) { throw new System.NotSupportedException(); /* How to explain the coordination factor? initCountingSumScorer(); return countingSumScorer.explain(doc); // misses coord factor. */ } static BooleanScorer2() { defaultSimilarity = Similarity.GetDefault(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Dynamic.Utils; namespace System.Linq.Expressions { /// <summary> /// Specifies what kind of jump this <see cref="GotoExpression"/> represents. /// </summary> public enum GotoExpressionKind { /// <summary> /// A <see cref="GotoExpression"/> that represents a jump to some location. /// </summary> Goto, /// <summary> /// A <see cref="GotoExpression"/> that represents a return statement. /// </summary> Return, /// <summary> /// A <see cref="GotoExpression"/> that represents a break statement. /// </summary> Break, /// <summary> /// A <see cref="GotoExpression"/> that represents a continue statement. /// </summary> Continue, } /// <summary> /// Represents an unconditional jump. This includes return statements, break and continue statements, and other jumps. /// </summary> [DebuggerTypeProxy(typeof(Expression.GotoExpressionProxy))] public sealed class GotoExpression : Expression { private readonly GotoExpressionKind _kind; private readonly Expression _value; private readonly LabelTarget _target; private readonly Type _type; internal GotoExpression(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) { _kind = kind; _value = value; _target = target; _type = type; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. (Inherited from <see cref="Expression"/>.) /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return _type; } } /// <summary> /// Returns the node type of this <see cref="Expression" />. (Inherited from <see cref="Expression" />.) /// </summary> /// <returns>The <see cref="ExpressionType"/> that represents this expression.</returns> public sealed override ExpressionType NodeType { get { return ExpressionType.Goto; } } /// <summary> /// The value passed to the target, or null if the target is of type /// System.Void. /// </summary> public Expression Value { get { return _value; } } /// <summary> /// The target label where this node jumps to. /// </summary> public LabelTarget Target { get { return _target; } } /// <summary> /// The kind of the goto. For information purposes only. /// </summary> public GotoExpressionKind Kind { get { return _kind; } } /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitGoto(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="target">The <see cref="Target" /> property of the result.</param> /// <param name="value">The <see cref="Value" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public GotoExpression Update(LabelTarget target, Expression value) { if (target == Target && value == Value) { return this; } return Expression.MakeGoto(Kind, target, value, Type); } } public partial class Expression { /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target) { return MakeGoto(GotoExpressionKind.Break, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Break, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>. /// </returns> public static GotoExpression Break(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Break, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a break statement with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Break, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Break(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Break, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a continue statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Continue(LabelTarget target) { return MakeGoto(GotoExpressionKind.Continue, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a continue statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Continue(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Continue, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target) { return MakeGoto(GotoExpressionKind.Return, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Return, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Return, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Return, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a return statement with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Continue, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Return(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Return, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to the specified value, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target) { return MakeGoto(GotoExpressionKind.Goto, target, null, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to the specified value, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and a null value to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Type type) { return MakeGoto(GotoExpressionKind.Goto, target, null, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto. The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Expression value) { return MakeGoto(GotoExpressionKind.Goto, target, value, typeof(void)); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a goto with the specified type. /// The value passed to the label upon jumping can be specified. /// </summary> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to Goto, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression Goto(LabelTarget target, Expression value, Type type) { return MakeGoto(GotoExpressionKind.Goto, target, value, type); } /// <summary> /// Creates a <see cref="GotoExpression"/> representing a jump of the specified <see cref="GotoExpressionKind"/>. /// The value passed to the label upon jumping can also be specified. /// </summary> /// <param name="kind">The <see cref="GotoExpressionKind"/> of the <see cref="GotoExpression"/>.</param> /// <param name="target">The <see cref="LabelTarget"/> that the <see cref="GotoExpression"/> will jump to.</param> /// <param name="value">The value that will be passed to the associated label upon jumping.</param> /// <param name="type">An <see cref="System.Type"/> to set the <see cref="P:Expression.Type"/> property equal to.</param> /// <returns> /// A <see cref="GotoExpression"/> with <see cref="P:GotoExpression.Kind"/> equal to <paramref name="kind"/>, /// the <see cref="P:GotoExpression.Target"/> property set to <paramref name="target"/>, /// the <see cref="P:Expression.Type"/> property set to <paramref name="type"/>, /// and <paramref name="value"/> to be passed to the target label upon jumping. /// </returns> public static GotoExpression MakeGoto(GotoExpressionKind kind, LabelTarget target, Expression value, Type type) { ValidateGoto(target, ref value, nameof(target), nameof(value)); return new GotoExpression(kind, target, value, type); } private static void ValidateGoto(LabelTarget target, ref Expression value, string targetParameter, string valueParameter) { ContractUtils.RequiresNotNull(target, targetParameter); if (value == null) { if (target.Type != typeof(void)) throw Error.LabelMustBeVoidOrHaveExpression(); } else { ValidateGotoType(target.Type, ref value, valueParameter); } } // Standard argument validation, taken from ValidateArgumentTypes private static void ValidateGotoType(Type expectedType, ref Expression value, string paramName) { RequiresCanRead(value, paramName); if (expectedType != typeof(void)) { if (!TypeUtils.AreReferenceAssignable(expectedType, value.Type)) { // C# autoquotes return values, so we'll do that here if (!TryQuote(expectedType, ref value)) { throw Error.ExpressionTypeDoesNotMatchLabel(value.Type, expectedType); } } } } } }
/* * 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 OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Presence { public class PresenceServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IPresenceService m_PresenceService; public PresenceServerPostHandler(IPresenceService service) : base("POST", "/presence") { m_PresenceService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); string method = string.Empty; try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); method = request["METHOD"].ToString(); switch (method) { case "login": return LoginAgent(request); case "logout": return LogoutAgent(request); case "logoutregion": return LogoutRegionAgents(request); case "report": return Report(request); case "getagent": return GetAgent(request); case "getagents": return GetAgents(request); } m_log.DebugFormat("[PRESENCE HANDLER]: unknown method request: {0}", method); } catch (Exception e) { m_log.DebugFormat("[PRESENCE HANDLER]: Exception in method {0}: {1}", method, e); } return FailureResult(); } byte[] LoginAgent(Dictionary<string, object> request) { string user = String.Empty; UUID session = UUID.Zero; UUID ssession = UUID.Zero; if (!request.ContainsKey("UserID") || !request.ContainsKey("SessionID")) return FailureResult(); user = request["UserID"].ToString(); if (!UUID.TryParse(request["SessionID"].ToString(), out session)) return FailureResult(); if (request.ContainsKey("SecureSessionID")) // If it's malformed, we go on with a Zero on it UUID.TryParse(request["SecureSessionID"].ToString(), out ssession); if (m_PresenceService.LoginAgent(user, session, ssession)) return SuccessResult(); return FailureResult(); } byte[] LogoutAgent(Dictionary<string, object> request) { UUID session = UUID.Zero; if (!request.ContainsKey("SessionID")) return FailureResult(); if (!UUID.TryParse(request["SessionID"].ToString(), out session)) return FailureResult(); if (m_PresenceService.LogoutAgent(session)) return SuccessResult(); return FailureResult(); } byte[] LogoutRegionAgents(Dictionary<string, object> request) { UUID region = UUID.Zero; if (!request.ContainsKey("RegionID")) return FailureResult(); if (!UUID.TryParse(request["RegionID"].ToString(), out region)) return FailureResult(); if (m_PresenceService.LogoutRegionAgents(region)) return SuccessResult(); return FailureResult(); } byte[] Report(Dictionary<string, object> request) { UUID session = UUID.Zero; UUID region = UUID.Zero; if (!request.ContainsKey("SessionID") || !request.ContainsKey("RegionID")) return FailureResult(); if (!UUID.TryParse(request["SessionID"].ToString(), out session)) return FailureResult(); if (!UUID.TryParse(request["RegionID"].ToString(), out region)) return FailureResult(); if (m_PresenceService.ReportAgent(session, region)) { return SuccessResult(); } return FailureResult(); } byte[] GetAgent(Dictionary<string, object> request) { UUID session = UUID.Zero; if (!request.ContainsKey("SessionID")) return FailureResult(); if (!UUID.TryParse(request["SessionID"].ToString(), out session)) return FailureResult(); PresenceInfo pinfo = m_PresenceService.GetAgent(session); Dictionary<string, object> result = new Dictionary<string, object>(); if (pinfo == null) result["result"] = "null"; else result["result"] = pinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetAgents(Dictionary<string, object> request) { string[] userIDs; if (!request.ContainsKey("uuids")) { m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents called without required uuids argument"); return FailureResult(); } if (!(request["uuids"] is List<string>)) { m_log.DebugFormat("[PRESENCE HANDLER]: GetAgents input argument was of unexpected type {0}", request["uuids"].GetType().ToString()); return FailureResult(); } userIDs = ((List<string>)request["uuids"]).ToArray(); PresenceInfo[] pinfos = m_PresenceService.GetAgents(userIDs); Dictionary<string, object> result = new Dictionary<string, object>(); if ((pinfos == null) || ((pinfos != null) && (pinfos.Length == 0))) result["result"] = "null"; else { int i = 0; foreach (PresenceInfo pinfo in pinfos) { Dictionary<string, object> rinfoDict = pinfo.ToKeyValuePairs(); result["presence" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } 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(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.OsLogin.V1.Snippets { using Google.Cloud.OsLogin.Common; using Google.Protobuf.WellKnownTypes; using System.Threading.Tasks; /// <summary>Generated snippets.</summary> public sealed class GeneratedOsLoginServiceClientSnippets { /// <summary>Snippet for DeletePosixAccount</summary> public void DeletePosixAccountRequestObject() { // Snippet: DeletePosixAccount(DeletePosixAccountRequest, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; // Make the request osLoginServiceClient.DeletePosixAccount(request); // End snippet } /// <summary>Snippet for DeletePosixAccountAsync</summary> public async Task DeletePosixAccountRequestObjectAsync() { // Snippet: DeletePosixAccountAsync(DeletePosixAccountRequest, CallSettings) // Additional: DeletePosixAccountAsync(DeletePosixAccountRequest, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) DeletePosixAccountRequest request = new DeletePosixAccountRequest { PosixAccountName = PosixAccountName.FromUserProject("[USER]", "[PROJECT]"), }; // Make the request await osLoginServiceClient.DeletePosixAccountAsync(request); // End snippet } /// <summary>Snippet for DeletePosixAccount</summary> public void DeletePosixAccount() { // Snippet: DeletePosixAccount(string, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]/projects/[PROJECT]"; // Make the request osLoginServiceClient.DeletePosixAccount(name); // End snippet } /// <summary>Snippet for DeletePosixAccountAsync</summary> public async Task DeletePosixAccountAsync() { // Snippet: DeletePosixAccountAsync(string, CallSettings) // Additional: DeletePosixAccountAsync(string, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]/projects/[PROJECT]"; // Make the request await osLoginServiceClient.DeletePosixAccountAsync(name); // End snippet } /// <summary>Snippet for DeletePosixAccount</summary> public void DeletePosixAccountResourceNames() { // Snippet: DeletePosixAccount(PosixAccountName, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) PosixAccountName name = PosixAccountName.FromUserProject("[USER]", "[PROJECT]"); // Make the request osLoginServiceClient.DeletePosixAccount(name); // End snippet } /// <summary>Snippet for DeletePosixAccountAsync</summary> public async Task DeletePosixAccountResourceNamesAsync() { // Snippet: DeletePosixAccountAsync(PosixAccountName, CallSettings) // Additional: DeletePosixAccountAsync(PosixAccountName, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) PosixAccountName name = PosixAccountName.FromUserProject("[USER]", "[PROJECT]"); // Make the request await osLoginServiceClient.DeletePosixAccountAsync(name); // End snippet } /// <summary>Snippet for DeleteSshPublicKey</summary> public void DeleteSshPublicKeyRequestObject() { // Snippet: DeleteSshPublicKey(DeleteSshPublicKeyRequest, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; // Make the request osLoginServiceClient.DeleteSshPublicKey(request); // End snippet } /// <summary>Snippet for DeleteSshPublicKeyAsync</summary> public async Task DeleteSshPublicKeyRequestObjectAsync() { // Snippet: DeleteSshPublicKeyAsync(DeleteSshPublicKeyRequest, CallSettings) // Additional: DeleteSshPublicKeyAsync(DeleteSshPublicKeyRequest, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) DeleteSshPublicKeyRequest request = new DeleteSshPublicKeyRequest { SshPublicKeyName = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; // Make the request await osLoginServiceClient.DeleteSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for DeleteSshPublicKey</summary> public void DeleteSshPublicKey() { // Snippet: DeleteSshPublicKey(string, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; // Make the request osLoginServiceClient.DeleteSshPublicKey(name); // End snippet } /// <summary>Snippet for DeleteSshPublicKeyAsync</summary> public async Task DeleteSshPublicKeyAsync() { // Snippet: DeleteSshPublicKeyAsync(string, CallSettings) // Additional: DeleteSshPublicKeyAsync(string, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; // Make the request await osLoginServiceClient.DeleteSshPublicKeyAsync(name); // End snippet } /// <summary>Snippet for DeleteSshPublicKey</summary> public void DeleteSshPublicKeyResourceNames() { // Snippet: DeleteSshPublicKey(SshPublicKeyName, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); // Make the request osLoginServiceClient.DeleteSshPublicKey(name); // End snippet } /// <summary>Snippet for DeleteSshPublicKeyAsync</summary> public async Task DeleteSshPublicKeyResourceNamesAsync() { // Snippet: DeleteSshPublicKeyAsync(SshPublicKeyName, CallSettings) // Additional: DeleteSshPublicKeyAsync(SshPublicKeyName, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); // Make the request await osLoginServiceClient.DeleteSshPublicKeyAsync(name); // End snippet } /// <summary>Snippet for GetLoginProfile</summary> public void GetLoginProfileRequestObject() { // Snippet: GetLoginProfile(GetLoginProfileRequest, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = UserName.FromUser("[USER]"), ProjectId = "", SystemId = "", }; // Make the request LoginProfile response = osLoginServiceClient.GetLoginProfile(request); // End snippet } /// <summary>Snippet for GetLoginProfileAsync</summary> public async Task GetLoginProfileRequestObjectAsync() { // Snippet: GetLoginProfileAsync(GetLoginProfileRequest, CallSettings) // Additional: GetLoginProfileAsync(GetLoginProfileRequest, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) GetLoginProfileRequest request = new GetLoginProfileRequest { UserName = UserName.FromUser("[USER]"), ProjectId = "", SystemId = "", }; // Make the request LoginProfile response = await osLoginServiceClient.GetLoginProfileAsync(request); // End snippet } /// <summary>Snippet for GetLoginProfile</summary> public void GetLoginProfile() { // Snippet: GetLoginProfile(string, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]"; // Make the request LoginProfile response = osLoginServiceClient.GetLoginProfile(name); // End snippet } /// <summary>Snippet for GetLoginProfileAsync</summary> public async Task GetLoginProfileAsync() { // Snippet: GetLoginProfileAsync(string, CallSettings) // Additional: GetLoginProfileAsync(string, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]"; // Make the request LoginProfile response = await osLoginServiceClient.GetLoginProfileAsync(name); // End snippet } /// <summary>Snippet for GetLoginProfile</summary> public void GetLoginProfileResourceNames() { // Snippet: GetLoginProfile(UserName, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName name = UserName.FromUser("[USER]"); // Make the request LoginProfile response = osLoginServiceClient.GetLoginProfile(name); // End snippet } /// <summary>Snippet for GetLoginProfileAsync</summary> public async Task GetLoginProfileResourceNamesAsync() { // Snippet: GetLoginProfileAsync(UserName, CallSettings) // Additional: GetLoginProfileAsync(UserName, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UserName name = UserName.FromUser("[USER]"); // Make the request LoginProfile response = await osLoginServiceClient.GetLoginProfileAsync(name); // End snippet } /// <summary>Snippet for GetSshPublicKey</summary> public void GetSshPublicKeyRequestObject() { // Snippet: GetSshPublicKey(GetSshPublicKeyRequest, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; // Make the request SshPublicKey response = osLoginServiceClient.GetSshPublicKey(request); // End snippet } /// <summary>Snippet for GetSshPublicKeyAsync</summary> public async Task GetSshPublicKeyRequestObjectAsync() { // Snippet: GetSshPublicKeyAsync(GetSshPublicKeyRequest, CallSettings) // Additional: GetSshPublicKeyAsync(GetSshPublicKeyRequest, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) GetSshPublicKeyRequest request = new GetSshPublicKeyRequest { SshPublicKeyName = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), }; // Make the request SshPublicKey response = await osLoginServiceClient.GetSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for GetSshPublicKey</summary> public void GetSshPublicKey() { // Snippet: GetSshPublicKey(string, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; // Make the request SshPublicKey response = osLoginServiceClient.GetSshPublicKey(name); // End snippet } /// <summary>Snippet for GetSshPublicKeyAsync</summary> public async Task GetSshPublicKeyAsync() { // Snippet: GetSshPublicKeyAsync(string, CallSettings) // Additional: GetSshPublicKeyAsync(string, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; // Make the request SshPublicKey response = await osLoginServiceClient.GetSshPublicKeyAsync(name); // End snippet } /// <summary>Snippet for GetSshPublicKey</summary> public void GetSshPublicKeyResourceNames() { // Snippet: GetSshPublicKey(SshPublicKeyName, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); // Make the request SshPublicKey response = osLoginServiceClient.GetSshPublicKey(name); // End snippet } /// <summary>Snippet for GetSshPublicKeyAsync</summary> public async Task GetSshPublicKeyResourceNamesAsync() { // Snippet: GetSshPublicKeyAsync(SshPublicKeyName, CallSettings) // Additional: GetSshPublicKeyAsync(SshPublicKeyName, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); // Make the request SshPublicKey response = await osLoginServiceClient.GetSshPublicKeyAsync(name); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKeyRequestObject() { // Snippet: ImportSshPublicKey(ImportSshPublicKeyRequest, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = UserName.FromUser("[USER]"), SshPublicKey = new SshPublicKey(), ProjectId = "", }; // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(request); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKeyRequestObjectAsync() { // Snippet: ImportSshPublicKeyAsync(ImportSshPublicKeyRequest, CallSettings) // Additional: ImportSshPublicKeyAsync(ImportSshPublicKeyRequest, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) ImportSshPublicKeyRequest request = new ImportSshPublicKeyRequest { ParentAsUserName = UserName.FromUser("[USER]"), SshPublicKey = new SshPublicKey(), ProjectId = "", }; // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey1() { // Snippet: ImportSshPublicKey(string, SshPublicKey, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string parent = "users/[USER]"; SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKey1Async() { // Snippet: ImportSshPublicKeyAsync(string, SshPublicKey, CallSettings) // Additional: ImportSshPublicKeyAsync(string, SshPublicKey, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "users/[USER]"; SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(parent, sshPublicKey); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey1ResourceNames() { // Snippet: ImportSshPublicKey(UserName, SshPublicKey, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName parent = UserName.FromUser("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKey1ResourceNamesAsync() { // Snippet: ImportSshPublicKeyAsync(UserName, SshPublicKey, CallSettings) // Additional: ImportSshPublicKeyAsync(UserName, SshPublicKey, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UserName parent = UserName.FromUser("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(parent, sshPublicKey); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey2() { // Snippet: ImportSshPublicKey(string, SshPublicKey, string, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string parent = "users/[USER]"; SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey, projectId); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKey2Async() { // Snippet: ImportSshPublicKeyAsync(string, SshPublicKey, string, CallSettings) // Additional: ImportSshPublicKeyAsync(string, SshPublicKey, string, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string parent = "users/[USER]"; SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(parent, sshPublicKey, projectId); // End snippet } /// <summary>Snippet for ImportSshPublicKey</summary> public void ImportSshPublicKey2ResourceNames() { // Snippet: ImportSshPublicKey(UserName, SshPublicKey, string, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UserName parent = UserName.FromUser("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = osLoginServiceClient.ImportSshPublicKey(parent, sshPublicKey, projectId); // End snippet } /// <summary>Snippet for ImportSshPublicKeyAsync</summary> public async Task ImportSshPublicKey2ResourceNamesAsync() { // Snippet: ImportSshPublicKeyAsync(UserName, SshPublicKey, string, CallSettings) // Additional: ImportSshPublicKeyAsync(UserName, SshPublicKey, string, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UserName parent = UserName.FromUser("[USER]"); SshPublicKey sshPublicKey = new SshPublicKey(); string projectId = ""; // Make the request ImportSshPublicKeyResponse response = await osLoginServiceClient.ImportSshPublicKeyAsync(parent, sshPublicKey, projectId); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKeyRequestObject() { // Snippet: UpdateSshPublicKey(UpdateSshPublicKeyRequest, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new SshPublicKey(), UpdateMask = new FieldMask(), }; // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(request); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKeyRequestObjectAsync() { // Snippet: UpdateSshPublicKeyAsync(UpdateSshPublicKeyRequest, CallSettings) // Additional: UpdateSshPublicKeyAsync(UpdateSshPublicKeyRequest, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) UpdateSshPublicKeyRequest request = new UpdateSshPublicKeyRequest { SshPublicKeyName = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"), SshPublicKey = new SshPublicKey(), UpdateMask = new FieldMask(), }; // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(request); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey1() { // Snippet: UpdateSshPublicKey(string, SshPublicKey, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(name, sshPublicKey); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKey1Async() { // Snippet: UpdateSshPublicKeyAsync(string, SshPublicKey, CallSettings) // Additional: UpdateSshPublicKeyAsync(string, SshPublicKey, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey1ResourceNames() { // Snippet: UpdateSshPublicKey(SshPublicKeyName, SshPublicKey, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(name, sshPublicKey); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKey1ResourceNamesAsync() { // Snippet: UpdateSshPublicKeyAsync(SshPublicKeyName, SshPublicKey, CallSettings) // Additional: UpdateSshPublicKeyAsync(SshPublicKeyName, SshPublicKey, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey2() { // Snippet: UpdateSshPublicKey(string, SshPublicKey, FieldMask, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(name, sshPublicKey, updateMask); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKey2Async() { // Snippet: UpdateSshPublicKeyAsync(string, SshPublicKey, FieldMask, CallSettings) // Additional: UpdateSshPublicKeyAsync(string, SshPublicKey, FieldMask, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) string name = "users/[USER]/sshPublicKeys/[FINGERPRINT]"; SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey, updateMask); // End snippet } /// <summary>Snippet for UpdateSshPublicKey</summary> public void UpdateSshPublicKey2ResourceNames() { // Snippet: UpdateSshPublicKey(SshPublicKeyName, SshPublicKey, FieldMask, CallSettings) // Create client OsLoginServiceClient osLoginServiceClient = OsLoginServiceClient.Create(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = osLoginServiceClient.UpdateSshPublicKey(name, sshPublicKey, updateMask); // End snippet } /// <summary>Snippet for UpdateSshPublicKeyAsync</summary> public async Task UpdateSshPublicKey2ResourceNamesAsync() { // Snippet: UpdateSshPublicKeyAsync(SshPublicKeyName, SshPublicKey, FieldMask, CallSettings) // Additional: UpdateSshPublicKeyAsync(SshPublicKeyName, SshPublicKey, FieldMask, CancellationToken) // Create client OsLoginServiceClient osLoginServiceClient = await OsLoginServiceClient.CreateAsync(); // Initialize request argument(s) SshPublicKeyName name = SshPublicKeyName.FromUserFingerprint("[USER]", "[FINGERPRINT]"); SshPublicKey sshPublicKey = new SshPublicKey(); FieldMask updateMask = new FieldMask(); // Make the request SshPublicKey response = await osLoginServiceClient.UpdateSshPublicKeyAsync(name, sshPublicKey, updateMask); // End snippet } } }
/* * Attributes.cs - Implementation of the "System.Xml.Private.Attributes" class. * * Copyright (C) 2004 Free Software Foundation, Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Xml.Private { using System; using System.Xml; using System.Collections; internal sealed class Attributes : XmlErrorProcessor { // Internal state. private int count; private ArrayList attributes; private Hashtable names; private XmlNameTable nt; private XmlNamespaceManager nm; // Constructor. public Attributes(ErrorHandler error) : base(error) { count = 0; nt = null; nm = null; attributes = new ArrayList(8); names = new Hashtable(new Key(null), new Key(null)); } // Get or set the count of attribute information nodes. public int Count { get { return count; } set { count = value; } } // Get the attribute information node at the given index. public AttributeInfo this[int index] { get { if(index >= attributes.Count) { attributes.Add(new AttributeInfo()); } return (AttributeInfo)attributes[index]; } } // Find the index of the attribute with the given name information. public int Find(String localName, String namespaceURI) { // create the search key Key key; if(nm == null && (namespaceURI == null || namespaceURI == "")) { key = new Key(nt.Get(localName)); } else { key = new Key(nt.Get(localName), nt.Get(namespaceURI)); } // perform the lookup and return the results Object val = names[key]; if(val == null) { return -1; } return (int)val; } public int Find(String name) { // create the search key Key key; if(nm == null) { key = new Key(nt.Get(name)); } else { int index = name.LastIndexOf(':'); if(index == 0) { return -1; } if(index > 0) { String prefix = nt.Get(name.Substring(0, index)); String localName = nt.Get(name.Substring(index + 1)); String namespaceURI = nm.LookupNamespace(prefix); key = new Key(localName, namespaceURI); } else { key = new Key(nt.Get(name), String.Empty); } } // perform the lookup and return the results Object val = names[key]; if(val == null) { return -1; } return (int)val; } // Reset the attribute information. public void Reset() { count = 0; names.Clear(); nt = null; nm = null; } // Update the search information. public void UpdateInfo(XmlNameTable nt) { this.nt = nt; this.nm = null; names.Clear(); for(int i = 0; i < count; ++i) { // get the attribute name information AttributeInfo info = (AttributeInfo)attributes[i]; String name = info.Name; // create the key Key key = new Key(name); // check for duplicate if(names.ContainsKey(key)) { Error(/* TODO */); } // add the key and index to the hash table names.Add(key, i); } } // Update the search and namespace information. public void UpdateInfo(XmlNameTable nt, XmlNamespaceManager nm) { this.nt = nt; this.nm = nm; names.Clear(); for(int i = 0; i < count; ++i) { // get the attribute name information AttributeInfo info = (AttributeInfo)attributes[i]; String name = info.Name; // set the defaults String localName = name; String prefix = String.Empty; String namespaceURI = String.Empty; // find the namespace separator int index = name.LastIndexOf(':'); // give an error if there's no name before the separator if(index == 0) { Error(/* TODO */); } // set the namespace information if(index > 0) { // add the prefix and local name to the name table prefix = nt.Add(name.Substring(0, index)); localName = nt.Add(name.Substring(index + 1)); // check for a valid prefix if(prefix.IndexOf(':') != -1) { Error(/* TODO */); } // set the namespace uri based on the prefix namespaceURI = nm.LookupNamespace(prefix); } else if(localName == "xmlns") { namespaceURI = nt.Add(XmlDocument.xmlns); } // create the key Key key = new Key(localName, namespaceURI); // check for duplicate if(names.ContainsKey(key)) { Error(/* TODO */); } // add the key and index to the hash table names.Add(key, i); // update the current attribute's namespace information info.UpdateNamespaceInfo(localName, namespaceURI, prefix); } } private struct Key : IComparer, IHashCodeProvider { // Publicly-accessible state. public Object localName; public Object namespaceURI; // Constructors. public Key(String localName, String namespaceURI) { this.localName = localName; this.namespaceURI = namespaceURI; } public Key(String name) { this.localName = name; this.namespaceURI = null; } // Explicit IComparer implementation. int IComparer.Compare(Object x, Object y) { if((x is Key) && (y is Key)) { Key one = (Key)x; Key two = (Key)y; if((one.localName == two.localName) && (one.namespaceURI == two.namespaceURI)) { return 0; } } return 1; } // Explicit IHashCodeProvider implementation. int IHashCodeProvider.GetHashCode(Object obj) { if(!(obj is Key)) { return 0; } Key k = (Key)obj; String ln = (String)k.localName; String ns = (String)k.namespaceURI; if(ln == null) { return 0; } int hash = ln.GetHashCode(); if(ns != null) { hash = (hash << 16) + ns.GetHashCode(); } return hash; } }; // class Key }; // class Attributes }; // namespace System.Xml.Private
// <copyright file="HttpCommandExecutor.cs" company="WebDriver Committers"> // Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC licenses this file // to you under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using OpenQA.Selenium.Internal; namespace OpenQA.Selenium.Remote { /// <summary> /// Provides a way of executing Commands over HTTP /// </summary> public class HttpCommandExecutor : ICommandExecutor { private const string JsonMimeType = "application/json"; private const string PngMimeType = "image/png"; private const string Utf8CharsetType = "utf-8"; private const string RequestAcceptHeader = JsonMimeType + ", " + PngMimeType; private const string RequestContentTypeHeader = JsonMimeType + "; charset=" + Utf8CharsetType; private const string UserAgentHeaderTemplate = "selenium/{0} (.net {1})"; private Uri remoteServerUri; private TimeSpan serverResponseTimeout; private bool enableKeepAlive; private bool isDisposed; private IWebProxy proxy; private CommandInfoRepository commandInfoRepository = new W3CWireProtocolCommandInfoRepository(); private HttpClient client; /// <summary> /// Initializes a new instance of the <see cref="HttpCommandExecutor"/> class /// </summary> /// <param name="addressOfRemoteServer">Address of the WebDriver Server</param> /// <param name="timeout">The timeout within which the server must respond.</param> public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout) : this(addressOfRemoteServer, timeout, true) { } /// <summary> /// Initializes a new instance of the <see cref="HttpCommandExecutor"/> class /// </summary> /// <param name="addressOfRemoteServer">Address of the WebDriver Server</param> /// <param name="timeout">The timeout within which the server must respond.</param> /// <param name="enableKeepAlive"><see langword="true"/> if the KeepAlive header should be sent /// with HTTP requests; otherwise, <see langword="false"/>.</param> public HttpCommandExecutor(Uri addressOfRemoteServer, TimeSpan timeout, bool enableKeepAlive) { if (addressOfRemoteServer == null) { throw new ArgumentNullException("addressOfRemoteServer", "You must specify a remote address to connect to"); } if (!addressOfRemoteServer.AbsoluteUri.EndsWith("/", StringComparison.OrdinalIgnoreCase)) { addressOfRemoteServer = new Uri(addressOfRemoteServer.ToString() + "/"); } this.remoteServerUri = addressOfRemoteServer; this.serverResponseTimeout = timeout; this.enableKeepAlive = enableKeepAlive; } /// <summary> /// Occurs when the <see cref="HttpCommandExecutor"/> is sending an HTTP /// request to the remote end WebDriver implementation. /// </summary> public event EventHandler<SendingRemoteHttpRequestEventArgs> SendingRemoteHttpRequest; /// <summary> /// Gets the repository of objects containin information about commands. /// </summary> public CommandInfoRepository CommandInfoRepository { get { return this.commandInfoRepository; } protected set { this.commandInfoRepository = value; } } /// <summary> /// Gets or sets an <see cref="IWebProxy"/> object to be used to proxy requests /// between this <see cref="HttpCommandExecutor"/> and the remote end WebDriver /// implementation. /// </summary> public IWebProxy Proxy { get { return this.proxy; } set { this.proxy = value; } } /// <summary> /// Gets or sets a value indicating whether keep-alive is enabled for HTTP /// communication between this <see cref="HttpCommandExecutor"/> and the /// remote end WebDriver implementation. /// </summary> public bool IsKeepAliveEnabled { get { return this.enableKeepAlive; } set { this.enableKeepAlive = value; } } /// <summary> /// Executes a command /// </summary> /// <param name="commandToExecute">The command you wish to execute</param> /// <returns>A response from the browser</returns> public virtual Response Execute(Command commandToExecute) { if (commandToExecute == null) { throw new ArgumentNullException("commandToExecute", "commandToExecute cannot be null"); } CommandInfo info = this.commandInfoRepository.GetCommandInfo(commandToExecute.Name); if (info == null) { throw new NotImplementedException(string.Format("The command you are attempting to execute, {0}, does not exist in the protocol dialect used by the remote end.", commandToExecute.Name)); } if (this.client == null) { this.CreateHttpClient(); } HttpRequestInfo requestInfo = new HttpRequestInfo(this.remoteServerUri, commandToExecute, info); HttpResponseInfo responseInfo = null; try { // Use TaskFactory to avoid deadlock in multithreaded implementations. responseInfo = new TaskFactory(CancellationToken.None, TaskCreationOptions.None, TaskContinuationOptions.None, TaskScheduler.Default) .StartNew(() => this.MakeHttpRequest(requestInfo)) .Unwrap() .GetAwaiter() .GetResult(); } catch (HttpRequestException ex) { WebException innerWebException = ex.InnerException as WebException; if (innerWebException != null) { if (innerWebException.Status == WebExceptionStatus.Timeout) { string timeoutMessage = "The HTTP request to the remote WebDriver server for URL {0} timed out after {1} seconds."; throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, timeoutMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex); } else if (innerWebException.Status == WebExceptionStatus.ConnectFailure) { string connectFailureMessage = "Could not connect to the remote WebDriver server for URL {0}."; throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, connectFailureMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex); } else if (innerWebException.Response == null) { string nullResponseMessage = "A exception with a null response was thrown sending an HTTP request to the remote WebDriver server for URL {0}. The status of the exception was {1}, and the message was: {2}"; throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, nullResponseMessage, requestInfo.FullUri.AbsoluteUri, innerWebException.Status, innerWebException.Message), innerWebException); } } string unknownErrorMessage = "An unknown exception was encountered sending an HTTP request to the remote WebDriver server for URL {0}. The exception message was: {1}"; throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, unknownErrorMessage, requestInfo.FullUri.AbsoluteUri, ex.Message), ex); } catch(TaskCanceledException ex) { string timeoutMessage = "The HTTP request to the remote WebDriver server for URL {0} timed out after {1} seconds."; throw new WebDriverException(string.Format(CultureInfo.InvariantCulture, timeoutMessage, requestInfo.FullUri.AbsoluteUri, this.serverResponseTimeout.TotalSeconds), ex); } Response toReturn = this.CreateResponse(responseInfo); return toReturn; } /// <summary> /// Raises the <see cref="SendingRemoteHttpRequest"/> event. /// </summary> /// <param name="eventArgs">A <see cref="SendingRemoteHttpRequestEventArgs"/> that contains the event data.</param> protected virtual void OnSendingRemoteHttpRequest(SendingRemoteHttpRequestEventArgs eventArgs) { if (eventArgs == null) { throw new ArgumentNullException("eventArgs", "eventArgs must not be null"); } if (this.SendingRemoteHttpRequest != null) { this.SendingRemoteHttpRequest(this, eventArgs); } } private void CreateHttpClient() { HttpClientHandler httpClientHandler = new HttpClientHandler(); string userInfo = this.remoteServerUri.UserInfo; if (!string.IsNullOrEmpty(userInfo) && userInfo.Contains(":")) { string[] userInfoComponents = this.remoteServerUri.UserInfo.Split(new char[] { ':' }, 2); httpClientHandler.Credentials = new NetworkCredential(userInfoComponents[0], userInfoComponents[1]); httpClientHandler.PreAuthenticate = true; } httpClientHandler.Proxy = this.Proxy; // httpClientHandler.MaxConnectionsPerServer = 2000; this.client = new HttpClient(httpClientHandler); string userAgentString = string.Format(CultureInfo.InvariantCulture, UserAgentHeaderTemplate, ResourceUtilities.AssemblyVersion, ResourceUtilities.PlatformFamily); this.client.DefaultRequestHeaders.UserAgent.ParseAdd(userAgentString); this.client.DefaultRequestHeaders.Accept.ParseAdd(RequestAcceptHeader); if (!this.IsKeepAliveEnabled) { this.client.DefaultRequestHeaders.Connection.ParseAdd("close"); } this.client.Timeout = this.serverResponseTimeout; } private async Task<HttpResponseInfo> MakeHttpRequest(HttpRequestInfo requestInfo) { SendingRemoteHttpRequestEventArgs eventArgs = new SendingRemoteHttpRequestEventArgs(null, requestInfo.RequestBody); this.OnSendingRemoteHttpRequest(eventArgs); HttpMethod method = new HttpMethod(requestInfo.HttpMethod); HttpRequestMessage requestMessage = new HttpRequestMessage(method, requestInfo.FullUri); if (requestInfo.HttpMethod == CommandInfo.GetCommand) { CacheControlHeaderValue cacheControlHeader = new CacheControlHeaderValue(); cacheControlHeader.NoCache = true; requestMessage.Headers.CacheControl = cacheControlHeader; } if (requestInfo.HttpMethod == CommandInfo.PostCommand) { MediaTypeWithQualityHeaderValue acceptHeader = new MediaTypeWithQualityHeaderValue(JsonMimeType); acceptHeader.CharSet = Utf8CharsetType; requestMessage.Headers.Accept.Add(acceptHeader); byte[] bytes = Encoding.UTF8.GetBytes(eventArgs.RequestBody); requestMessage.Content = new ByteArrayContent(bytes, 0, bytes.Length); MediaTypeHeaderValue contentTypeHeader = new MediaTypeHeaderValue(JsonMimeType); contentTypeHeader.CharSet = Utf8CharsetType; requestMessage.Content.Headers.ContentType = contentTypeHeader; } HttpResponseMessage responseMessage = await this.client.SendAsync(requestMessage); HttpResponseInfo httpResponseInfo = new HttpResponseInfo(); httpResponseInfo.Body = await responseMessage.Content.ReadAsStringAsync(); httpResponseInfo.ContentType = responseMessage.Content.Headers.ContentType.ToString(); httpResponseInfo.StatusCode = responseMessage.StatusCode; return httpResponseInfo; } private Response CreateResponse(HttpResponseInfo responseInfo) { Response response = new Response(); string body = responseInfo.Body; if (responseInfo.ContentType != null && responseInfo.ContentType.StartsWith("application/json", StringComparison.OrdinalIgnoreCase)) { response = Response.FromJson(body); } else { response.Value = body; } if (this.CommandInfoRepository.SpecificationLevel < 1 && (responseInfo.StatusCode < HttpStatusCode.OK || responseInfo.StatusCode >= HttpStatusCode.BadRequest)) { if (responseInfo.StatusCode >= HttpStatusCode.BadRequest && responseInfo.StatusCode < HttpStatusCode.InternalServerError) { response.Status = WebDriverResult.UnhandledError; } else if (responseInfo.StatusCode >= HttpStatusCode.InternalServerError) { if (responseInfo.StatusCode == HttpStatusCode.NotImplemented) { response.Status = WebDriverResult.UnknownCommand; } else if (response.Status == WebDriverResult.Success) { response.Status = WebDriverResult.UnhandledError; } } else { response.Status = WebDriverResult.UnhandledError; } } if (response.Value is string) { response.Value = ((string)response.Value).Replace("\r\n", "\n").Replace("\n", Environment.NewLine); } return response; } /// <summary> /// Releases all resources used by the <see cref="HttpCommandExecutor"/>. /// </summary> public void Dispose() { this.Dispose(true); } /// <summary> /// Releases the unmanaged resources used by the <see cref="HttpCommandExecutor"/> and /// optionally releases the managed resources. /// </summary> /// <param name="disposing"><see langword="true"/> to release managed and resources; /// <see langword="false"/> to only release unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (!this.isDisposed) { if (this.client != null) { this.client.Dispose(); } this.isDisposed = true; } } private class HttpRequestInfo { public HttpRequestInfo(Uri serverUri, Command commandToExecute, CommandInfo commandInfo) { this.FullUri = commandInfo.CreateCommandUri(serverUri, commandToExecute); this.HttpMethod = commandInfo.Method; this.RequestBody = commandToExecute.ParametersAsJsonString; } public Uri FullUri { get; set; } public string HttpMethod { get; set; } public string RequestBody { get; set; } } private class HttpResponseInfo { public HttpStatusCode StatusCode { get; set; } public string Body { get; set; } public string ContentType { get; set; } } } }
//------------------------------------------------------------------------------ // <copyright file="SqlDataReader.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System; using System.Data; using System.Data.Sql; using System.Data.SqlTypes; using System.IO; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics; // for Conditional compilation using System.Diagnostics.CodeAnalysis; using System.Xml; using Microsoft.SqlServer.Server; using System.Data.ProviderBase; using System.Data.Common; using System.Threading.Tasks; // SqlServer provider's implementation of ISqlReader. // Supports ISqlReader and ISqlResultSet objects. // // User should never be able to create one of these themselves, nor subclass. // This is accomplished by having no public override constructors. internal sealed class SqlDataReaderSmi : SqlDataReader { // // IDBRecord properties // public override int FieldCount { get { ThrowIfClosed( "FieldCount" ); return InternalFieldCount; } } public override int VisibleFieldCount { get { ThrowIfClosed("VisibleFieldCount"); if (FNotInResults()) { return 0; } return _visibleColumnCount; } } // // IDBRecord Metadata Methods // public override String GetName(int ordinal) { EnsureCanGetMetaData( "GetName" ); return _currentMetaData[ordinal].Name; } public override String GetDataTypeName(int ordinal) { EnsureCanGetMetaData( "GetDataTypeName" ); SmiExtendedMetaData md = _currentMetaData[ordinal]; if ( SqlDbType.Udt == md.SqlDbType ) { return md.TypeSpecificNamePart1 + "." + md.TypeSpecificNamePart2 + "." + md.TypeSpecificNamePart3; } else { return md.TypeName; } } public override Type GetFieldType(int ordinal) { EnsureCanGetMetaData( "GetFieldType" ); if (SqlDbType.Udt == _currentMetaData[ordinal].SqlDbType) { return _currentMetaData[ordinal].Type; } else { return MetaType.GetMetaTypeFromSqlDbType( _currentMetaData[ordinal].SqlDbType, _currentMetaData[ordinal].IsMultiValued).ClassType ; } } override public Type GetProviderSpecificFieldType(int ordinal) { EnsureCanGetMetaData( "GetProviderSpecificFieldType" ); if (SqlDbType.Udt == _currentMetaData[ordinal].SqlDbType) { return _currentMetaData[ordinal].Type; } else { return MetaType.GetMetaTypeFromSqlDbType( _currentMetaData[ordinal].SqlDbType, _currentMetaData[ordinal].IsMultiValued).SqlType ; } } public override int Depth { get{ ThrowIfClosed( "Depth" ); return 0; } } // public override Object GetValue(int ordinal) { EnsureCanGetCol( "GetValue", ordinal); SmiQueryMetaData metaData = _currentMetaData[ordinal]; if (_currentConnection.IsKatmaiOrNewer) { return ValueUtilsSmi.GetValue200(_readerEventSink, (SmiTypedGetterSetter)_currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } else { return ValueUtilsSmi.GetValue(_readerEventSink, _currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } } public override T GetFieldValue<T>(int ordinal) { EnsureCanGetCol( "GetFieldValue<T>", ordinal); SmiQueryMetaData metaData = _currentMetaData[ordinal]; if (_typeofINullable.IsAssignableFrom(typeof(T))) { // If its a SQL Type or Nullable UDT if (_currentConnection.IsKatmaiOrNewer) { return (T)ValueUtilsSmi.GetSqlValue200(_readerEventSink, (SmiTypedGetterSetter)_currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } else { return (T)ValueUtilsSmi.GetSqlValue(_readerEventSink, _currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } } else { // Otherwise Its a CLR or non-Nullable UDT if (_currentConnection.IsKatmaiOrNewer) { return (T)ValueUtilsSmi.GetValue200(_readerEventSink, (SmiTypedGetterSetter)_currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } else { return (T)ValueUtilsSmi.GetValue(_readerEventSink, _currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } } } public override Task<T> GetFieldValueAsync<T>(int ordinal, CancellationToken cancellationToken) { // As per Async spec, Context Connections do not support async return ADP.CreatedTaskWithException<T>(ADP.ExceptionWithStackTrace(SQL.NotAvailableOnContextConnection())); } override internal SqlBuffer.StorageType GetVariantInternalStorageType(int ordinal) { Debug.Assert(null != _currentColumnValuesV3, "Attempting to get variant internal storage type without calling GetValue first"); if (IsDBNull(ordinal)) return SqlBuffer.StorageType.Empty; SmiMetaData valueMetaData = _currentColumnValuesV3.GetVariantType(_readerEventSink, ordinal); if (valueMetaData == null) return SqlBuffer.StorageType.Empty; else return ValueUtilsSmi.SqlDbTypeToStorageType(valueMetaData.SqlDbType); } public override int GetValues(object[] values) { EnsureCanGetCol( "GetValues", 0); if (null == values) { throw ADP.ArgumentNull("values"); } int copyLength = (values.Length < _visibleColumnCount) ? values.Length : _visibleColumnCount; for(int i=0; i<copyLength; i++) { values[_indexMap[i]] = GetValue(i); } return copyLength; } public override int GetOrdinal(string name) { EnsureCanGetMetaData( "GetOrdinal" ); if (null == _fieldNameLookup) { _fieldNameLookup = new FieldNameLookup( (IDataReader) this, -1 ); // } return _fieldNameLookup.GetOrdinal(name); // MDAC 71470 } // Generic array access by column index (accesses column value) public override object this[int ordinal] { get { return GetValue( ordinal ); } } // Generic array access by column name (accesses column value) public override object this[string strName] { get { return GetValue( GetOrdinal( strName ) ); } } // // IDataRecord Data Access methods // public override bool IsDBNull(int ordinal) { EnsureCanGetCol( "IsDBNull", ordinal); return ValueUtilsSmi.IsDBNull(_readerEventSink, _currentColumnValuesV3, ordinal); } public override Task<bool> IsDBNullAsync(int ordinal, CancellationToken cancellationToken) { // As per Async spec, Context Connections do not support async return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(SQL.NotAvailableOnContextConnection())); } public override bool GetBoolean(int ordinal) { EnsureCanGetCol( "GetBoolean", ordinal); return ValueUtilsSmi.GetBoolean(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override byte GetByte(int ordinal) { EnsureCanGetCol( "GetByte", ordinal); return ValueUtilsSmi.GetByte(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override long GetBytes(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { EnsureCanGetCol( "GetBytes", ordinal); return ValueUtilsSmi.GetBytes(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], fieldOffset, buffer, bufferOffset, length, true); } // XmlReader support code calls this method. internal override long GetBytesInternal(int ordinal, long fieldOffset, byte[] buffer, int bufferOffset, int length) { EnsureCanGetCol( "GetBytes", ordinal); return ValueUtilsSmi.GetBytesInternal(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], fieldOffset, buffer, bufferOffset, length, false); } public override char GetChar(int ordinal) { throw ADP.NotSupported(); } public override long GetChars(int ordinal, long fieldOffset, char[] buffer, int bufferOffset, int length) { EnsureCanGetCol( "GetChars", ordinal); SmiExtendedMetaData metaData = _currentMetaData[ordinal]; if (IsCommandBehavior(CommandBehavior.SequentialAccess)) { if (metaData.SqlDbType == SqlDbType.Xml) { return GetStreamingXmlChars(ordinal, fieldOffset, buffer, bufferOffset, length); } } return ValueUtilsSmi.GetChars(_readerEventSink, _currentColumnValuesV3, ordinal, metaData, fieldOffset, buffer, bufferOffset, length); } public override Guid GetGuid(int ordinal) { EnsureCanGetCol( "GetGuid", ordinal); return ValueUtilsSmi.GetGuid(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override Int16 GetInt16(int ordinal) { EnsureCanGetCol( "GetInt16", ordinal); return ValueUtilsSmi.GetInt16(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override Int32 GetInt32(int ordinal) { EnsureCanGetCol( "GetInt32", ordinal); return ValueUtilsSmi.GetInt32(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override Int64 GetInt64(int ordinal) { EnsureCanGetCol( "GetInt64", ordinal); return ValueUtilsSmi.GetInt64(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override Single GetFloat(int ordinal) { EnsureCanGetCol( "GetFloat", ordinal); return ValueUtilsSmi.GetSingle(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override Double GetDouble(int ordinal) { EnsureCanGetCol( "GetDouble", ordinal); return ValueUtilsSmi.GetDouble(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override String GetString(int ordinal) { EnsureCanGetCol( "GetString", ordinal); return ValueUtilsSmi.GetString(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override Decimal GetDecimal(int ordinal) { EnsureCanGetCol( "GetDecimal", ordinal); return ValueUtilsSmi.GetDecimal(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override DateTime GetDateTime(int ordinal) { EnsureCanGetCol( "GetDateTime", ordinal); return ValueUtilsSmi.GetDateTime(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } // // IDataReader properties // // Logically closed test. I.e. is this object closed as far as external access is concerned? public override bool IsClosed { get { return IsReallyClosed(); } } public override int RecordsAffected { get { return base.Command.InternalRecordsAffected; } } // // IDataReader methods // internal override void CloseReaderFromConnection() { // Context Connections do not support async - so there is no threading issues with closing from the connection CloseInternal(closeConnection: false); } public override void Close() { // Connection should be open at this point, so we can do multiple checks of HasEvents, and we may need to close the connection afterwards CloseInternal(closeConnection: IsCommandBehavior(CommandBehavior.CloseConnection)); } private void CloseInternal(bool closeConnection) { IntPtr hscp; Bid.ScopeEnter(out hscp, "<sc.SqlDataReaderSmi.Close|API> %d#", ObjectID); bool processFinallyBlock = true; try { if(!IsClosed) { _hasRows = false; // Process the remaining events. This makes sure that environment changes are applied and any errors are picked up. while(_eventStream.HasEvents) { _eventStream.ProcessEvent( _readerEventSink ); _readerEventSink.ProcessMessagesAndThrow(true); } // Close the request executor _requestExecutor.Close(_readerEventSink); _readerEventSink.ProcessMessagesAndThrow(true); } } catch (Exception e) { processFinallyBlock = ADP.IsCatchableExceptionType(e); throw; } finally { if (processFinallyBlock) { _isOpen = false; if ((closeConnection) && (Connection != null)) { Connection.Close(); } Bid.ScopeLeave(ref hscp); } } } // Move to the next resultset public override unsafe bool NextResult() { ThrowIfClosed( "NextResult" ); bool hasAnotherResult = InternalNextResult(false); return hasAnotherResult; } public override Task<bool> NextResultAsync(CancellationToken cancellationToken) { // Async not supported on Context Connections return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(SQL.NotAvailableOnContextConnection())); } internal unsafe bool InternalNextResult(bool ignoreNonFatalMessages) { IntPtr hscp = IntPtr.Zero; if (Bid.AdvancedOn) { Bid.ScopeEnter(out hscp, "<sc.SqlDataReaderSmi.InternalNextResult|ADV> %d#", ObjectID); } try { _hasRows = false; if( PositionState.AfterResults != _currentPosition ) { // Consume any remaning rows in the current result. while( InternalRead(ignoreNonFatalMessages) ) { // This space intentionally left blank } // reset resultset metadata - it will be created again if there is a pending resultset ResetResultSet(); // Process the events until metadata is found or all of the // available events have been consumed. If there is another // result, the metadata for it will be available after the last // read on the prior result. while(null == _currentMetaData && _eventStream.HasEvents) { _eventStream.ProcessEvent( _readerEventSink ); _readerEventSink.ProcessMessagesAndThrow(ignoreNonFatalMessages); } } return PositionState.AfterResults != _currentPosition; } finally { if (Bid.AdvancedOn) { Bid.ScopeLeave(ref hscp); } } } public override bool Read() { ThrowIfClosed( "Read" ); bool hasAnotherRow = InternalRead(false); return hasAnotherRow; } public override Task<bool> ReadAsync(CancellationToken cancellationToken) { // Async not supported on Context Connections return ADP.CreatedTaskWithException<bool>(ADP.ExceptionWithStackTrace(SQL.NotAvailableOnContextConnection())); } internal unsafe bool InternalRead(bool ignoreNonFatalErrors) { IntPtr hscp = IntPtr.Zero; if (Bid.AdvancedOn) { Bid.ScopeEnter(out hscp, "<sc.SqlDataReaderSmi.InternalRead|ADV> %d#", ObjectID); } try { // Don't move unless currently in results. if( FInResults() ) { // Set current row to null so we can see if we get a new one _currentColumnValues = null; _currentColumnValuesV3 = null; // Reset blobs if (_currentStream != null) { _currentStream.SetClosed(); _currentStream = null; } if (_currentTextReader != null) { _currentTextReader.SetClosed(); _currentTextReader = null; } // NOTE: SQLBUDT #386118 -- may indicate that we want to break this loop when we get a MessagePosted callback, but we can't prove that. while( null == _currentColumnValues && // Did we find a row? null == _currentColumnValuesV3 && // Did we find a V3 row? FInResults() && // Was the batch terminated due to a serious error? PositionState.AfterRows != _currentPosition && // Have we seen a statement completed event? _eventStream.HasEvents ) { // Have we processed all events? _eventStream.ProcessEvent( _readerEventSink ); _readerEventSink.ProcessMessagesAndThrow(ignoreNonFatalErrors); } } return PositionState.OnRow == _currentPosition; } finally { if (Bid.AdvancedOn) { Bid.ScopeLeave(ref hscp); } } } public override DataTable GetSchemaTable() { ThrowIfClosed( "GetSchemaTable" ); if ( null == _schemaTable && FInResults() ) { DataTable schemaTable = new DataTable( "SchemaTable" ); schemaTable.Locale = System.Globalization.CultureInfo.InvariantCulture; schemaTable.MinimumCapacity = InternalFieldCount; DataColumn ColumnName = new DataColumn(SchemaTableColumn.ColumnName, typeof(System.String)); DataColumn Ordinal = new DataColumn(SchemaTableColumn.ColumnOrdinal, typeof(System.Int32)); DataColumn Size = new DataColumn(SchemaTableColumn.ColumnSize, typeof(System.Int32)); DataColumn Precision = new DataColumn(SchemaTableColumn.NumericPrecision, typeof(System.Int16)); DataColumn Scale = new DataColumn(SchemaTableColumn.NumericScale, typeof(System.Int16)); DataColumn DataType = new DataColumn(SchemaTableColumn.DataType, typeof(System.Type)); DataColumn ProviderSpecificDataType = new DataColumn(SchemaTableOptionalColumn.ProviderSpecificDataType, typeof(System.Type)); DataColumn ProviderType = new DataColumn(SchemaTableColumn.ProviderType, typeof(System.Int32)); DataColumn NonVersionedProviderType = new DataColumn(SchemaTableColumn.NonVersionedProviderType, typeof(System.Int32)); DataColumn IsLong = new DataColumn(SchemaTableColumn.IsLong, typeof(System.Boolean)); DataColumn AllowDBNull = new DataColumn(SchemaTableColumn.AllowDBNull, typeof(System.Boolean)); DataColumn IsReadOnly = new DataColumn(SchemaTableOptionalColumn.IsReadOnly, typeof(System.Boolean)); DataColumn IsRowVersion = new DataColumn(SchemaTableOptionalColumn.IsRowVersion, typeof(System.Boolean)); DataColumn IsUnique = new DataColumn(SchemaTableColumn.IsUnique, typeof(System.Boolean)); DataColumn IsKey = new DataColumn(SchemaTableColumn.IsKey, typeof(System.Boolean)); DataColumn IsAutoIncrement = new DataColumn(SchemaTableOptionalColumn.IsAutoIncrement, typeof(System.Boolean)); DataColumn IsHidden = new DataColumn(SchemaTableOptionalColumn.IsHidden, typeof(System.Boolean)); DataColumn BaseCatalogName = new DataColumn(SchemaTableOptionalColumn.BaseCatalogName, typeof(System.String)); DataColumn BaseSchemaName = new DataColumn(SchemaTableColumn.BaseSchemaName, typeof(System.String)); DataColumn BaseTableName = new DataColumn(SchemaTableColumn.BaseTableName, typeof(System.String)); DataColumn BaseColumnName = new DataColumn(SchemaTableColumn.BaseColumnName, typeof(System.String)); // unique to SqlClient DataColumn BaseServerName = new DataColumn(SchemaTableOptionalColumn.BaseServerName, typeof(System.String)); DataColumn IsAliased = new DataColumn(SchemaTableColumn.IsAliased, typeof(System.Boolean)); DataColumn IsExpression = new DataColumn(SchemaTableColumn.IsExpression, typeof(System.Boolean)); DataColumn IsIdentity = new DataColumn("IsIdentity", typeof(System.Boolean)); // UDT specific. Holds UDT typename ONLY if the type of the column is UDT, otherwise the data type DataColumn DataTypeName = new DataColumn("DataTypeName", typeof(System.String)); DataColumn UdtAssemblyQualifiedName = new DataColumn("UdtAssemblyQualifiedName", typeof(System.String)); // Xml metadata specific DataColumn XmlSchemaCollectionDatabase = new DataColumn("XmlSchemaCollectionDatabase", typeof(System.String)); DataColumn XmlSchemaCollectionOwningSchema = new DataColumn("XmlSchemaCollectionOwningSchema", typeof(System.String)); DataColumn XmlSchemaCollectionName = new DataColumn("XmlSchemaCollectionName", typeof(System.String)); // SparseColumnSet DataColumn IsColumnSet = new DataColumn("IsColumnSet", typeof(System.Boolean)); Ordinal.DefaultValue = 0; IsLong.DefaultValue = false; DataColumnCollection columns = schemaTable.Columns; // must maintain order for backward compatibility columns.Add(ColumnName); columns.Add(Ordinal); columns.Add(Size); columns.Add(Precision); columns.Add(Scale); columns.Add(IsUnique); columns.Add(IsKey); columns.Add(BaseServerName); columns.Add(BaseCatalogName); columns.Add(BaseColumnName); columns.Add(BaseSchemaName); columns.Add(BaseTableName); columns.Add(DataType); columns.Add(AllowDBNull); columns.Add(ProviderType); columns.Add(IsAliased); columns.Add(IsExpression); columns.Add(IsIdentity); columns.Add(IsAutoIncrement); columns.Add(IsRowVersion); columns.Add(IsHidden); columns.Add(IsLong); columns.Add(IsReadOnly); columns.Add(ProviderSpecificDataType); columns.Add(DataTypeName); columns.Add(XmlSchemaCollectionDatabase); columns.Add(XmlSchemaCollectionOwningSchema); columns.Add(XmlSchemaCollectionName); columns.Add(UdtAssemblyQualifiedName); columns.Add(NonVersionedProviderType); columns.Add(IsColumnSet); for (int i = 0; i < InternalFieldCount; i++) { SmiQueryMetaData colMetaData = _currentMetaData[i]; long maxLength = colMetaData.MaxLength; MetaType metaType = MetaType.GetMetaTypeFromSqlDbType(colMetaData.SqlDbType, colMetaData.IsMultiValued); if ( SmiMetaData.UnlimitedMaxLengthIndicator == maxLength ) { metaType = MetaType.GetMaxMetaTypeFromMetaType( metaType ); maxLength = (metaType.IsSizeInCharacters && !metaType.IsPlp) ? (0x7fffffff / 2) : 0x7fffffff; } DataRow schemaRow = schemaTable.NewRow(); // NOTE: there is an impedence mismatch here - the server always // treats numeric data as variable length and sends a maxLength // based upon the precision, whereas TDS always sends 17 for // the max length; rather than push this logic into the server, // I've elected to make a fixup here instead. if (SqlDbType.Decimal == colMetaData.SqlDbType) { // maxLength = TdsEnums.MAX_NUMERIC_LEN; // SQLBUDT 339686 } else if (SqlDbType.Variant == colMetaData.SqlDbType) { // maxLength = 8009; // SQLBUDT 340726 } schemaRow[ColumnName] = colMetaData.Name; schemaRow[Ordinal] = i; schemaRow[Size] = maxLength; schemaRow[ProviderType] = (int) colMetaData.SqlDbType; // SqlDbType schemaRow[NonVersionedProviderType] = (int) colMetaData.SqlDbType; // SqlDbType if (colMetaData.SqlDbType != SqlDbType.Udt) { schemaRow[DataType] = metaType.ClassType; // com+ type schemaRow[ProviderSpecificDataType] = metaType.SqlType; } else { schemaRow[UdtAssemblyQualifiedName] = colMetaData.Type.AssemblyQualifiedName; schemaRow[DataType] = colMetaData.Type; schemaRow[ProviderSpecificDataType] = colMetaData.Type; } // NOTE: there is also an impedence mismatch here - the server // has different ideas about what the precision value should be // than does the client bits. I tried fixing up the default // meta data values in SmiMetaData, however, it caused the // server suites to fall over dead. Rather than attempt to // bake it into the server, I'm fixing it up in the client. byte precision = 0xff; // default for everything, except certain numeric types. // switch (colMetaData.SqlDbType) { case SqlDbType.BigInt: case SqlDbType.DateTime: case SqlDbType.Decimal: case SqlDbType.Int: case SqlDbType.Money: case SqlDbType.SmallDateTime: case SqlDbType.SmallInt: case SqlDbType.SmallMoney: case SqlDbType.TinyInt: precision = colMetaData.Precision; break; case SqlDbType.Float: precision = 15; break; case SqlDbType.Real: precision = 7; break; default: precision = 0xff; // everything else is unknown; break; } schemaRow[Precision] = precision; // if ( SqlDbType.Decimal == colMetaData.SqlDbType || SqlDbType.Time == colMetaData.SqlDbType || SqlDbType.DateTime2 == colMetaData.SqlDbType || SqlDbType.DateTimeOffset == colMetaData.SqlDbType) { schemaRow[Scale] = colMetaData.Scale; } else { schemaRow[Scale] = MetaType.GetMetaTypeFromSqlDbType( colMetaData.SqlDbType, colMetaData.IsMultiValued).Scale; } schemaRow[AllowDBNull] = colMetaData.AllowsDBNull; if ( !( colMetaData.IsAliased.IsNull ) ) { schemaRow[IsAliased] = colMetaData.IsAliased.Value; } if ( !( colMetaData.IsKey.IsNull ) ) { schemaRow[IsKey] = colMetaData.IsKey.Value; } if ( !( colMetaData.IsHidden.IsNull ) ) { schemaRow[IsHidden] = colMetaData.IsHidden.Value; } if ( !( colMetaData.IsExpression.IsNull ) ) { schemaRow[IsExpression] = colMetaData.IsExpression.Value; } schemaRow[IsReadOnly] = colMetaData.IsReadOnly; schemaRow[IsIdentity] = colMetaData.IsIdentity; schemaRow[IsColumnSet] = colMetaData.IsColumnSet; schemaRow[IsAutoIncrement] = colMetaData.IsIdentity; schemaRow[IsLong] = metaType.IsLong; // mark unique for timestamp columns if ( SqlDbType.Timestamp == colMetaData.SqlDbType ) { schemaRow[IsUnique] = true; schemaRow[IsRowVersion] = true; } else { schemaRow[IsUnique] = false; schemaRow[IsRowVersion] = false; } if ( !ADP.IsEmpty( colMetaData.ColumnName ) ) { schemaRow[BaseColumnName] = colMetaData.ColumnName; } else if (!ADP.IsEmpty( colMetaData.Name)) { // Use projection name if base column name is not present schemaRow[BaseColumnName] = colMetaData.Name; } if ( !ADP.IsEmpty(colMetaData.TableName ) ) { schemaRow[BaseTableName] = colMetaData.TableName; } if (!ADP.IsEmpty(colMetaData.SchemaName)) { schemaRow[BaseSchemaName] = colMetaData.SchemaName; } if (!ADP.IsEmpty(colMetaData.CatalogName)) { schemaRow[BaseCatalogName] = colMetaData.CatalogName; } if (!ADP.IsEmpty(colMetaData.ServerName)) { schemaRow[BaseServerName] = colMetaData.ServerName; } if ( SqlDbType.Udt == colMetaData.SqlDbType ) { schemaRow[DataTypeName] = colMetaData.TypeSpecificNamePart1 + "." + colMetaData.TypeSpecificNamePart2 + "." + colMetaData.TypeSpecificNamePart3; } else { schemaRow[DataTypeName] = metaType.TypeName; } // Add Xml metadata if ( SqlDbType.Xml == colMetaData.SqlDbType ) { schemaRow[XmlSchemaCollectionDatabase] = colMetaData.TypeSpecificNamePart1; schemaRow[XmlSchemaCollectionOwningSchema] = colMetaData.TypeSpecificNamePart2; schemaRow[XmlSchemaCollectionName] = colMetaData.TypeSpecificNamePart3; } schemaTable.Rows.Add(schemaRow); schemaRow.AcceptChanges(); } // mark all columns as readonly foreach(DataColumn column in columns) { column.ReadOnly = true; // MDAC 70943 } _schemaTable = schemaTable; } return _schemaTable; } // // ISqlRecord methods // public override SqlBinary GetSqlBinary(int ordinal) { EnsureCanGetCol( "GetSqlBinary", ordinal); return ValueUtilsSmi.GetSqlBinary(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlBoolean GetSqlBoolean(int ordinal) { EnsureCanGetCol( "GetSqlBoolean", ordinal); return ValueUtilsSmi.GetSqlBoolean(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlByte GetSqlByte(int ordinal) { EnsureCanGetCol( "GetSqlByte", ordinal); return ValueUtilsSmi.GetSqlByte(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlInt16 GetSqlInt16(int ordinal) { EnsureCanGetCol( "GetSqlInt16", ordinal); return ValueUtilsSmi.GetSqlInt16(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlInt32 GetSqlInt32(int ordinal) { EnsureCanGetCol( "GetSqlInt32", ordinal); return ValueUtilsSmi.GetSqlInt32(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlInt64 GetSqlInt64(int ordinal) { EnsureCanGetCol( "GetSqlInt64", ordinal); return ValueUtilsSmi.GetSqlInt64(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlSingle GetSqlSingle(int ordinal) { EnsureCanGetCol( "GetSqlSingle", ordinal); return ValueUtilsSmi.GetSqlSingle(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlDouble GetSqlDouble(int ordinal) { EnsureCanGetCol( "GetSqlDouble", ordinal); return ValueUtilsSmi.GetSqlDouble(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlMoney GetSqlMoney(int ordinal) { EnsureCanGetCol( "GetSqlMoney", ordinal); return ValueUtilsSmi.GetSqlMoney(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlDateTime GetSqlDateTime(int ordinal) { EnsureCanGetCol( "GetSqlDateTime", ordinal); return ValueUtilsSmi.GetSqlDateTime(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlDecimal GetSqlDecimal(int ordinal) { EnsureCanGetCol( "GetSqlDecimal", ordinal); return ValueUtilsSmi.GetSqlDecimal(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlString GetSqlString(int ordinal) { EnsureCanGetCol( "GetSqlString", ordinal); return ValueUtilsSmi.GetSqlString(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlGuid GetSqlGuid(int ordinal) { EnsureCanGetCol( "GetSqlGuid", ordinal); return ValueUtilsSmi.GetSqlGuid(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal]); } public override SqlChars GetSqlChars(int ordinal) { EnsureCanGetCol( "GetSqlChars", ordinal); return ValueUtilsSmi.GetSqlChars(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], _currentConnection.InternalContext); } public override SqlBytes GetSqlBytes(int ordinal) { EnsureCanGetCol( "GetSqlBytes", ordinal); return ValueUtilsSmi.GetSqlBytes(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], _currentConnection.InternalContext); } public override SqlXml GetSqlXml(int ordinal) { EnsureCanGetCol( "GetSqlXml", ordinal); return ValueUtilsSmi.GetSqlXml(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], _currentConnection.InternalContext); } public override TimeSpan GetTimeSpan(int ordinal) { EnsureCanGetCol("GetTimeSpan", ordinal); return ValueUtilsSmi.GetTimeSpan(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], _currentConnection.IsKatmaiOrNewer); } public override DateTimeOffset GetDateTimeOffset(int ordinal) { EnsureCanGetCol("GetDateTimeOffset", ordinal); return ValueUtilsSmi.GetDateTimeOffset(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], _currentConnection.IsKatmaiOrNewer); } public override object GetSqlValue(int ordinal) { EnsureCanGetCol( "GetSqlValue", ordinal); SmiMetaData metaData = _currentMetaData[ordinal]; if (_currentConnection.IsKatmaiOrNewer) { return ValueUtilsSmi.GetSqlValue200(_readerEventSink, (SmiTypedGetterSetter)_currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); } return ValueUtilsSmi.GetSqlValue(_readerEventSink, _currentColumnValuesV3, ordinal, metaData, _currentConnection.InternalContext); ; } public override int GetSqlValues(object[] values) { EnsureCanGetCol( "GetSqlValues", 0); if (null == values) { throw ADP.ArgumentNull("values"); } int copyLength = (values.Length < _visibleColumnCount) ? values.Length : _visibleColumnCount; for(int i=0; i<copyLength; i++) { values[_indexMap[i]] = GetSqlValue(i); } return copyLength; } // // ISqlReader methods/properties // public override bool HasRows { get {return _hasRows;} } // // SqlDataReader method/properties // public override Stream GetStream(int ordinal) { EnsureCanGetCol("GetStream", ordinal); SmiQueryMetaData metaData = _currentMetaData[ordinal]; // For non-null, non-variant types with sequential access, we support proper streaming if ((metaData.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess)) && (!ValueUtilsSmi.IsDBNull(_readerEventSink, _currentColumnValuesV3, ordinal))) { if (HasActiveStreamOrTextReaderOnColumn(ordinal)) { throw ADP.NonSequentialColumnAccess(ordinal, ordinal + 1); } _currentStream = ValueUtilsSmi.GetSequentialStream(_readerEventSink, _currentColumnValuesV3, ordinal, metaData); return _currentStream; } else { return ValueUtilsSmi.GetStream(_readerEventSink, _currentColumnValuesV3, ordinal, metaData); } } public override TextReader GetTextReader(int ordinal) { EnsureCanGetCol("GetTextReader", ordinal); SmiQueryMetaData metaData = _currentMetaData[ordinal]; // For non-variant types with sequential access, we support proper streaming if ((metaData.SqlDbType != SqlDbType.Variant) && (IsCommandBehavior(CommandBehavior.SequentialAccess)) && (!ValueUtilsSmi.IsDBNull(_readerEventSink, _currentColumnValuesV3, ordinal))) { if (HasActiveStreamOrTextReaderOnColumn(ordinal)) { throw ADP.NonSequentialColumnAccess(ordinal, ordinal + 1); } _currentTextReader = ValueUtilsSmi.GetSequentialTextReader(_readerEventSink, _currentColumnValuesV3, ordinal, metaData); return _currentTextReader; } else { return ValueUtilsSmi.GetTextReader(_readerEventSink, _currentColumnValuesV3, ordinal, metaData); } } public override XmlReader GetXmlReader(int ordinal) { // NOTE: sql_variant can not contain a XML data type: http://msdn.microsoft.com/en-us/library/ms173829.aspx EnsureCanGetCol("GetXmlReader", ordinal); if (_currentMetaData[ordinal].SqlDbType != SqlDbType.Xml) { throw ADP.InvalidCast(); } Stream stream = null; if ((IsCommandBehavior(CommandBehavior.SequentialAccess)) && (!ValueUtilsSmi.IsDBNull(_readerEventSink, _currentColumnValuesV3, ordinal))) { if (HasActiveStreamOrTextReaderOnColumn(ordinal)) { throw ADP.NonSequentialColumnAccess(ordinal, ordinal + 1); } // Need to bypass the type check since streams are not usually allowed on XML types _currentStream = ValueUtilsSmi.GetSequentialStream(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], bypassTypeCheck: true); stream = _currentStream; } else { stream = ValueUtilsSmi.GetStream(_readerEventSink, _currentColumnValuesV3, ordinal, _currentMetaData[ordinal], bypassTypeCheck: true); } return SqlXml.CreateSqlXmlReader(stream); } // // Internal reader state // // Logical state of reader/resultset as viewed by the client // Does not necessarily match up with server state. internal enum PositionState { BeforeResults, // Before all resultset in request BeforeRows, // Before all rows in current resultset OnRow, // On a valid row in the current resultset AfterRows, // After all rows in current resultset AfterResults // After all resultsets in request } private PositionState _currentPosition; // Where is the reader relative to incoming results? // // Fields // private bool _isOpen; // Is the reader open? private SmiQueryMetaData[] _currentMetaData; // Metadata for current resultset private int[] _indexMap; // map of indices for visible column private int _visibleColumnCount; // number of visible columns private DataTable _schemaTable; // Cache of user-visible extended metadata while in results. private ITypedGetters _currentColumnValues; // Unmanaged-managed data marshalers/cache private ITypedGettersV3 _currentColumnValuesV3; // Unmanaged-managed data marshalers/cache for SMI V3 private bool _hasRows; // Are there any rows in the current resultset? Must be able to say before moving to first row. private SmiEventStream _eventStream; // The event buffer that receives the events from the execution engine. private SmiRequestExecutor _requestExecutor; // The used to request actions from the execution engine. private SqlInternalConnectionSmi _currentConnection; private ReaderEventSink _readerEventSink; // The event sink that will process events from the event buffer. private FieldNameLookup _fieldNameLookup; // cached lookup object to improve access time based on field name private SqlSequentialStreamSmi _currentStream; // The stream on the current column (if any) private SqlSequentialTextReaderSmi _currentTextReader; // The text reader on the current column (if any) // // Internal methods for use by other classes in project // // Constructor // // Assumes that if there were any results, the first chunk of them are in the data stream // (up to the first actual row or the end of the resultsets). unsafe internal SqlDataReaderSmi ( SmiEventStream eventStream, // the event stream that receives the events from the execution engine SqlCommand parent, // command that owns reader CommandBehavior behavior, // behavior specified for this execution SqlInternalConnectionSmi connection, // connection that owns everybody SmiEventSink parentSink, // Event sink of parent command SmiRequestExecutor requestExecutor ) : base( parent, behavior ) { // _eventStream = eventStream; _currentConnection = connection; _readerEventSink = new ReaderEventSink( this, parentSink ); _currentPosition = PositionState.BeforeResults; _isOpen = true; _indexMap = null; _visibleColumnCount = 0; _currentStream = null; _currentTextReader = null; _requestExecutor = requestExecutor; } internal override SmiExtendedMetaData[] GetInternalSmiMetaData() { if (null == _currentMetaData || _visibleColumnCount == this.InternalFieldCount) { return _currentMetaData; } else { #if DEBUG // DEVNOTE: Interpretation of returned array currently depends on hidden columns // always appearing at the end, since there currently is no access to the index map // outside of this class. In Debug code, we check this assumption. bool sawHiddenColumn = false; #endif SmiExtendedMetaData[] visibleMetaData = new SmiExtendedMetaData[_visibleColumnCount]; for(int i=0; i<_visibleColumnCount; i++) { #if DEBUG if (_currentMetaData[_indexMap[i]].IsHidden.IsTrue) { sawHiddenColumn = true; } else { Debug.Assert(!sawHiddenColumn); } #endif visibleMetaData[i] = _currentMetaData[_indexMap[i]]; } return visibleMetaData; } } internal override int GetLocaleId(int ordinal) { EnsureCanGetMetaData( "GetLocaleId" ); return (int)_currentMetaData[ordinal].LocaleId; } // // Private implementation methods // private int InternalFieldCount { get { if ( FNotInResults() ) { return 0; } else { return _currentMetaData.Length; } } } // Have we cleaned up internal resources? private bool IsReallyClosed() { return !_isOpen; } // Central checkpoint for closed recordset. // Any code that requires an open recordset should call this method first! // Especially any code that accesses unmanaged memory structures whose lifetime // matches the lifetime of the unmanaged recordset. internal void ThrowIfClosed( string operationName ) { if (IsClosed) throw ADP.DataReaderClosed( operationName ); } // Central checkpoint to ensure the requested column can be accessed. // Calling this function serves to notify that it has been accessed by the user. [SuppressMessage("Microsoft.Performance", "CA1801:AvoidUnusedParameters")] // for future compatibility private void EnsureCanGetCol( string operationName, int ordinal) { EnsureOnRow( operationName ); } internal void EnsureOnRow( string operationName ) { ThrowIfClosed( operationName ); if (_currentPosition != PositionState.OnRow) { throw SQL.InvalidRead(); } } internal void EnsureCanGetMetaData( string operationName ) { ThrowIfClosed( operationName ); if (FNotInResults()) { throw SQL.InvalidRead(); // } } private bool FInResults() { return !FNotInResults(); } private bool FNotInResults() { return (PositionState.AfterResults == _currentPosition || PositionState.BeforeResults == _currentPosition); } private void MetaDataAvailable( SmiQueryMetaData[] md, bool nextEventIsRow ) { Debug.Assert( _currentPosition != PositionState.AfterResults ); _currentMetaData = md; _hasRows = nextEventIsRow; _fieldNameLookup = null; _schemaTable = null; // will be rebuilt based on new metadata _currentPosition = PositionState.BeforeRows; // calculate visible column indices _indexMap = new int[_currentMetaData.Length]; int i; int visibleCount = 0; for(i=0; i<_currentMetaData.Length; i++) { if (!_currentMetaData[i].IsHidden.IsTrue) { _indexMap[visibleCount] = i; visibleCount++; } } _visibleColumnCount = visibleCount; } private bool HasActiveStreamOrTextReaderOnColumn(int columnIndex) { bool active = false; active |= ((_currentStream != null) && (_currentStream.ColumnIndex == columnIndex)); active |= ((_currentTextReader != null) && (_currentTextReader.ColumnIndex == columnIndex)); return active; } // Obsolete V2- method private void RowAvailable( ITypedGetters row ) { Debug.Assert( _currentPosition != PositionState.AfterResults ); _currentColumnValues = row; _currentPosition = PositionState.OnRow; } private void RowAvailable( ITypedGettersV3 row ) { Debug.Assert( _currentPosition != PositionState.AfterResults ); _currentColumnValuesV3 = row; _currentPosition = PositionState.OnRow; } private void StatementCompleted( ) { Debug.Assert( _currentPosition != PositionState.AfterResults ); _currentPosition = PositionState.AfterRows; } private void ResetResultSet() { _currentMetaData = null; _visibleColumnCount = 0; _schemaTable = null; } private void BatchCompleted() { Debug.Assert( _currentPosition != PositionState.AfterResults ); ResetResultSet(); _currentPosition = PositionState.AfterResults; _eventStream.Close( _readerEventSink ); } // An implementation of the IEventSink interface that either performs // the required enviornment changes or forwards the events on to the // corresponding reader instance. Having the event sink be a separate // class keeps the IEventSink methods out of SqlDataReader's inteface. private sealed class ReaderEventSink : SmiEventSink_Default { private readonly SqlDataReaderSmi reader; internal ReaderEventSink( SqlDataReaderSmi reader, SmiEventSink parent ) : base( parent ) { this.reader = reader; } internal override void MetaDataAvailable( SmiQueryMetaData[] md, bool nextEventIsRow ) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.MetaDataAvailable|ADV> %d#, md.Length=%d nextEventIsRow=%d.\n", reader.ObjectID, (null != md) ? md.Length : -1, nextEventIsRow); if (null != md) { for (int i=0; i < md.Length; i++) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.MetaDataAvailable|ADV> %d#, metaData[%d] is %ls%ls\n", reader.ObjectID, i, md[i].GetType().ToString(), md[i].TraceString()); } } } this.reader.MetaDataAvailable( md, nextEventIsRow ); } // Obsolete V2- method internal override void RowAvailable( ITypedGetters row ) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.RowAvailable|ADV> %d# (v2).\n", reader.ObjectID); } this.reader.RowAvailable( row ); } internal override void RowAvailable( ITypedGettersV3 row ) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.RowAvailable|ADV> %d# (ITypedGettersV3).\n", reader.ObjectID); } this.reader.RowAvailable( row ); } internal override void RowAvailable(SmiTypedGetterSetter rowData) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.RowAvailable|ADV> %d# (SmiTypedGetterSetter).\n", reader.ObjectID); } this.reader.RowAvailable(rowData); } internal override void StatementCompleted( int recordsAffected ) { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.StatementCompleted|ADV> %d# recordsAffected=%d.\n", reader.ObjectID, recordsAffected); } // devnote: relies on SmiEventSink_Default to pass event to parent // Both command and reader care about StatementCompleted, but for different reasons. base.StatementCompleted( recordsAffected ); this.reader.StatementCompleted( ); } internal override void BatchCompleted() { if (Bid.AdvancedOn) { Bid.Trace("<sc.SqlDataReaderSmi.ReaderEventSink.BatchCompleted|ADV> %d#.\n", reader.ObjectID); } // devnote: relies on SmiEventSink_Default to pass event to parent // parent's callback *MUST* come before reader's BatchCompleted, since // reader will close the event stream during this call, and parent wants // to extract parameter values before that happens. base.BatchCompleted(); this.reader.BatchCompleted(); } } } }
// 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 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute.Models { using Azure; using Management; using Compute; using Rest; using Rest.Serialization; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Describes a virtual machine scale set virtual machine. /// </summary> [JsonTransformation] public partial class VirtualMachineScaleSetVM : Resource { /// <summary> /// Initializes a new instance of the VirtualMachineScaleSetVM class. /// </summary> public VirtualMachineScaleSetVM() { } /// <summary> /// Initializes a new instance of the VirtualMachineScaleSetVM class. /// </summary> /// <param name="location">Resource location</param> /// <param name="id">Resource Id</param> /// <param name="name">Resource name</param> /// <param name="type">Resource type</param> /// <param name="tags">Resource tags</param> /// <param name="instanceId">The virtual machine instance ID.</param> /// <param name="sku">The virtual machine SKU.</param> /// <param name="latestModelApplied">Specifies whether the latest model /// has been applied to the virtual machine.</param> /// <param name="vmId">Azure VM unique ID.</param> /// <param name="instanceView">The virtual machine instance /// view.</param> /// <param name="hardwareProfile">The hardware profile.</param> /// <param name="storageProfile">The storage profile.</param> /// <param name="osProfile">The OS profile.</param> /// <param name="networkProfile">The network profile.</param> /// <param name="diagnosticsProfile">The diagnostics profile.</param> /// <param name="availabilitySet">The reference Id of the availability /// set to which this virtual machine belongs.</param> /// <param name="provisioningState">The provisioning state, which only /// appears in the response.</param> /// <param name="licenseType">The license type, which is for bring your /// own license scenario.</param> /// <param name="plan">The purchase plan when deploying virtual machine /// from VM Marketplace images.</param> /// <param name="resources">The virtual machine child extension /// resources.</param> public VirtualMachineScaleSetVM(string location, string id = default(string), string name = default(string), string type = default(string), IDictionary<string, string> tags = default(IDictionary<string, string>), string instanceId = default(string), Sku sku = default(Sku), bool? latestModelApplied = default(bool?), string vmId = default(string), VirtualMachineInstanceView instanceView = default(VirtualMachineInstanceView), HardwareProfile hardwareProfile = default(HardwareProfile), StorageProfile storageProfile = default(StorageProfile), OSProfile osProfile = default(OSProfile), NetworkProfile networkProfile = default(NetworkProfile), DiagnosticsProfile diagnosticsProfile = default(DiagnosticsProfile), SubResource availabilitySet = default(SubResource), string provisioningState = default(string), string licenseType = default(string), Plan plan = default(Plan), IList<VirtualMachineExtension> resources = default(IList<VirtualMachineExtension>)) : base(location, id, name, type, tags) { InstanceId = instanceId; Sku = sku; LatestModelApplied = latestModelApplied; VmId = vmId; InstanceView = instanceView; HardwareProfile = hardwareProfile; StorageProfile = storageProfile; OsProfile = osProfile; NetworkProfile = networkProfile; DiagnosticsProfile = diagnosticsProfile; AvailabilitySet = availabilitySet; ProvisioningState = provisioningState; LicenseType = licenseType; Plan = plan; Resources = resources; } /// <summary> /// Gets the virtual machine instance ID. /// </summary> [JsonProperty(PropertyName = "instanceId")] public string InstanceId { get; protected set; } /// <summary> /// Gets the virtual machine SKU. /// </summary> [JsonProperty(PropertyName = "sku")] public Sku Sku { get; protected set; } /// <summary> /// Gets specifies whether the latest model has been applied to the /// virtual machine. /// </summary> [JsonProperty(PropertyName = "properties.latestModelApplied")] public bool? LatestModelApplied { get; protected set; } /// <summary> /// Gets azure VM unique ID. /// </summary> [JsonProperty(PropertyName = "properties.vmId")] public string VmId { get; protected set; } /// <summary> /// Gets the virtual machine instance view. /// </summary> [JsonProperty(PropertyName = "properties.instanceView")] public VirtualMachineInstanceView InstanceView { get; protected set; } /// <summary> /// Gets or sets the hardware profile. /// </summary> [JsonProperty(PropertyName = "properties.hardwareProfile")] public HardwareProfile HardwareProfile { get; set; } /// <summary> /// Gets or sets the storage profile. /// </summary> [JsonProperty(PropertyName = "properties.storageProfile")] public StorageProfile StorageProfile { get; set; } /// <summary> /// Gets or sets the OS profile. /// </summary> [JsonProperty(PropertyName = "properties.osProfile")] public OSProfile OsProfile { get; set; } /// <summary> /// Gets or sets the network profile. /// </summary> [JsonProperty(PropertyName = "properties.networkProfile")] public NetworkProfile NetworkProfile { get; set; } /// <summary> /// Gets or sets the diagnostics profile. /// </summary> [JsonProperty(PropertyName = "properties.diagnosticsProfile")] public DiagnosticsProfile DiagnosticsProfile { get; set; } /// <summary> /// Gets or sets the reference Id of the availability set to which this /// virtual machine belongs. /// </summary> [JsonProperty(PropertyName = "properties.availabilitySet")] public SubResource AvailabilitySet { get; set; } /// <summary> /// Gets the provisioning state, which only appears in the response. /// </summary> [JsonProperty(PropertyName = "properties.provisioningState")] public string ProvisioningState { get; protected set; } /// <summary> /// Gets or sets the license type, which is for bring your own license /// scenario. /// </summary> [JsonProperty(PropertyName = "properties.licenseType")] public string LicenseType { get; set; } /// <summary> /// Gets or sets the purchase plan when deploying virtual machine from /// VM Marketplace images. /// </summary> [JsonProperty(PropertyName = "plan")] public Plan Plan { get; set; } /// <summary> /// Gets the virtual machine child extension resources. /// </summary> [JsonProperty(PropertyName = "resources")] public IList<VirtualMachineExtension> Resources { get; protected set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public override void Validate() { base.Validate(); if (StorageProfile != null) { StorageProfile.Validate(); } if (Resources != null) { foreach (var element in Resources) { if (element != null) { element.Validate(); } } } } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Bolt.Generators; using Microsoft.Dnx.Runtime.Common.CommandLine; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Bolt.Console { public class RootConfig { private static readonly AnsiConsole Console = AnsiConsole.GetOutput(true); private readonly Dictionary<string, DocumentGenerator> _documents = new Dictionary<string, DocumentGenerator>(); public RootConfig(AssemblyCache cache) { Contracts = new List<ProxyConfig>(); AssemblyCache = cache; Generators = new List<GeneratorConfig>(); Assemblies = new List<string>(); } public static RootConfig CreateFromConfig(AssemblyCache cache, string file) { file = Path.GetFullPath(file); string content = File.ReadAllText(file); return CreateFromConfig(cache, Path.GetDirectoryName(file), content); } public static RootConfig CreateFromConfig(AssemblyCache cache, string outputDirectory, string content) { var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include, Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }; RootConfig config = JsonConvert.DeserializeObject<RootConfig>(content, settings); config.OutputDirectory = outputDirectory; config.AssemblyCache = cache; foreach (ProxyConfig contract in config.Contracts) { contract.Parent = config; } if (config.Generators != null) { foreach (GeneratorConfig generator in config.Generators) { generator.Parent = config; } } return config; } public static RootConfig CreateFromAssembly(AssemblyCache cache, string assembly, GenerateContractMode mode, bool internalVisibility) { RootConfig root = new RootConfig(cache) { Contracts = new List<ProxyConfig>() }; Assembly loadedAssembly = null; if (!string.IsNullOrEmpty(assembly) && File.Exists(assembly)) { root.Assemblies = new List<string> { Path.GetFullPath(assembly) }; loadedAssembly = cache.Loader.Load(assembly); } else { loadedAssembly = cache.HostedAssembly; } if (loadedAssembly != null) { foreach (var type in root.AssemblyCache.GetTypes(loadedAssembly)) { root.AddContract(type.GetTypeInfo(), mode, internalVisibility); }; } return root; } [JsonIgnore] public AssemblyCache AssemblyCache { get; private set; } public List<string> Assemblies { get; set; } public List<GeneratorConfig> Generators { get; set; } [JsonProperty(Required = Required.Always)] public List<ProxyConfig> Contracts { get; set; } [JsonIgnore] public bool IgnoreGeneratorErrors { get; set; } public string Modifier { get; set; } public bool FullTypeNames { get; set; } [JsonIgnore] public string OutputDirectory { get; set; } public string Serialize() { return JsonConvert.SerializeObject( this, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, Formatting = Formatting.Indented, ContractResolver = new CamelCasePropertyNamesContractResolver() }); } public void AddContractsFromNamespace(string ns, GenerateContractMode mode, bool internalVisibility) { foreach (var type in AssemblyCache.GetTypes(ns)) { AddContract(type.GetTypeInfo(), mode, internalVisibility); Console.WriteLine($"Contract '{type.Name.Bold()}' added."); } } public void AddAllContracts(GenerateContractMode mode, bool internalVisibility) { foreach (var type in AssemblyCache.GetTypes()) { AddContract(type.GetTypeInfo(), mode, internalVisibility); Console.WriteLine($"Contract '{type.Name.Bold()}' added."); } } public void AddContract(string name, GenerateContractMode mode, bool internalVisibility) { var type = AssemblyCache.GetType(name); var addedContract = AddContract(type.GetTypeInfo(), mode, internalVisibility); if (addedContract != null) { Console.WriteLine($"Contract '{type.Name.Bold()}' added."); } else { Console.WriteLine($"Contract '{type.Name.Bold()}' not found."); } } public ProxyConfig AddContract(TypeInfo type, GenerateContractMode mode, bool internalVisibility) { if (type == null) { return null; } if (!type.IsInterface) { return null; } if (Contracts.FirstOrDefault(existing => existing.Contract == type.FullName) != null) { return null; } ProxyConfig c = new ProxyConfig { Parent = this, Contract = type.AssemblyQualifiedName, Modifier = internalVisibility ? "internal" : "public", ForceAsync = true, Namespace = type.Namespace, Mode = mode }; Contracts.Add(c); return c; } public int Generate() { if (Assemblies != null) { List<string> directories = Assemblies.Select(Path.GetDirectoryName) .Concat(new[] { Directory.GetCurrentDirectory() }) .Distinct() .ToList(); foreach (string dir in directories) { AssemblyCache.Loader.AddDirectory(dir); } foreach (string assembly in Assemblies) { AssemblyCache.Loader.Load(assembly); } } Stopwatch watch = Stopwatch.StartNew(); foreach (ProxyConfig contract in Contracts) { try { contract.Generate(); } catch (Exception e) { if (!IgnoreGeneratorErrors) { return Program.HandleError($"Failed to generate contract: {contract.Contract.Bold().White()}", e); } Program.HandleError($"Skipped contract generation: {contract.Contract.Bold().White()}", e); } } Console.WriteLine(Environment.NewLine); Console.WriteLine("Generating files ... "); foreach (var filesInDirectory in _documents.GroupBy(f=>Path.GetDirectoryName(f.Key))) { Console.WriteLine(string.Join(string.Empty, Enumerable.Repeat("-", filesInDirectory.Key.Count() + 12).ToArray())); Console.WriteLine($"Directory: {filesInDirectory.Key.Bold().White()}"); Console.WriteLine(Environment.NewLine); foreach (var documentGenerator in filesInDirectory) { try { string status; string result = documentGenerator.Value.GetResult(); if (File.Exists(documentGenerator.Key)) { string prev = File.ReadAllText(documentGenerator.Key); if (prev != result) { File.WriteAllText(documentGenerator.Key, result); status = "Overwritten".Green().Bold(); } else { status = "Skipped".White(); } } else { string directory = Path.GetDirectoryName(documentGenerator.Key); if (directory != null && !Directory.Exists(directory)) { Directory.CreateDirectory(directory); } File.WriteAllText(documentGenerator.Key, result); status = "Generated".Green(); } Console.WriteLine($"{status}: {Path.GetFileName(documentGenerator.Key).White().Bold()}"); } catch (Exception e) { return Program.HandleError($"File Generation Failed: {Path.GetFileName(documentGenerator.Key).White()}", e); } } } Console.WriteLine(Environment.NewLine); Console.WriteLine("Status:"); Console.WriteLine($"{(_documents.Count + " Files Generated,").Green().Bold()} {watch.ElapsedMilliseconds}ms elapsed"); Console.WriteLine(Environment.NewLine); return 0; } public DocumentGenerator GetDocument(string output) { if (output == null) { throw new ArgumentNullException(nameof(output)); } if (!_documents.ContainsKey(output)) { _documents[output] = new DocumentGenerator(); if (FullTypeNames) { _documents[output].Formatter.ForceFullTypeNames = true; } } return _documents[output]; } public IUserCodeGenerator GetGenerator(string generatorName) { GeneratorConfig found = Generators.EmptyIfNull().FirstOrDefault( g => string.Equals(g.Name, generatorName, StringComparison.OrdinalIgnoreCase)); if (found == null) { throw new InvalidOperationException($"GeneratorEx '{generatorName}' is not registered."); } return found.GetGenerator(); } } }
using System; using System.Text; using System.Collections.Generic; using Volte.Utils; namespace Volte.Data.Json { [Serializable] public class Row { const string ZFILE_NAME = "Row"; // Methods public Row() { _cells = new List<Cell>(); _Reference = new JSONObject(); _Reference.SetBoolean("a" , false); } public Row(int i) { _cells = new List<Cell> (i); _Reference = new JSONObject(); _Reference.SetBoolean("a" , false); } internal void Read(Lexer _Lexer) { if (_Lexer.Current == '{') { _Lexer.NextToken(); string name = _Lexer.ParseName(); int c = 0; if (name == "cells") { _Lexer.SkipWhiteSpace(); if (_Lexer.Current == '[') { _Lexer.NextToken(); _Lexer.SkipWhiteSpace(); for (;;) { c++; JSONObject _JSONObject = new JSONObject(_Lexer); Cell _cell; _cell.sCode = _JSONObject.GetValue("id"); _cell.Value = _JSONObject.GetValue("v"); _cell.sFormula = _JSONObject.GetValue("f"); _cells.Add(_cell); if (_Lexer.Current == ',') { _Lexer.NextToken(); } else { break; } } } _Lexer.NextToken(); } if (_Lexer.Current == ',') { _Lexer.NextToken(); } name = _Lexer.ParseName(); if (name == "reference") { _Reference = new JSONObject(); _Reference.SetBoolean("a" , false); _Reference.Read(_Lexer); _Lexer.SkipWhiteSpace(); } _Lexer.NextToken(); } } private void Write(StringBuilder writer , string sName , object o) { if (_Flatten==Flatten.Value){ }else if (_Flatten==Flatten.NameValue){ writer.Append("\""); writer.Append(sName); writer.Append("\":"); }else{ writer.Append("\""); writer.Append(sName); writer.Append("\":"); } if (o is DateTime) { if (o==null || string.IsNullOrEmpty(o.ToString())) { writer.Append("null"); }else if (o is DateTime) { if ((DateTime)o<= Util.DateTime_MinValue) { writer.Append("null"); } else { try{ writer.Append(Util.DateTimeToMilliSecond((DateTime)o)); }catch (Exception ex) { ZZLogger.Debug(ZFILE_NAME , o); ZZLogger.Debug(ZFILE_NAME , ex); } } }else{ writer.Append(Util.DateTimeToMilliSecond(Util.ToDateTime(o))); } }else if (o is decimal || o is int) { writer.Append(o.ToString()); } else if (o is bool) { writer.Append(o.ToString().ToLower()); } else { writer.Append("\""); if (o!=null){ Util.EscapeString(writer, o.ToString()); } writer.Append("\""); } } internal void Write(StringBuilder writer , Columns _columns) { if (_Flatten==Flatten.Value){ writer.AppendLine("["); if (_cells != null) { bool first = true; foreach (Cell _Cell in _cells) { if (!first) { writer.AppendLine(","); } else { first = false; } this.Write(writer , "v" , _Cell.Value); } } writer.Append("]"); }else if (_Flatten==Flatten.NameValue){ writer.AppendLine("{"); if (_cells != null) { bool first = true; int i=0; foreach (Cell _Cell in _cells) { if (!first) { writer.AppendLine(","); } else { first = false; } this.Write(writer , _columns.Fields[i].Name , _Cell.Value); i++; } } writer.Append("}"); }else{ writer.AppendLine("{"); if (_cells != null) { writer.Append("\"cells\":"); writer.Append("["); bool first = true; foreach (Cell _Cell in _cells) { if (!first) { writer.AppendLine(","); } else { first = false; } writer.Append("{"); this.Write(writer , "v" , _Cell.Value); if (!string.IsNullOrEmpty(_Cell.sCode)){ writer.Append(","); this.Write(writer , "id" , _Cell.sCode); } if (!string.IsNullOrEmpty(_Cell.sFormula)){ writer.Append(","); this.Write(writer , "f" , _Cell.sFormula); } writer.Append("}"); } writer.Append("]"); writer.AppendLine(","); writer.AppendLine(""); } writer.Append("\"reference\":"); if (_Reference==null){ _Reference = new JSONObject(); _Reference.SetBoolean("a" , false); } _Reference.Write(writer); writer.AppendLine(""); writer.AppendLine("}"); } } public decimal GetDecimal(int i) { return Util.ToDecimal(this[i].Value); } public DateTime GetDateTime(int i) { return Util.ToDateTime(this[i].Value); } public Cell this[int i] { get { if (i >= _cells.Count) { _size = _cells.Count; for (int x = _size; x <= i; x++) { _size++; _cells.Add(new Cell()); } } return _cells[i]; } set { if (i >= _cells.Count) { _size = _cells.Count; for (int x = _size; x <= i; x++) { _size++; if (x >= i) { _cells.Add(value); } else { _cells.Add(new Cell()); } } } else { _cells[i] = value; } } } public int Index { get { return _Index; } set { _Index = value; } } public JSONObject Reference { get { return _Reference; } set { _Reference = value; } } public Flatten Flatten { get { return _Flatten; } set { _Flatten = value; } } // Fields private int _Index = -1; private int _size = 0; private Flatten _Flatten = Flatten.Complex; private List<Cell> _cells = new List<Cell>(); private JSONObject _Reference = new JSONObject(); } }
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 JWPush.Server.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Test.Common; using System.Threading; using Xunit; using Xunit.Abstractions; namespace System.Net.Sockets.Tests { public class DnsEndPointTest { // Port 8 is unassigned as per https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt private const int UnusedPort = 8; private readonly ITestOutputHelper _log; public DnsEndPointTest(ITestOutputHelper output) { _log = TestLogging.GetInstance(); } private void OnConnectAsyncCompleted(object sender, SocketAsyncEventArgs args) { ManualResetEvent complete = (ManualResetEvent)args.UserToken; complete.Set(); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(PlatformID.Windows)] public void Socket_ConnectDnsEndPoint_Success(SocketImplementationType type) { int port; SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); sock.Connect(new DnsEndPoint("localhost", port)); sock.Dispose(); server.Dispose(); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void Socket_ConnectDnsEndPoint_Failure() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // TODO (#7853): Behavior difference from .Net Desktop. This will actually throw InternalSocketException. SocketException ex = Assert.ThrowsAny<SocketException>(() => { sock.Connect(new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort)); }); SocketError errorCode = ex.SocketErrorCode; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketErrorCode: {0}" + errorCode); // TODO (#7853): Behavior difference from .Net Desktop. This will actually throw InternalSocketException. ex = Assert.ThrowsAny<SocketException>(() => { sock.Connect(new DnsEndPoint("localhost", UnusedPort)); }); Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode); } } [Fact] public void Socket_SendToDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { Assert.Throws<ArgumentException>(() => { sock.SendTo(new byte[10], new DnsEndPoint("localhost", UnusedPort)); }); } } [Fact] public void Socket_ReceiveFromDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { int port = sock.BindToAnonymousPort(IPAddress.Loopback); EndPoint endpoint = new DnsEndPoint("localhost", port); Assert.Throws<ArgumentException>(() => { sock.ReceiveFrom(new byte[10], ref endpoint); }); } } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [PlatformSpecific(PlatformID.Windows)] public void Socket_BeginConnectDnsEndPoint_Success(SocketImplementationType type) { int port; SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port); Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", port), null, null); sock.EndConnect(result); sock.Dispose(); server.Dispose(); } [Fact] [PlatformSpecific(PlatformID.Windows)] public void Socket_BeginConnectDnsEndPoint_Failure() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { // TODO (#7853): Behavior difference from .Net Desktop. This will actually throw InternalSocketException. SocketException ex = Assert.ThrowsAny<SocketException>(() => { IAsyncResult result = sock.BeginConnect(new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort), null, null); sock.EndConnect(result); }); SocketError errorCode = ex.SocketErrorCode; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketErrorCode: {0}" + errorCode); // TODO (#7853): Behavior difference from .Net Desktop. This will actually throw InternalSocketException. ex = Assert.ThrowsAny<SocketException>(() => { IAsyncResult result = sock.BeginConnect(new DnsEndPoint("localhost", UnusedPort), null, null); sock.EndConnect(result); }); Assert.Equal(SocketError.ConnectionRefused, ex.SocketErrorCode); } } [Fact] public void Socket_BeginSendToDnsEndPoint_ArgumentException() { using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { Assert.Throws<ArgumentException>(() => { sock.BeginSendTo(new byte[10], 0, 0, SocketFlags.None, new DnsEndPoint("localhost", UnusedPort), null, null); }); } } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [Trait("IPv4", "true")] [PlatformSpecific(PlatformID.Windows)] public void Socket_ConnectAsyncDnsEndPoint_Success(SocketImplementationType type) { Assert.True(Capability.IPv4Support()); int port; SocketTestServer server = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); complete.Dispose(); sock.Dispose(); server.Dispose(); } [Fact] [Trait("IPv4", "true")] [PlatformSpecific(PlatformID.Windows)] public void Socket_ConnectAsyncDnsEndPoint_HostNotFound() { Assert.True(Capability.IPv4Support()); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); } AssertHostNotFoundOrNoData(args); complete.Dispose(); sock.Dispose(); } [Fact] [Trait("IPv4", "true")] [PlatformSpecific(PlatformID.Windows)] public void Socket_ConnectAsyncDnsEndPoint_ConnectionRefused() { Assert.True(Capability.IPv4Support()); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); bool willRaiseEvent = sock.ConnectAsync(args); if (willRaiseEvent) { Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); } Assert.Equal(SocketError.ConnectionRefused, args.SocketError); Assert.True(args.ConnectByNameError is SocketException); Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode); complete.Dispose(); sock.Dispose(); } [Theory] [InlineData(SocketImplementationType.APM)] [InlineData(SocketImplementationType.Async)] [Trait("IPv4", "true")] [Trait("IPv6", "true")] [ActiveIssue(4002, PlatformID.AnyUnix)] public void Socket_StaticConnectAsync_Success(SocketImplementationType type) { Assert.True(Capability.IPv4Support() && Capability.IPv6Support()); int port4, port6; SocketTestServer server4 = SocketTestServer.SocketTestServerFactory(type, IPAddress.Loopback, out port4); SocketTestServer server6 = SocketTestServer.SocketTestServerFactory(type, IPAddress.IPv6Loopback, out port6); SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", port4); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args)); Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); Assert.NotNull(args.ConnectSocket); Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetwork); Assert.True(args.ConnectSocket.Connected); args.ConnectSocket.Dispose(); args.RemoteEndPoint = new DnsEndPoint("localhost", port6); complete.Reset(); Assert.True(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args)); Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.Success, args.SocketError); Assert.Null(args.ConnectByNameError); Assert.NotNull(args.ConnectSocket); Assert.True(args.ConnectSocket.AddressFamily == AddressFamily.InterNetworkV6); Assert.True(args.ConnectSocket.Connected); args.ConnectSocket.Dispose(); server4.Dispose(); server6.Dispose(); } [Fact] public void Socket_StaticConnectAsync_HostNotFound() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("notahostname.invalid.corp.microsoft.com", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); if (!willRaiseEvent) { OnConnectAsyncCompleted(null, args); } Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); AssertHostNotFoundOrNoData(args); Assert.Null(args.ConnectSocket); complete.Dispose(); } [Fact] public void Socket_StaticConnectAsync_ConnectionRefused() { SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("localhost", UnusedPort); args.Completed += OnConnectAsyncCompleted; ManualResetEvent complete = new ManualResetEvent(false); args.UserToken = complete; bool willRaiseEvent = Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args); if (!willRaiseEvent) { OnConnectAsyncCompleted(null, args); } Assert.True(complete.WaitOne(Configuration.PassingTestTimeout), "Timed out while waiting for connection"); Assert.Equal(SocketError.ConnectionRefused, args.SocketError); Assert.True(args.ConnectByNameError is SocketException); Assert.Equal(SocketError.ConnectionRefused, ((SocketException)args.ConnectByNameError).SocketErrorCode); Assert.Null(args.ConnectSocket); complete.Dispose(); } public void CallbackThatShouldNotBeCalled(object sender, SocketAsyncEventArgs args) { Assert.True(false, "This Callback should not be called"); } [Fact] [Trait("IPv6", "true")] public void Socket_StaticConnectAsync_SyncFailure() { Assert.True(Capability.IPv6Support()); // IPv6 required because we use AF.InterNetworkV6 SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new DnsEndPoint("127.0.0.1", UnusedPort, AddressFamily.InterNetworkV6); args.Completed += CallbackThatShouldNotBeCalled; Assert.False(Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, args)); Assert.Equal(SocketError.NoData, args.SocketError); Assert.Null(args.ConnectSocket); } private static void AssertHostNotFoundOrNoData(SocketAsyncEventArgs args) { SocketError errorCode = args.SocketError; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketError: " + errorCode); Assert.True(args.ConnectByNameError is SocketException); errorCode = ((SocketException)args.ConnectByNameError).SocketErrorCode; Assert.True((errorCode == SocketError.HostNotFound) || (errorCode == SocketError.NoData), "SocketError: " + errorCode); } #region GC Finalizer test // This test assumes sequential execution of tests and that it is going to be executed after other tests // that used Sockets. [Fact] public void TestFinalizers() { // Making several passes through the FReachable list. for (int i = 0; i < 3; i++) { GC.Collect(); GC.WaitForPendingFinalizers(); } } #endregion } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Universal charset detector code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 2001 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Shy Shalom <shooshX@gmail.com> * Rudi Pettazzi <rudi.pettazzi@gmail.com> (C# port) * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ namespace UniversalDetector.Core { public class UTF8SMModel : SMModel { private readonly static int[] UTF8_cls = { BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,0,0), // 08 - 0f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 10 - 17 BitPackage.Pack4bits(1,1,1,0,1,1,1,1), // 18 - 1f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 20 - 27 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 28 - 2f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 30 - 37 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 38 - 3f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 40 - 47 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 48 - 4f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 50 - 57 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 58 - 5f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 60 - 67 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 68 - 6f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 70 - 77 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 78 - 7f BitPackage.Pack4bits(2,2,2,2,3,3,3,3), // 80 - 87 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 88 - 8f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 90 - 97 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 98 - 9f BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // a0 - a7 BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // a8 - af BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // b0 - b7 BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // b8 - bf BitPackage.Pack4bits(0,0,6,6,6,6,6,6), // c0 - c7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // c8 - cf BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // d0 - d7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // d8 - df BitPackage.Pack4bits(7,8,8,8,8,8,8,8), // e0 - e7 BitPackage.Pack4bits(8,8,8,8,8,9,8,8), // e8 - ef BitPackage.Pack4bits(10,11,11,11,11,11,11,11), // f0 - f7 BitPackage.Pack4bits(12,13,13,13,14,15,0,0) // f8 - ff }; private readonly static int[] UTF8_st = { BitPackage.Pack4bits(ERROR,START,ERROR,ERROR,ERROR,ERROR, 12, 10),//00-07 BitPackage.Pack4bits( 9, 11, 8, 7, 6, 5, 4, 3),//08-0f BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//10-17 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//18-1f BitPackage.Pack4bits(ITSME,ITSME,ITSME,ITSME,ITSME,ITSME,ITSME,ITSME),//20-27 BitPackage.Pack4bits(ITSME,ITSME,ITSME,ITSME,ITSME,ITSME,ITSME,ITSME),//28-2f BitPackage.Pack4bits(ERROR,ERROR, 5, 5, 5, 5,ERROR,ERROR),//30-37 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//38-3f BitPackage.Pack4bits(ERROR,ERROR,ERROR, 5, 5, 5,ERROR,ERROR),//40-47 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//48-4f BitPackage.Pack4bits(ERROR,ERROR, 7, 7, 7, 7,ERROR,ERROR),//50-57 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//58-5f BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR, 7, 7,ERROR,ERROR),//60-67 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//68-6f BitPackage.Pack4bits(ERROR,ERROR, 9, 9, 9, 9,ERROR,ERROR),//70-77 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//78-7f BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR, 9,ERROR,ERROR),//80-87 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//88-8f BitPackage.Pack4bits(ERROR,ERROR, 12, 12, 12, 12,ERROR,ERROR),//90-97 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//98-9f BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR, 12,ERROR,ERROR),//a0-a7 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//a8-af BitPackage.Pack4bits(ERROR,ERROR, 12, 12, 12,ERROR,ERROR,ERROR),//b0-b7 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR),//b8-bf BitPackage.Pack4bits(ERROR,ERROR,START,START,START,START,ERROR,ERROR),//c0-c7 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ERROR) //c8-cf }; private readonly static int[] UTF8CharLenTable = {0, 1, 0, 0, 0, 0, 2, 3, 3, 3, 4, 4, 5, 5, 6, 6 }; public UTF8SMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, UTF8_cls), 16, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, UTF8_st), UTF8CharLenTable, "UTF-8") { } } public class GB18030SMModel : SMModel { private readonly static int[] GB18030_cls = { BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,0,0), // 08 - 0f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 10 - 17 BitPackage.Pack4bits(1,1,1,0,1,1,1,1), // 18 - 1f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 20 - 27 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 28 - 2f BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // 30 - 37 BitPackage.Pack4bits(3,3,1,1,1,1,1,1), // 38 - 3f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 40 - 47 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 48 - 4f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 50 - 57 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 58 - 5f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 60 - 67 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 68 - 6f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 70 - 77 BitPackage.Pack4bits(2,2,2,2,2,2,2,4), // 78 - 7f BitPackage.Pack4bits(5,6,6,6,6,6,6,6), // 80 - 87 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // 88 - 8f BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // 90 - 97 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // 98 - 9f BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // a0 - a7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // a8 - af BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // b0 - b7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // b8 - bf BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // c0 - c7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // c8 - cf BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // d0 - d7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // d8 - df BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // e0 - e7 BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // e8 - ef BitPackage.Pack4bits(6,6,6,6,6,6,6,6), // f0 - f7 BitPackage.Pack4bits(6,6,6,6,6,6,6,0) // f8 - ff }; private readonly static int[] GB18030_st = { BitPackage.Pack4bits(ERROR,START,START,START,START,START, 3,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ITSME,ITSME),//08-0f BitPackage.Pack4bits(ITSME,ITSME,ITSME,ITSME,ITSME,ERROR,ERROR,START),//10-17 BitPackage.Pack4bits( 4,ERROR,START,START,ERROR,ERROR,ERROR,ERROR),//18-1f BitPackage.Pack4bits(ERROR,ERROR, 5,ERROR,ERROR,ERROR,ITSME,ERROR),//20-27 BitPackage.Pack4bits(ERROR,ERROR,START,START,START,START,START,START) //28-2f }; // To be accurate, the length of class 6 can be either 2 or 4. // But it is not necessary to discriminate between the two since // it is used for frequency analysis only, and we are validating // each code range there as well. So it is safe to set it to be // 2 here. private readonly static int[] GB18030CharLenTable = {0, 1, 1, 1, 1, 1, 2}; public GB18030SMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, GB18030_cls), 7, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, GB18030_st), GB18030CharLenTable, "GB18030") { } } public class BIG5SMModel : SMModel { private readonly static int[] BIG5_cls = { BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,0,0), // 08 - 0f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 10 - 17 BitPackage.Pack4bits(1,1,1,0,1,1,1,1), // 18 - 1f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 20 - 27 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 28 - 2f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 30 - 37 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 38 - 3f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 40 - 47 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 48 - 4f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 50 - 57 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 58 - 5f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 60 - 67 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 68 - 6f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 70 - 77 BitPackage.Pack4bits(2,2,2,2,2,2,2,1), // 78 - 7f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 80 - 87 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 88 - 8f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 90 - 97 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 98 - 9f BitPackage.Pack4bits(4,3,3,3,3,3,3,3), // a0 - a7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // a8 - af BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // b0 - b7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // b8 - bf BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // c0 - c7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // c8 - cf BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // d0 - d7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // d8 - df BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // e0 - e7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // e8 - ef BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // f0 - f7 BitPackage.Pack4bits(3,3,3,3,3,3,3,0) // f8 - ff }; private readonly static int[] BIG5_st = { BitPackage.Pack4bits(ERROR,START,START, 3,ERROR,ERROR,ERROR,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ITSME,ITSME,ITSME,ITSME,ITSME,ERROR),//08-0f BitPackage.Pack4bits(ERROR,START,START,START,START,START,START,START) //10-17 }; private readonly static int[] BIG5CharLenTable = {0, 1, 1, 2, 0}; public BIG5SMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, BIG5_cls), 5, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, BIG5_st), BIG5CharLenTable, "Big5") { } } public class EUCJPSMModel : SMModel { private readonly static int[] EUCJP_cls = { //BitPacket.Pack4bits(5,4,4,4,4,4,4,4), // 00 - 07 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 00 - 07 BitPackage.Pack4bits(4,4,4,4,4,4,5,5), // 08 - 0f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 10 - 17 BitPackage.Pack4bits(4,4,4,5,4,4,4,4), // 18 - 1f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 20 - 27 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 28 - 2f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 30 - 37 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 38 - 3f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 40 - 47 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 48 - 4f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 50 - 57 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 58 - 5f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 60 - 67 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 68 - 6f BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 70 - 77 BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // 78 - 7f BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // 80 - 87 BitPackage.Pack4bits(5,5,5,5,5,5,1,3), // 88 - 8f BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // 90 - 97 BitPackage.Pack4bits(5,5,5,5,5,5,5,5), // 98 - 9f BitPackage.Pack4bits(5,2,2,2,2,2,2,2), // a0 - a7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a8 - af BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b0 - b7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b8 - bf BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c0 - c7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c8 - cf BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d0 - d7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d8 - df BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // e0 - e7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // e8 - ef BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // f0 - f7 BitPackage.Pack4bits(0,0,0,0,0,0,0,5) // f8 - ff }; private readonly static int[] EUCJP_st = { BitPackage.Pack4bits( 3, 4, 3, 5,START,ERROR,ERROR,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ITSME,ITSME,ITSME,ITSME),//08-0f BitPackage.Pack4bits(ITSME,ITSME,START,ERROR,START,ERROR,ERROR,ERROR),//10-17 BitPackage.Pack4bits(ERROR,ERROR,START,ERROR,ERROR,ERROR, 3,ERROR),//18-1f BitPackage.Pack4bits( 3,ERROR,ERROR,ERROR,START,START,START,START) //20-27 }; private readonly static int[] EUCJPCharLenTable = { 2, 2, 2, 3, 1, 0 }; public EUCJPSMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCJP_cls), 6, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCJP_st), EUCJPCharLenTable, "EUC-JP") { } } public class EUCKRSMModel : SMModel { private readonly static int[] EUCKR_cls = { //BitPacket.Pack4bits(0,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,0,0), // 08 - 0f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 10 - 17 BitPackage.Pack4bits(1,1,1,0,1,1,1,1), // 18 - 1f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 20 - 27 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 28 - 2f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 30 - 37 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 38 - 3f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 40 - 47 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 48 - 4f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 50 - 57 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 58 - 5f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 60 - 67 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 68 - 6f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 70 - 77 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 78 - 7f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 80 - 87 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 88 - 8f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 90 - 97 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 98 - 9f BitPackage.Pack4bits(0,2,2,2,2,2,2,2), // a0 - a7 BitPackage.Pack4bits(2,2,2,2,2,3,3,3), // a8 - af BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b0 - b7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b8 - bf BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c0 - c7 BitPackage.Pack4bits(2,3,2,2,2,2,2,2), // c8 - cf BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d0 - d7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d8 - df BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e0 - e7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // e8 - ef BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // f0 - f7 BitPackage.Pack4bits(2,2,2,2,2,2,2,0) // f8 - ff }; private readonly static int[] EUCKR_st = { BitPackage.Pack4bits(ERROR,START, 3,ERROR,ERROR,ERROR,ERROR,ERROR),//00-07 BitPackage.Pack4bits(ITSME,ITSME,ITSME,ITSME,ERROR,ERROR,START,START) //08-0f }; private readonly static int[] EUCKRCharLenTable = { 0, 1, 2, 0 }; public EUCKRSMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCKR_cls), 4, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCKR_st), EUCKRCharLenTable, "EUC-KR") { } } public class EUCTWSMModel : SMModel { private readonly static int[] EUCTW_cls = { BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 00 - 07 BitPackage.Pack4bits(2,2,2,2,2,2,0,0), // 08 - 0f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 10 - 17 BitPackage.Pack4bits(2,2,2,0,2,2,2,2), // 18 - 1f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 20 - 27 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 28 - 2f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 30 - 37 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 38 - 3f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 40 - 47 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 48 - 4f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 50 - 57 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 58 - 5f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 60 - 67 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 68 - 6f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 70 - 77 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 78 - 7f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 80 - 87 BitPackage.Pack4bits(0,0,0,0,0,0,6,0), // 88 - 8f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 90 - 97 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 98 - 9f BitPackage.Pack4bits(0,3,4,4,4,4,4,4), // a0 - a7 BitPackage.Pack4bits(5,5,1,1,1,1,1,1), // a8 - af BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // b0 - b7 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // b8 - bf BitPackage.Pack4bits(1,1,3,1,3,3,3,3), // c0 - c7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // c8 - cf BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // d0 - d7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // d8 - df BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // e0 - e7 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // e8 - ef BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // f0 - f7 BitPackage.Pack4bits(3,3,3,3,3,3,3,0) // f8 - ff }; private readonly static int[] EUCTW_st = { BitPackage.Pack4bits(ERROR,ERROR,START, 3, 3, 3, 4,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ERROR,ERROR,ITSME,ITSME),//08-0f BitPackage.Pack4bits(ITSME,ITSME,ITSME,ITSME,ITSME,ERROR,START,ERROR),//10-17 BitPackage.Pack4bits(START,START,START,ERROR,ERROR,ERROR,ERROR,ERROR),//18-1f BitPackage.Pack4bits( 5,ERROR,ERROR,ERROR,START,ERROR,START,START),//20-27 BitPackage.Pack4bits(START,ERROR,START,START,START,START,START,START) //28-2f }; private readonly static int[] EUCTWCharLenTable = { 0, 0, 1, 2, 2, 2, 3 }; public EUCTWSMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCTW_cls), 7, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, EUCTW_st), EUCTWCharLenTable, "EUC-TW") { } } public class SJISSMModel : SMModel { private readonly static int[] SJIS_cls = { //BitPacket.Pack4bits(0,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 00 - 07 BitPackage.Pack4bits(1,1,1,1,1,1,0,0), // 08 - 0f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 10 - 17 BitPackage.Pack4bits(1,1,1,0,1,1,1,1), // 18 - 1f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 20 - 27 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 28 - 2f BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 30 - 37 BitPackage.Pack4bits(1,1,1,1,1,1,1,1), // 38 - 3f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 40 - 47 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 48 - 4f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 50 - 57 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 58 - 5f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 60 - 67 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 68 - 6f BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // 70 - 77 BitPackage.Pack4bits(2,2,2,2,2,2,2,1), // 78 - 7f BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // 80 - 87 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // 88 - 8f BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // 90 - 97 BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // 98 - 9f //0xa0 is illegal in sjis encoding, but some pages does //contain such byte. We need to be more error forgiven. BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a0 - a7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // a8 - af BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b0 - b7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // b8 - bf BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c0 - c7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // c8 - cf BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d0 - d7 BitPackage.Pack4bits(2,2,2,2,2,2,2,2), // d8 - df BitPackage.Pack4bits(3,3,3,3,3,3,3,3), // e0 - e7 BitPackage.Pack4bits(3,3,3,3,3,4,4,4), // e8 - ef BitPackage.Pack4bits(4,4,4,4,4,4,4,4), // f0 - f7 BitPackage.Pack4bits(4,4,4,4,4,0,0,0) // f8 - ff }; private readonly static int[] SJIS_st = { BitPackage.Pack4bits(ERROR,START,START, 3,ERROR,ERROR,ERROR,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ITSME,ITSME,ITSME,ITSME),//08-0f BitPackage.Pack4bits(ITSME,ITSME,ERROR,ERROR,START,START,START,START) //10-17 }; private readonly static int[] SJISCharLenTable = { 0, 1, 1, 2, 0, 0 }; public SJISSMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, SJIS_cls), 6, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, SJIS_st), SJISCharLenTable, "Shift_JIS") { } } public class UCS2BESMModel : SMModel { private readonly static int[] UCS2BE_cls = { BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 00 - 07 BitPackage.Pack4bits(0,0,1,0,0,2,0,0), // 08 - 0f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 10 - 17 BitPackage.Pack4bits(0,0,0,3,0,0,0,0), // 18 - 1f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 20 - 27 BitPackage.Pack4bits(0,3,3,3,3,3,0,0), // 28 - 2f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 30 - 37 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 38 - 3f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 40 - 47 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 48 - 4f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 50 - 57 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 58 - 5f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 60 - 67 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 68 - 6f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 70 - 77 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 78 - 7f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 80 - 87 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 88 - 8f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 90 - 97 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 98 - 9f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // a0 - a7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // a8 - af BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // b0 - b7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // b8 - bf BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // c0 - c7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // c8 - cf BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // d0 - d7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // d8 - df BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // e0 - e7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // e8 - ef BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // f0 - f7 BitPackage.Pack4bits(0,0,0,0,0,0,4,5) // f8 - ff }; private readonly static int[] UCS2BE_st = { BitPackage.Pack4bits( 5, 7, 7,ERROR, 4, 3,ERROR,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ITSME,ITSME,ITSME,ITSME),//08-0f BitPackage.Pack4bits(ITSME,ITSME, 6, 6, 6, 6,ERROR,ERROR),//10-17 BitPackage.Pack4bits( 6, 6, 6, 6, 6,ITSME, 6, 6),//18-1f BitPackage.Pack4bits( 6, 6, 6, 6, 5, 7, 7,ERROR),//20-27 BitPackage.Pack4bits( 5, 8, 6, 6,ERROR, 6, 6, 6),//28-2f BitPackage.Pack4bits( 6, 6, 6, 6,ERROR,ERROR,START,START) //30-37 }; private readonly static int[] UCS2BECharLenTable = { 2, 2, 2, 0, 2, 2 }; public UCS2BESMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, UCS2BE_cls), 6, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, UCS2BE_st), UCS2BECharLenTable, "UTF-16BE") { } } public class UCS2LESMModel : SMModel { private readonly static int[] UCS2LE_cls = { BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 00 - 07 BitPackage.Pack4bits(0,0,1,0,0,2,0,0), // 08 - 0f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 10 - 17 BitPackage.Pack4bits(0,0,0,3,0,0,0,0), // 18 - 1f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 20 - 27 BitPackage.Pack4bits(0,3,3,3,3,3,0,0), // 28 - 2f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 30 - 37 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 38 - 3f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 40 - 47 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 48 - 4f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 50 - 57 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 58 - 5f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 60 - 67 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 68 - 6f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 70 - 77 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 78 - 7f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 80 - 87 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 88 - 8f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 90 - 97 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // 98 - 9f BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // a0 - a7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // a8 - af BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // b0 - b7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // b8 - bf BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // c0 - c7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // c8 - cf BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // d0 - d7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // d8 - df BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // e0 - e7 BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // e8 - ef BitPackage.Pack4bits(0,0,0,0,0,0,0,0), // f0 - f7 BitPackage.Pack4bits(0,0,0,0,0,0,4,5) // f8 - ff }; private readonly static int[] UCS2LE_st = { BitPackage.Pack4bits( 6, 6, 7, 6, 4, 3,ERROR,ERROR),//00-07 BitPackage.Pack4bits(ERROR,ERROR,ERROR,ERROR,ITSME,ITSME,ITSME,ITSME),//08-0f BitPackage.Pack4bits(ITSME,ITSME, 5, 5, 5,ERROR,ITSME,ERROR),//10-17 BitPackage.Pack4bits( 5, 5, 5,ERROR, 5,ERROR, 6, 6),//18-1f BitPackage.Pack4bits( 7, 6, 8, 8, 5, 5, 5,ERROR),//20-27 BitPackage.Pack4bits( 5, 5, 5,ERROR,ERROR,ERROR, 5, 5),//28-2f BitPackage.Pack4bits( 5, 5, 5,ERROR, 5,ERROR,START,START) //30-37 }; private readonly static int[] UCS2LECharLenTable = { 2, 2, 2, 2, 2, 2 }; public UCS2LESMModel() : base( new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, UCS2LE_cls), 6, new BitPackage(BitPackage.INDEX_SHIFT_4BITS, BitPackage.SHIFT_MASK_4BITS, BitPackage.BIT_SHIFT_4BITS, BitPackage.UNIT_MASK_4BITS, UCS2LE_st), UCS2LECharLenTable, "UTF-16LE") { } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // Authors: // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2007 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System.Collections.Generic; using System.ComponentModel; using System.Drawing.Imaging; using System.Globalization; using System.Linq; using Xunit; namespace System.Drawing.Printing.Tests { public class PrinterSettingsTests { [ConditionalFact(Helpers.IsDrawingSupported)] public void Ctor_Default_Success() { var printerSettings = new PrinterSettings(); Assert.NotNull(printerSettings.DefaultPageSettings); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void CanDuplex_ReturnsExpected() { var printerSettings = new PrinterSettings(); bool canDuplex = printerSettings.CanDuplex; } [ConditionalFact(Helpers.IsDrawingSupported)] public void Copies_Default_ReturnsExpected() { var printerSettings = new PrinterSettings(); int copies = printerSettings.Copies; } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(0)] [InlineData(short.MaxValue)] public void Copies_SetValue_ReturnsExpected(short copies) { var printerSettings = new PrinterSettings() { Copies = copies }; Assert.Equal(copies, printerSettings.Copies); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(-1)] [InlineData(short.MinValue)] public void Copies_SetValue_ThrowsArgumentException(short copies) { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentException>(null, () => printerSettings.Copies = copies); } [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void Collate_Default_ReturnsExpected() { var printerSettings = new PrinterSettings(); bool collate = printerSettings.Collate; } [ConditionalFact(Helpers.IsDrawingSupported)] public void Collate_SetValue_ReturnsExpected() { var printerSettings = new PrinterSettings() { Collate = false }; Assert.False(printerSettings.Collate); } [ConditionalFact(Helpers.IsDrawingSupported)] public void DefaultPageSettings_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.NotNull(printerSettings.DefaultPageSettings); } [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(Duplex.Simplex)] [InlineData(Duplex.Vertical)] [InlineData(Duplex.Horizontal)] public void Duplex_SetValue_ReturnsExpected(Duplex duplex) { var printerSettings = new PrinterSettings() { Duplex = duplex }; Assert.Equal(duplex, printerSettings.Duplex); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.IsDrawingSupported)] [InlineData(Duplex.Default - 1)] [InlineData(Duplex.Horizontal + 1)] [InlineData((Duplex)int.MaxValue)] [InlineData((Duplex)int.MinValue)] public void Duplex_Invalid_ThrowsInvalidEnumArgumentException(Duplex duplex) { var printerSettings = new PrinterSettings(); Assert.ThrowsAny<ArgumentException>(() => printerSettings.Duplex = duplex); } [Fact] public void FromPage_Default_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.Equal(0, printerSettings.FromPage); } [Theory] [InlineData(1)] [InlineData(int.MaxValue)] public void FromPage_SetValue_ReturnsExpected(int pageNumber) { var printerSettings = new PrinterSettings() { FromPage = pageNumber }; Assert.Equal(pageNumber, printerSettings.FromPage); } [Theory] [InlineData(-1)] [InlineData(int.MinValue)] public void FromPage_Invalid_ThrowsArgumentException(int pageNumber) { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentException>(null, () => printerSettings.FromPage = pageNumber); } [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void Static_InstalledPrinters_ReturnsExpected() { Assert.NotNull(PrinterSettings.InstalledPrinters); } [ConditionalFact(Helpers.IsDrawingSupported)] public void IsDefaultPrinter_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.True(printerSettings.IsDefaultPrinter); } [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void IsPlotter_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.False(printerSettings.IsPlotter); } [ConditionalFact(Helpers.IsDrawingSupported)] [ActiveIssue(20884, TestPlatforms.AnyUnix)] public void IsValid_ReturnsExpected() { var printerSettings = new PrinterSettings() { PrinterName = "Invalid Printer" }; Assert.False(printerSettings.IsValid); } [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void LandscapeAngle_ReturnsExpected() { var printerSettings = new PrinterSettings(); int[] validValues = new[] { -90, 0, 90, 270 }; Assert.True(validValues.Contains(printerSettings.LandscapeAngle), $"PrinterSettings.LandscapeAngle ({printerSettings.LandscapeAngle}) must be 0, 90, or 270 degrees."); } [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void MaximumCopies_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.True(printerSettings.MaximumCopies >= 0, $"PrinterSettings.MaximumCopies ({printerSettings.MaximumCopies}) should not be negative."); } [Fact] public void MaximumPage_Default_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.Equal(9999, printerSettings.MaximumPage); } [Theory] [InlineData(20)] [InlineData(int.MaxValue)] public void MaximumPage_SetValue_ReturnsExpected(int maximumPage) { var printerSettings = new PrinterSettings() { MaximumPage = maximumPage }; Assert.Equal(maximumPage, printerSettings.MaximumPage); } [Theory] [InlineData(-1)] [InlineData(int.MinValue)] public void MaximumPage_Invalid_ThrowsArgumentException(int maximumPage) { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentException>(null, () => printerSettings.MaximumPage = maximumPage); } [Fact] public void MinimumPage_Default_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.Equal(0, printerSettings.MinimumPage); } [Theory] [InlineData(20)] [InlineData(int.MaxValue)] public void MinimumPage_SetValue_ReturnsExpected(int minimumPage) { var printerSettings = new PrinterSettings() { MinimumPage = minimumPage }; Assert.Equal(minimumPage, printerSettings.MinimumPage); } [Theory] [InlineData(-1)] [InlineData(int.MinValue)] public void MinimumPage_Invalid_ThrowsArgumentException(int minimumPage) { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentException>(null, () => printerSettings.MinimumPage = minimumPage); } [Fact] public void PrintFileName_SetValue_ReturnsExpected() { var printFileName = "fileName"; var printerSettings = new PrinterSettings() { PrintFileName = printFileName }; Assert.Equal(printFileName, printerSettings.PrintFileName); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [Fact] public void PrintFileName_Null_ThrowsArgumentNullException() { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentNullException>(null, () => printerSettings.PrintFileName = null); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [Fact] public void PrintFileName_Empty_ThrowsArgumentNullException() { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentNullException>(string.Empty, () => printerSettings.PrintFileName = string.Empty); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void PaperSizes_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.NotNull(printerSettings.PaperSizes); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void PaperSources_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.NotNull(printerSettings.PaperSources); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [Theory] [InlineData(PrintRange.AllPages)] [InlineData(PrintRange.CurrentPage)] [InlineData(PrintRange.Selection)] [InlineData(PrintRange.SomePages)] public void PrintRange_SetValue_ReturnsExpected(PrintRange printRange) { var printerSettings = new PrinterSettings() { PrintRange = printRange }; Assert.Equal(printRange, printerSettings.PrintRange); } [Theory] [InlineData(PrintRange.AllPages - 1)] [InlineData(PrintRange.SomePages + 1)] [InlineData((PrintRange)int.MaxValue)] [InlineData((PrintRange)int.MinValue)] public void PrintRange_Invalid_ThrowsInvalidEnumArgumentException(PrintRange printRange) { var printerSettings = new PrinterSettings(); Assert.ThrowsAny<ArgumentException>(() => printerSettings.PrintRange = printRange); } [Fact] public void PrintToFile_SetValue_ReturnsExpected() { var printToFile = true; var printerSettings = new PrinterSettings() { PrintToFile = printToFile }; Assert.Equal(printToFile, printerSettings.PrintToFile); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [Theory] [InlineData("")] [InlineData("My printer")] public void PrinterName_SetValue_ReturnsExpected(string printerName) { var printerSettings = new PrinterSettings() { PrinterName = printerName }; Assert.Equal(printerName, printerSettings.PrinterName); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void PrinterName_Null_ReturnsExpected() { var printerSettings = new PrinterSettings() { PrinterName = null }; Assert.NotNull(printerSettings.PrinterName); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void PrinterResolutions_ReturnsExpected() { var printerSettings = new PrinterSettings(); Assert.NotNull(printerSettings.PrinterResolutions); } public static IEnumerable<object[]> IsDirectPrintingSupported_ImageFormatSupported_TestData() { yield return new object[] { ImageFormat.Jpeg }; yield return new object[] { ImageFormat.Png }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalTheory(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] [MemberData(nameof(IsDirectPrintingSupported_ImageFormatSupported_TestData))] public void IsDirectPrintingSupported_ImageFormatSupported_ReturnsExpected(ImageFormat imageFormat) { var printerSettings = new PrinterSettings(); bool supported = printerSettings.IsDirectPrintingSupported(imageFormat); } public static IEnumerable<object[]> IsDirectPrintingSupported_ImageFormatNotSupported_TestData() { yield return new object[] { ImageFormat.Emf }; yield return new object[] { ImageFormat.Exif }; yield return new object[] { ImageFormat.Gif }; yield return new object[] { ImageFormat.Icon }; yield return new object[] { ImageFormat.MemoryBmp }; yield return new object[] { ImageFormat.Tiff }; yield return new object[] { ImageFormat.Wmf }; yield return new object[] { ImageFormat.Bmp }; } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [Theory] [MemberData(nameof(IsDirectPrintingSupported_ImageFormatNotSupported_TestData))] public void IsDirectPrintingSupported_ImageFormatNotSupported_ReturnsExpected(ImageFormat imageFormat) { var printerSettings = new PrinterSettings(); Assert.False(printerSettings.IsDirectPrintingSupported(imageFormat)); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void IsDirectPrintingSupported_ImageNotSupported_ReturnsExpected() { using (var bitmap = new Bitmap(10, 10)) { var printerSettings = new PrinterSettings(); Assert.False(printerSettings.IsDirectPrintingSupported(bitmap)); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported)] public void SupportsColor_ReturnsExpected() { var printerSettings = new PrinterSettings(); bool supportsColor = printerSettings.SupportsColor; } [Theory] [InlineData(20)] [InlineData(int.MaxValue)] public void ToPage_SetValue_ReturnsExpected(int toPage) { var printerSettings = new PrinterSettings() { ToPage = toPage }; Assert.Equal(toPage, printerSettings.ToPage); } [Theory] [InlineData(-1)] [InlineData(int.MinValue)] public void ToPage_Invalid_ThrowsArgumentException(int toPage) { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentException>(null, () => printerSettings.ToPage = toPage); } [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void Clone_Success() { var printerSettings = new PrinterSettings(); PrinterSettings clone = Assert.IsAssignableFrom<PrinterSettings>(printerSettings.Clone()); Assert.False(ReferenceEquals(clone, printerSettings)); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void CreateMeasurementGraphics_Default_ReturnsExpected() { var printerSettings = new PrinterSettings(); using (Graphics graphic = printerSettings.CreateMeasurementGraphics()) { Assert.NotNull(graphic); Assert.Equal(printerSettings.DefaultPageSettings.Bounds.X, graphic.VisibleClipBounds.X, 0); Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Y, graphic.VisibleClipBounds.Y, 0); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void CreateMeasurementGraphics_Bool_ReturnsExpected() { var printerSettings = new PrinterSettings(); using (Graphics graphic = printerSettings.CreateMeasurementGraphics(true)) { Assert.NotNull(graphic); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void CreateMeasurementGraphics_PageSettings_ReturnsExpected() { var printerSettings = new PrinterSettings(); var pageSettings = new PageSettings(); using (Graphics graphic = printerSettings.CreateMeasurementGraphics(pageSettings)) { Assert.NotNull(graphic); Assert.Equal(printerSettings.DefaultPageSettings.Bounds.X, graphic.VisibleClipBounds.X, 0); Assert.Equal(printerSettings.DefaultPageSettings.Bounds.Y, graphic.VisibleClipBounds.Y, 0); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.AnyInstalledPrinters, Helpers.IsDrawingSupported, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void CreateMeasurementGraphics_PageSettingsBool_ReturnsExpected() { var printerSettings = new PrinterSettings(); var pageSettings = new PageSettings(); using (Graphics graphic = printerSettings.CreateMeasurementGraphics(pageSettings, true)) { Assert.NotNull(graphic); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Height, graphic.VisibleClipBounds.Height, 0); Assert.Equal(printerSettings.DefaultPageSettings.PrintableArea.Width, graphic.VisibleClipBounds.Width, 0); } } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported, Helpers.WindowsRS3OrEarlier)] // RS4 failures: https://github.com/dotnet/corefx/issues/29858 public void CreateMeasurementGraphics_Null_ThrowsNullReferenceException() { var printerSettings = new PrinterSettings(); Assert.Throws<NullReferenceException>(() => printerSettings.CreateMeasurementGraphics(null)); Assert.Throws<NullReferenceException>(() => printerSettings.CreateMeasurementGraphics(null, true)); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void GetHdevmode_ReturnsExpected() { var printerSettings = new PrinterSettings(); IntPtr handle = IntPtr.Zero; handle = printerSettings.GetHdevmode(); Assert.NotEqual(IntPtr.Zero, handle); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void GetHdevmode_PageSettings_ReturnsExpected() { var printerSettings = new PrinterSettings(); var pageSettings = new PageSettings(); IntPtr handle = IntPtr.Zero; handle = printerSettings.GetHdevmode(pageSettings); Assert.NotEqual(IntPtr.Zero, handle); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void GetHdevmode_Null_ThrowsNullReferenceException() { var printerSettings = new PrinterSettings(); Assert.Throws<NullReferenceException>(() => printerSettings.GetHdevmode(null)); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void GetHdevnames_ReturnsExpected() { var printerSettings = new PrinterSettings(); IntPtr handle = IntPtr.Zero; handle = printerSettings.GetHdevnames(); Assert.NotEqual(IntPtr.Zero, handle); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(typeof(PrinterSettingsTests), nameof(CanTestSetHdevmode_IntPtr_Success))] public void SetHdevmode_IntPtr_Success() { string printerName = GetNameOfTestPrinterSuitableForDevModeTesting(); var printerSettings = new PrinterSettings() { PrinterName = printerName, Copies = 3 }; var newPrinterSettings = new PrinterSettings() { PrinterName = printerName, Copies = 6 }; IntPtr handle = printerSettings.GetHdevmode(); newPrinterSettings.SetHdevmode(handle); Assert.Equal(printerSettings.Copies, newPrinterSettings.Copies); Assert.Equal(printerSettings.Collate, newPrinterSettings.Collate); Assert.Equal(printerSettings.Duplex, newPrinterSettings.Duplex); } public static bool CanTestSetHdevmode_IntPtr_Success => Helpers.GetIsDrawingSupported() && GetNameOfTestPrinterSuitableForDevModeTesting() != null; private static string GetNameOfTestPrinterSuitableForDevModeTesting() { foreach (string candidate in s_TestPrinterNames) { PrinterSettings printerSettings = new PrinterSettings() { PrinterName = candidate }; if (printerSettings.IsValid) return candidate; } return null; } private static readonly string[] s_TestPrinterNames = { // Our method of testing this api requires a printer that supports multi-copy printing, collating and duplex settings. Not all printers // support these so rather than trust the machine running the test to have configured such a printer as the default, use the name of // a known compliant printer that ships with Windows 10. "Microsoft Print to PDF", "Microsoft XPS Document Writer", // Backup for older Windows }; [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void GetHdevmode_Zero_ThrowsArgumentException() { var printerSettings = new PrinterSettings(); AssertExtensions.Throws<ArgumentException>(null, () => printerSettings.SetHdevmode(IntPtr.Zero)); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void SetHdevnames_IntPtr_Success() { var printerSettings = new PrinterSettings(); var newPrinterSettings = new PrinterSettings(); IntPtr handle = printerSettings.GetHdevnames(); newPrinterSettings.SetHdevnames(handle); Assert.Equal(newPrinterSettings.PrinterName, printerSettings.PrinterName); } [ActiveIssue(20884, TestPlatforms.AnyUnix)] [ConditionalFact(Helpers.IsDrawingSupported)] public void ToString_ReturnsExpected() { var printerSettings = new PrinterSettings(); var expected = "[PrinterSettings " + printerSettings.PrinterName + " Copies=" + printerSettings.Copies.ToString(CultureInfo.InvariantCulture) + " Collate=" + printerSettings.Collate.ToString(CultureInfo.InvariantCulture) + " Duplex=" + printerSettings.Duplex.ToString() + " FromPage=" + printerSettings.FromPage.ToString(CultureInfo.InvariantCulture) + " LandscapeAngle=" + printerSettings.LandscapeAngle.ToString(CultureInfo.InvariantCulture) + " MaximumCopies=" + printerSettings.MaximumCopies.ToString(CultureInfo.InvariantCulture) + " OutputPort=" + printerSettings.PrintFileName.ToString(CultureInfo.InvariantCulture) + " ToPage=" + printerSettings.ToPage.ToString(CultureInfo.InvariantCulture) + "]"; Assert.Equal(expected, printerSettings.ToString()); } } }
// // Batcher.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2014 Xamarin Inc // Copyright (c) 2014 .NET Foundation // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // // // Copyright (c) 2014 Couchbase, Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Couchbase.Lite.Util; using System.Collections.Concurrent; namespace Couchbase.Lite.Support { /// <summary> /// Utility that queues up objects until the queue fills up or a time interval elapses, /// then passes all the objects at once to a client-supplied processor block. /// </summary> internal class Batcher<T> { #region Constants private const string TAG = "Batcher"; #endregion #region Variables private readonly TaskFactory _workExecutor; private Task _flushFuture; private readonly int _capacity; private readonly int _delay; private int _scheduledDelay; private readonly Action<IList<T>> _processor; private bool _scheduled; private DateTime _lastProcessedTime; private CancellationTokenSource _cancellationSource; private ConcurrentQueue<T> _inbox = new ConcurrentQueue<T>(); private object _scheduleLocker = new object(); #endregion #region Constructor /// <summary>Constructor</summary> /// <param name="workExecutor">the work executor that performs actual work</param> /// <param name="capacity">The maximum number of objects to batch up. If the queue reaches this size, the queued objects will be sent to the processor immediately. /// </param> /// <param name="delay">The maximum waiting time to collect objects before processing them. In some circumstances objects will be processed sooner. /// </param> /// <param name="processor">The callback/block that will be called to process the objects. /// </param> /// <param name="tokenSource">The token source to use to create the token to cancel this Batcher object</param> public Batcher(TaskFactory workExecutor, int capacity, int delay, Action<IList<T>> processor, CancellationTokenSource tokenSource = null) { Log.D(TAG, "New batcher created with capacity: {0}, delay: {1}", capacity, delay); _workExecutor = workExecutor; _cancellationSource = tokenSource; _capacity = capacity; _delay = delay; _processor = processor; } #endregion #region Public Methods public void ProcessNow() { Log.V(TAG, "ProcessNow() called"); _scheduled = false; var amountToTake = Math.Min(_capacity, _inbox.Count); List<T> toProcess = new List<T>(); T nextObj; int i = 0; while(i++ < amountToTake && _inbox.TryDequeue(out nextObj)) { toProcess.Add(nextObj); } if (toProcess != null && toProcess.Count > 0) { Log.D(TAG, "invoking processor with " + toProcess.Count + " items "); _processor(toProcess); } else { Log.D(TAG, "nothing to process"); } _lastProcessedTime = DateTime.UtcNow; Log.D(TAG, "Set lastProcessedTime to {0}", _lastProcessedTime.ToString()); if (_inbox.Count > 0) { ScheduleWithDelay(DelayToUse()); } } public void QueueObjects(IList<T> objects) { if (objects == null || objects.Count == 0) { return; } Log.V(TAG, "QueueObjects called with {0} objects", objects.Count); foreach (var obj in objects) { _inbox.Enqueue(obj); } ScheduleWithDelay(DelayToUse()); } /// <summary>Adds an object to the queue.</summary> public void QueueObject(T o) { var objects = new List<T> { o }; QueueObjects(objects); } /// <summary>Sends queued objects to the processor block (up to the capacity).</summary> public void Flush() { ScheduleWithDelay(DelayToUse()); } /// <summary>Sends _all_ the queued objects at once to the processor block.</summary> public void FlushAll() { while(_inbox.Count > 0) { Unschedule(); ProcessNow(); _lastProcessedTime = DateTime.UtcNow; } } /// <summary>Number of items to be processed.</summary> public int Count() { return _inbox.Count; } /// <summary>Empties the queue without processing any of the objects in it.</summary> public void Clear() { Log.V(TAG, "clear() called, setting _jobQueue to null"); Unschedule(); var itemCount = _inbox.Count; _inbox = new ConcurrentQueue<T>(); Log.D(TAG, "Discarded {0} items", itemCount); } #endregion #region Internal Methods /// <summary> /// Calculates the delay to use when scheduling the next batch of objects to process. /// </summary> /// <remarks> /// There is a balance required between clearing down the input queue as fast as possible /// and not exhausting downstream system resources such as sockets and http response buffers /// by processing too many batches concurrently. /// </remarks> /// <returns>The delay o use.</returns> internal int DelayToUse() { if(_inbox.Count > _capacity) { return 0; } var delta = (int)(DateTime.UtcNow - _lastProcessedTime).TotalMilliseconds; var delayToUse = delta >= _delay ? 0 : _delay; Log.V(TAG, "DelayToUse() delta: {0}, delayToUse: {1}, delay: {2} [last: {3}]", delta, delayToUse, _delay, _lastProcessedTime.ToString()); return delayToUse; } #endregion #region Private Methods private void ScheduleWithDelay(int suggestedDelay) { lock(_scheduleLocker) { if (_scheduled) { Log.V(TAG, "ScheduleWithDelay called with delay: {0} ms but already scheduled", suggestedDelay); } if (_scheduled && (suggestedDelay < _scheduledDelay)) { Log.V(TAG, "Unscheduling"); Unschedule(); } if (!_scheduled) { _scheduled = true; _scheduledDelay = suggestedDelay; Log.D(TAG, "ScheduleWithDelay called with delay: {0} ms, scheduler: {1}/{2}", suggestedDelay, _workExecutor.Scheduler.GetType().Name, ((SingleTaskThreadpoolScheduler)_workExecutor.Scheduler).ScheduledTasks.Count()); _cancellationSource = new CancellationTokenSource(); _flushFuture = Task.Delay(suggestedDelay).ContinueWith((t) => { if (_cancellationSource != null && !(_cancellationSource.IsCancellationRequested)) { ProcessNow(); } return true; }, _cancellationSource.Token, TaskContinuationOptions.None, _workExecutor.Scheduler); } else { if (_flushFuture == null || _flushFuture.IsCompleted) throw new InvalidOperationException("Flushfuture missing despite scheduled."); } } } private void Unschedule() { lock(_scheduleLocker) { _scheduled = false; if (_cancellationSource != null) { try { _cancellationSource.Cancel(true); } catch (Exception) { // Swallow it. } _cancellationSource = null; } } } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.Serialization; using System.Text; using System; using System.Diagnostics.Contracts; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // [Serializable] internal class DecoderNLS : Decoder, ISerializable { // Remember our encoding protected Encoding m_encoding; [NonSerialized] protected bool m_mustFlush; [NonSerialized] internal bool m_throwOnOverflow; [NonSerialized] internal int m_bytesUsed; #region Serialization // Constructor called by serialization. called during deserialization. internal DecoderNLS(SerializationInfo info, StreamingContext context) { throw new NotSupportedException( String.Format( System.Globalization.CultureInfo.CurrentCulture, Environment.GetResourceString("NotSupported_TypeCannotDeserialized"), this.GetType())); } // ISerializable implementation. called during serialization. void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { SerializeDecoder(info); info.AddValue("encoding", this.m_encoding); info.SetType(typeof(Encoding.DefaultDecoder)); } #endregion Serialization internal DecoderNLS(Encoding encoding) { this.m_encoding = encoding; this.m_fallback = this.m_encoding.DecoderFallback; this.Reset(); } // This is used by our child deserializers internal DecoderNLS() { this.m_encoding = null; this.Reset(); } public override void Reset() { if (m_fallbackBuffer != null) m_fallbackBuffer.Reset(); } public override unsafe int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override unsafe int GetCharCount(byte[] bytes, int index, int count, bool flush) { // Validate Parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (index < 0 || count < 0) throw new ArgumentOutOfRangeException((index < 0 ? nameof(index) : nameof(count)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - index < count) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid null fixed problem if (bytes.Length == 0) bytes = new byte[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) return GetCharCount(pBytes + index, count, flush); } public unsafe override int GetCharCount(byte* bytes, int count, bool flush) { // Validate parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Remember the flush this.m_mustFlush = flush; this.m_throwOnOverflow = true; // By default just call the encoding version, no flush by default return m_encoding.GetCharCount(bytes, count, this); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex, false); } public override unsafe int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { // Validate Parameters if (bytes == null || chars == null) throw new ArgumentNullException(bytes == null ? nameof(bytes) : nameof(chars), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (charIndex < 0 || charIndex > chars.Length) throw new ArgumentOutOfRangeException(nameof(charIndex), Environment.GetResourceString("ArgumentOutOfRange_Index")); Contract.EndContractBlock(); // Avoid empty input fixed problem if (bytes.Length == 0) bytes = new byte[1]; int charCount = chars.Length - charIndex; if (chars.Length == 0) chars = new char[1]; // Just call pointer version fixed (byte* pBytes = &bytes[0]) fixed (char* pChars = &chars[0]) // Remember that charCount is # to decode, not size of array return GetChars(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush); } public unsafe override int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate parameters if (chars == null || bytes == null) throw new ArgumentNullException((chars == null ? nameof(chars) : nameof(bytes)), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // Remember our flush m_mustFlush = flush; m_throwOnOverflow = true; // By default just call the encoding's version return m_encoding.GetChars(bytes, byteCount, chars, charCount, this); } // This method is used when the output buffer might not be big enough. // Just call the pointer version. (This gets chars) public override unsafe void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), Environment.GetResourceString("ArgumentNull_Array")); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), Environment.GetResourceString("ArgumentOutOfRange_IndexCountBuffer")); Contract.EndContractBlock(); // Avoid empty input problem if (bytes.Length == 0) bytes = new byte[1]; if (chars.Length == 0) chars = new char[1]; // Just call the pointer version (public overrides can't do this) fixed (byte* pBytes = &bytes[0]) { fixed (char* pChars = &chars[0]) { Convert(pBytes + byteIndex, byteCount, pChars + charIndex, charCount, flush, out bytesUsed, out charsUsed, out completed); } } } // This is the version that used pointers. We call the base encoding worker function // after setting our appropriate internal variables. This is getting chars public unsafe override void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), Environment.GetResourceString("ArgumentNull_Array")); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum")); Contract.EndContractBlock(); // We don't want to throw this.m_mustFlush = flush; this.m_throwOnOverflow = false; this.m_bytesUsed = 0; // Do conversion charsUsed = this.m_encoding.GetChars(bytes, byteCount, chars, charCount, this); bytesUsed = this.m_bytesUsed; // Its completed if they've used what they wanted AND if they didn't want flush or if we are flushed completed = (bytesUsed == byteCount) && (!flush || !this.HasState) && (m_fallbackBuffer == null || m_fallbackBuffer.Remaining == 0); // Our data thingys are now full, we can return } public bool MustFlush { get { return m_mustFlush; } } // Anything left in our decoder? internal virtual bool HasState { get { return false; } } // Allow encoding to clear our must flush instead of throwing (in ThrowCharsOverflow) internal void ClearMustFlush() { m_mustFlush = false; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics.X86; using System.Runtime.Intrinsics; namespace IntelHardwareIntrinsicTest { class Program { const int Pass = 100; const int Fail = 0; static unsafe int Main(string[] args) { int testResult = Pass; if (Avx.IsSupported) { using (TestTable<float> floatTable = new TestTable<float>(new float[8] { 1, -5, 100, 0, 1, -5, 100, 0 }, new float[8] { 22, -1, -50, 0, 22, -1, -50, 0 }, new float[8])) { var vf1 = Unsafe.Read<Vector256<float>>(floatTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<float>>(floatTable.inArray2Ptr); // SDDD SDDD var vf3 = Avx.Blend(vf1, vf2, 1); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((x, y, z) => (z[0] == y[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3]) && (z[4] == x[4]) && (z[5] == x[5]) && (z[6] == x[6]) && (z[7] == x[7]))) { Console.WriteLine("0Avx Blend failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // DSDD DDDD vf3 = Avx.Blend(vf1, vf2, 2); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((x, y, z) => (z[0] == x[0]) && (z[1] == y[1]) && (z[2] == x[2]) && (z[3] == x[3]) && (z[4] == x[4]) && (z[5] == x[5]) && (z[6] == x[6]) && (z[7] == x[7]))) { Console.WriteLine("Avx Blend failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // DDSD DDDD vf3 = Avx.Blend(vf1, vf2, 4); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((x, y, z) => (z[0] == x[0]) && (z[1] == x[1]) && (z[2] == y[2]) && (z[3] == x[3]) && (z[4] == x[4]) && (z[5] == x[5]) && (z[6] == x[6]) && (z[7] == x[7]))) { Console.WriteLine("Avx Blend failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // SDSD SDSD vf3 = Avx.Blend(vf1, vf2, 85); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((x, y, z) => (z[0] == y[0]) && (z[1] == x[1]) && (z[2] == y[2]) && (z[3] == x[3]) && (z[4] == y[4]) && (z[5] == x[5]) && (z[6] == y[6]) && (z[7] == x[7]))) { Console.WriteLine("Avx Blend failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // SDDD DDDD vf3 = (Vector256<float>)typeof(Avx).GetMethod(nameof(Avx.Blend), new Type[] { vf1.GetType(), vf2.GetType(), typeof(byte) }).Invoke(null, new object[] { vf1, vf2, (byte)(1) }); Unsafe.Write(floatTable.outArrayPtr, vf3); if (!floatTable.CheckResult((x, y, z) => (z[0] == y[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3]) && (z[4] == x[4]) && (z[5] == x[5]) && (z[6] == x[6]) && (z[7] == x[7]))) { Console.WriteLine("Avx Blend failed on float:"); foreach (var item in floatTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } using (TestTable<double> doubleTable = new TestTable<double>(new double[4] { 1, -5, 100, 0 }, new double[4] { 22, -1, -50, 0 }, new double[4])) { var vf1 = Unsafe.Read<Vector256<double>>(doubleTable.inArray1Ptr); var vf2 = Unsafe.Read<Vector256<double>>(doubleTable.inArray2Ptr); // DD DD var vf3 = Avx.Blend(vf1, vf2, 0); Unsafe.Write(doubleTable.outArrayPtr, vf3); if (!doubleTable.CheckResult((x, y, z) => (z[0] == x[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3]))) { Console.WriteLine("Avx Blend failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // SD DD vf3 = Avx.Blend(vf1, vf2, 1); Unsafe.Write(doubleTable.outArrayPtr, vf3); if (!doubleTable.CheckResult((x, y, z) => (z[0] == y[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3]))) { Console.WriteLine("Avx Blend failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // DS DD vf3 = Avx.Blend(vf1, vf2, 2); Unsafe.Write(doubleTable.outArrayPtr, vf3); if (!doubleTable.CheckResult((x, y, z) => (z[0] == x[0]) && (z[1] == y[1]) && (z[2] == x[2]) && (z[3] == x[3]))) { Console.WriteLine("Avx Blend failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // SS DD vf3 = Avx.Blend(vf1, vf2, 51); Unsafe.Write(doubleTable.outArrayPtr, vf3); if (!doubleTable.CheckResult((x, y, z) => (z[0] == y[0]) && (z[1] == y[1]) && (z[2] == x[2]) && (z[3] == x[3]))) { Console.WriteLine("Avx Blend failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } // DD DD vf3 = (Vector256<double>)typeof(Avx).GetMethod(nameof(Avx.Blend), new Type[] { vf1.GetType(), vf2.GetType(), typeof(byte) }).Invoke(null, new object[] { vf1, vf2, (byte)(0) }); Unsafe.Write(doubleTable.outArrayPtr, vf3); if (!doubleTable.CheckResult((x, y, z) => (z[0] == x[0]) && (z[1] == x[1]) && (z[2] == x[2]) && (z[3] == x[3]))) { Console.WriteLine("Avx Blend failed on double:"); foreach (var item in doubleTable.outArray) { Console.Write(item + ", "); } Console.WriteLine(); testResult = Fail; } } } return testResult; } public unsafe struct TestTable<T> : IDisposable where T : struct { public T[] inArray1; public T[] inArray2; public T[] outArray; public void* inArray1Ptr => inHandle1.AddrOfPinnedObject().ToPointer(); public void* inArray2Ptr => inHandle2.AddrOfPinnedObject().ToPointer(); public void* outArrayPtr => outHandle.AddrOfPinnedObject().ToPointer(); GCHandle inHandle1; GCHandle inHandle2; GCHandle outHandle; public TestTable(T[] a, T[] b, T[] c) { this.inArray1 = a; this.inArray2 = b; this.outArray = c; inHandle1 = GCHandle.Alloc(inArray1, GCHandleType.Pinned); inHandle2 = GCHandle.Alloc(inArray2, GCHandleType.Pinned); outHandle = GCHandle.Alloc(outArray, GCHandleType.Pinned); } public bool CheckResult(Func<T[], T[], T[], bool> check) { return check(inArray1, inArray2, outArray); } public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using NodaTime; using NUnit.Framework; using QuantConnect.Algorithm; using QuantConnect.Algorithm.Selection; using QuantConnect.AlgorithmFactory.Python.Wrappers; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Data.Auxiliary; using QuantConnect.Data.Consolidators; using QuantConnect.Data.Custom; using QuantConnect.Data.Custom.IconicTypes; using QuantConnect.Data.Market; using QuantConnect.Data.UniverseSelection; using QuantConnect.Lean.Engine.DataFeeds; using QuantConnect.Securities; using QuantConnect.Tests.Engine.DataFeeds; using QuantConnect.Util; using Bitcoin = QuantConnect.Algorithm.CSharp.LiveTradingFeaturesAlgorithm.Bitcoin; using HistoryRequest = QuantConnect.Data.HistoryRequest; namespace QuantConnect.Tests.Algorithm { [TestFixture] public class AlgorithmAddDataTests { [Test] public void DefaultDataFeeds_CanBeOverwritten_Successfully() { var algo = new QCAlgorithm(); algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); // forex defult - should be quotebar var forexTrade = algo.AddForex("EURUSD"); Assert.IsTrue(forexTrade.Subscriptions.Count() == 1); Assert.IsTrue(GetMatchingSubscription(forexTrade, typeof(QuoteBar)) != null); // Change Config.Set("security-data-feeds", "{ Forex: [\"Trade\"] }"); var dataFeedsConfigString = Config.Get("security-data-feeds"); Dictionary<SecurityType, List<TickType>> dataFeeds = new Dictionary<SecurityType, List<TickType>>(); if (dataFeedsConfigString != string.Empty) { dataFeeds = JsonConvert.DeserializeObject<Dictionary<SecurityType, List<TickType>>>(dataFeedsConfigString); } algo.SetAvailableDataTypes(dataFeeds); // new forex - should be tradebar var forexQuote = algo.AddForex("EURUSD"); Assert.IsTrue(forexQuote.Subscriptions.Count() == 1); Assert.IsTrue(GetMatchingSubscription(forexQuote, typeof(TradeBar)) != null); // reset to empty string, affects other tests because config is static Config.Set("security-data-feeds", ""); } [Test] public void DefaultDataFeeds_AreAdded_Successfully() { var algo = new QCAlgorithm(); algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); // forex var forex = algo.AddSecurity(SecurityType.Forex, "eurusd"); Assert.IsTrue(forex.Subscriptions.Count() == 1); Assert.IsTrue(GetMatchingSubscription(forex, typeof(QuoteBar)) != null); // equity high resolution var equityMinute = algo.AddSecurity(SecurityType.Equity, "goog"); Assert.IsTrue(equityMinute.Subscriptions.Count() == 2); Assert.IsTrue(GetMatchingSubscription(equityMinute, typeof(TradeBar)) != null); Assert.IsTrue(GetMatchingSubscription(equityMinute, typeof(QuoteBar)) != null); // equity low resolution var equityDaily = algo.AddSecurity(SecurityType.Equity, "goog", Resolution.Daily); Assert.IsTrue(equityDaily.Subscriptions.Count() == 1); Assert.IsTrue(GetMatchingSubscription(equityDaily, typeof(TradeBar)) != null); // option var option = algo.AddSecurity(SecurityType.Option, "goog"); Assert.IsTrue(option.Subscriptions.Count() == 1); Assert.IsTrue(GetMatchingSubscription(option, typeof(ZipEntryName)) != null); // cfd var cfd = algo.AddSecurity(SecurityType.Cfd, "abc"); Assert.IsTrue(cfd.Subscriptions.Count() == 1); Assert.IsTrue(GetMatchingSubscription(cfd, typeof(QuoteBar)) != null); // future var future = algo.AddSecurity(SecurityType.Future, "ES"); Assert.IsTrue(future.Subscriptions.Count() == 1); Assert.IsTrue(future.Subscriptions.FirstOrDefault(x => typeof(ZipEntryName).IsAssignableFrom(x.Type)) != null); // Crypto high resolution var cryptoMinute = algo.AddSecurity(SecurityType.Equity, "goog"); Assert.IsTrue(cryptoMinute.Subscriptions.Count() == 2); Assert.IsTrue(GetMatchingSubscription(cryptoMinute, typeof(TradeBar)) != null); Assert.IsTrue(GetMatchingSubscription(cryptoMinute, typeof(QuoteBar)) != null); // Crypto low resolution var cryptoHourly = algo.AddSecurity(SecurityType.Crypto, "btcusd", Resolution.Hour); Assert.IsTrue(cryptoHourly.Subscriptions.Count() == 2); Assert.IsTrue(GetMatchingSubscription(cryptoHourly, typeof(TradeBar)) != null); Assert.IsTrue(GetMatchingSubscription(cryptoHourly, typeof(QuoteBar)) != null); } [Test] public void CustomDataTypes_AreAddedToSubscriptions_Successfully() { var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); // Add a bitcoin subscription qcAlgorithm.AddData<Bitcoin>("BTC"); var bitcoinSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Type == typeof(Bitcoin)); Assert.AreEqual(bitcoinSubscription.Type, typeof(Bitcoin)); // Add a quandl subscription qcAlgorithm.AddData<Quandl>("EURCAD"); var quandlSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Type == typeof(Quandl)); Assert.AreEqual(quandlSubscription.Type, typeof(Quandl)); } [Test] public void OnEndOfTimeStepSeedsUnderlyingSecuritiesThatHaveNoData() { var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm, new MockDataFeed())); qcAlgorithm.SetLiveMode(true); var testHistoryProvider = new TestHistoryProvider(); qcAlgorithm.HistoryProvider = testHistoryProvider; var option = qcAlgorithm.AddSecurity(SecurityType.Option, testHistoryProvider.underlyingSymbol); var option2 = qcAlgorithm.AddSecurity(SecurityType.Option, testHistoryProvider.underlyingSymbol2); Assert.IsFalse(qcAlgorithm.Securities.ContainsKey(option.Symbol.Underlying)); Assert.IsFalse(qcAlgorithm.Securities.ContainsKey(option2.Symbol.Underlying)); qcAlgorithm.OnEndOfTimeStep(); var data = qcAlgorithm.Securities[testHistoryProvider.underlyingSymbol].GetLastData(); var data2 = qcAlgorithm.Securities[testHistoryProvider.underlyingSymbol2].GetLastData(); Assert.IsNotNull(data); Assert.IsNotNull(data2); Assert.AreEqual(data.Price, 2); Assert.AreEqual(data2.Price, 3); } [Test, Parallelizable(ParallelScope.Self)] public void OnEndOfTimeStepDoesNotThrowWhenSeedsSameUnderlyingForTwoSecurities() { var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm, new MockDataFeed())); qcAlgorithm.SetLiveMode(true); var testHistoryProvider = new TestHistoryProvider(); qcAlgorithm.HistoryProvider = testHistoryProvider; var option = qcAlgorithm.AddOption(testHistoryProvider.underlyingSymbol); var symbol = Symbol.CreateOption(testHistoryProvider.underlyingSymbol, Market.USA, OptionStyle.American, OptionRight.Call, 1, new DateTime(2015, 12, 24)); var symbol2 = Symbol.CreateOption(testHistoryProvider.underlyingSymbol, Market.USA, OptionStyle.American, OptionRight.Put, 1, new DateTime(2015, 12, 24)); var optionContract = qcAlgorithm.AddOptionContract(symbol); var optionContract2 = qcAlgorithm.AddOptionContract(symbol2); qcAlgorithm.OnEndOfTimeStep(); var data = qcAlgorithm.Securities[testHistoryProvider.underlyingSymbol].GetLastData(); Assert.AreEqual(testHistoryProvider.LastResolutionRequest, Resolution.Minute); Assert.IsNotNull(data); Assert.AreEqual(data.Price, 2); } [TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Cfd, false, true)] [TestCase("BTCUSD", typeof(IndexedLinkedData), SecurityType.Crypto, false, true)] [TestCase("CL", typeof(IndexedLinkedData), SecurityType.Future, false, true)] [TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Forex, false, true)] [TestCase("AAPL", typeof(IndexedLinkedData), SecurityType.Equity, true, true)] [TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Cfd, false, false)] [TestCase("BTCUSD", typeof(UnlinkedData), SecurityType.Crypto, false, false)] [TestCase("CL", typeof(UnlinkedData), SecurityType.Future, false, false)] [TestCase("AAPL", typeof(UnlinkedData), SecurityType.Equity, true, false)] [TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Forex, false, false)] public void AddDataSecuritySymbolWithUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped) { SymbolCache.Clear(); var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); Security asset; switch (securityType) { case SecurityType.Cfd: asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily); break; case SecurityType.Crypto: asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily); break; case SecurityType.Equity: asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily); break; case SecurityType.Forex: asset = qcAlgorithm.AddForex(ticker, Resolution.Daily); break; case SecurityType.Future: asset = qcAlgorithm.AddFuture(ticker, Resolution.Minute); break; default: throw new Exception($"SecurityType {securityType} is not valid for this test"); } // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it. // This covers the case where two idential data subscriptions are created. var dummy = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone); var customData = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone); Assert.IsTrue(customData.Symbol.HasUnderlying, $"{customDataType.Name} added as {ticker} Symbol with SecurityType {securityType} does not have underlying"); Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol, $"Custom data underlying does not match {securityType} Symbol for {ticker}"); var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First(); var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single(); var assetShouldBeMapped = assetSubscription.TickerShouldBeMapped(); var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped(); Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped); Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped); Assert.AreNotEqual(assetSubscription, customDataSubscription); if (assetShouldBeMapped == customShouldBeMapped) { Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol); Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First()); } } [TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Cfd, false, false)] [TestCase("BTCUSD", typeof(IndexedLinkedData), SecurityType.Crypto, false, false)] [TestCase("CL", typeof(IndexedLinkedData), SecurityType.Future, false, false)] [TestCase("EURUSD", typeof(IndexedLinkedData), SecurityType.Forex, false, false)] [TestCase("AAPL", typeof(IndexedLinkedData), SecurityType.Equity, true, true)] public void AddDataSecurityTickerWithUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped) { SymbolCache.Clear(); var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); Security asset; switch (securityType) { case SecurityType.Cfd: asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily); break; case SecurityType.Crypto: asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily); break; case SecurityType.Equity: asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily); break; case SecurityType.Forex: asset = qcAlgorithm.AddForex(ticker, Resolution.Daily); break; case SecurityType.Future: asset = qcAlgorithm.AddFuture(ticker, Resolution.Minute); break; default: throw new Exception($"SecurityType {securityType} is not valid for this test"); } // Aliased value for Futures contains a forward-slash, which causes the // lookup in the SymbolCache to fail if (securityType == SecurityType.Future) { ticker = asset.Symbol.Value; } // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it. // This covers the case where two idential data subscriptions are created. var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone); var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone); Assert.IsTrue(customData.Symbol.HasUnderlying, $"Custom data added as {ticker} Symbol with SecurityType {securityType} does not have underlying"); Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol, $"Custom data underlying does not match {securityType} Symbol for {ticker}"); var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First(); var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single(); var assetShouldBeMapped = assetSubscription.TickerShouldBeMapped(); var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped(); if (securityType == SecurityType.Equity) { Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped); Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped); Assert.AreNotEqual(assetSubscription, customDataSubscription); if (assetShouldBeMapped == customShouldBeMapped) { Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol); Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First()); } } } [TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Cfd, false, false)] [TestCase("BTCUSD", typeof(UnlinkedData), SecurityType.Crypto, false, false)] [TestCase("CL", typeof(UnlinkedData), SecurityType.Future, false, false)] [TestCase("AAPL", typeof(UnlinkedData), SecurityType.Equity, true, false)] [TestCase("EURUSD", typeof(UnlinkedData), SecurityType.Forex, false, false)] public void AddDataSecurityTickerNoUnderlying(string ticker, Type customDataType, SecurityType securityType, bool securityShouldBeMapped, bool customDataShouldBeMapped) { SymbolCache.Clear(); var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); Security asset; switch (securityType) { case SecurityType.Cfd: asset = qcAlgorithm.AddCfd(ticker, Resolution.Daily); break; case SecurityType.Crypto: asset = qcAlgorithm.AddCrypto(ticker, Resolution.Daily); break; case SecurityType.Equity: asset = qcAlgorithm.AddEquity(ticker, Resolution.Daily); break; case SecurityType.Forex: asset = qcAlgorithm.AddForex(ticker, Resolution.Daily); break; case SecurityType.Future: asset = qcAlgorithm.AddFuture(ticker, Resolution.Minute); break; default: throw new Exception($"SecurityType {securityType} is not valid for this test"); } // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it. // This covers the case where two idential data subscriptions are created. var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone); var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First().DataTimeZone); // Check to see if we have an underlying symbol when we shouldn't Assert.IsFalse(customData.Symbol.HasUnderlying, $"{customDataType.Name} has underlying symbol for SecurityType {securityType} with ticker {ticker}"); Assert.AreEqual(customData.Symbol.Underlying, null, $"{customDataType.Name} - Custom data underlying Symbol for SecurityType {securityType} is not null"); var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == securityType).First(); var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single(); var assetShouldBeMapped = assetSubscription.TickerShouldBeMapped(); var customShouldBeMapped = customDataSubscription.TickerShouldBeMapped(); Assert.AreEqual(securityShouldBeMapped, assetShouldBeMapped); Assert.AreEqual(customDataShouldBeMapped, customShouldBeMapped); Assert.AreNotEqual(assetSubscription, customDataSubscription); if (assetShouldBeMapped == customShouldBeMapped) { // Would fail with CL future without this check because MappedSymbol returns "/CL" for the Future symbol if (assetSubscription.SecurityType == SecurityType.Future) { Assert.AreNotEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol); Assert.AreNotEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First()); } else { Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol); Assert.AreEqual(asset.Symbol.Value, customData.Symbol.Value.Split('.').First()); } } } [Test] public void AddOptionWithUnderlyingFuture() { // Adds an option containing a Future as its underlying Symbol. // This is an essential step in enabling custom derivatives // based on any asset class provided to Option. This test // checks the ability to create Future Options. var algo = new QCAlgorithm(); algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); var underlying = algo.AddFuture("ES", Resolution.Minute, Market.CME); underlying.SetFilter(0, 365); var futureOption = algo.AddOption(underlying.Symbol, Resolution.Minute); Assert.IsTrue(futureOption.Symbol.HasUnderlying); Assert.AreEqual(underlying.Symbol, futureOption.Symbol.Underlying); } [Test] public void AddFutureOptionContractNonEquityOption() { // Adds an option contract containing an underlying future contract. // We test to make sure that the security returned is a specific option // contract and with the future as the underlying. var algo = new QCAlgorithm(); algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); var underlying = algo.AddFutureContract( Symbol.CreateFuture("ES", Market.CME, new DateTime(2021, 3, 19)), Resolution.Minute); var futureOptionContract = algo.AddFutureOptionContract( Symbol.CreateOption(underlying.Symbol, Market.CME, OptionStyle.American, OptionRight.Call, 2550m, new DateTime(2021, 3, 19)), Resolution.Minute); Assert.AreEqual(underlying.Symbol, futureOptionContract.Symbol.Underlying); Assert.AreEqual(underlying, futureOptionContract.Underlying); Assert.IsFalse(underlying.Symbol.IsCanonical()); Assert.IsFalse(futureOptionContract.Symbol.IsCanonical()); } [Test] public void AddFutureOptionAddsUniverseSelectionModel() { var algo = new QCAlgorithm(); algo.SubscriptionManager.SetDataManager(new DataManagerStub(algo)); var underlying = algo.AddFuture("ES", Resolution.Minute, Market.CME); underlying.SetFilter(0, 365); algo.AddFutureOption(underlying.Symbol, _ => _); Assert.IsTrue(algo.UniverseSelection is OptionChainedUniverseSelectionModel); } [TestCase("AAPL", typeof(IndexedLinkedData), true)] [TestCase("TWX", typeof(IndexedLinkedData), true)] [TestCase("FB", typeof(IndexedLinkedData), true)] [TestCase("NFLX", typeof(IndexedLinkedData), true)] [TestCase("TWX", typeof(UnlinkedData), false)] [TestCase("AAPL", typeof(UnlinkedData), false)] public void AddDataOptionsSymbolHasChainedUnderlyingSymbols(string ticker, Type customDataType, bool customDataShouldBeMapped) { SymbolCache.Clear(); var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); var asset = qcAlgorithm.AddOption(ticker); // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it. // This covers the case where two idential data subscriptions are created. var dummy = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone); var customData = qcAlgorithm.AddData(customDataType, asset.Symbol, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone); // Check to see if we have an underlying symbol when we shouldn't Assert.IsTrue(customData.Symbol.HasUnderlying, $"{customDataType.Name} - {ticker} has no underlying Symbol"); Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol); Assert.AreEqual(customData.Symbol.Underlying.Underlying, asset.Symbol.Underlying); Assert.AreEqual(customData.Symbol.Underlying.Underlying.Underlying, null); var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single(); var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single(); Assert.IsTrue(assetSubscription.TickerShouldBeMapped()); Assert.AreEqual(customDataShouldBeMapped, customDataSubscription.TickerShouldBeMapped()); Assert.AreEqual($"?{assetSubscription.MappedSymbol}", customDataSubscription.MappedSymbol); } [TestCase("AAPL", typeof(IndexedLinkedData))] [TestCase("TWX", typeof(IndexedLinkedData))] [TestCase("FB", typeof(IndexedLinkedData))] [TestCase("NFLX", typeof(IndexedLinkedData))] public void AddDataOptionsTickerHasChainedUnderlyingSymbol(string ticker, Type customDataType) { SymbolCache.Clear(); var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); var asset = qcAlgorithm.AddOption(ticker); // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it. // This covers the case where two idential data subscriptions are created. var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone); var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone); // Check to see if we have an underlying symbol when we shouldn't Assert.IsTrue(customData.Symbol.HasUnderlying, $"{customDataType.Name} - {ticker} has no underlying Symbol"); Assert.AreNotEqual(customData.Symbol.Underlying, asset.Symbol); Assert.IsFalse(customData.Symbol.Underlying.HasUnderlying); Assert.AreEqual(customData.Symbol.Underlying, asset.Symbol.Underlying); var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single(); var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single(); Assert.IsTrue(assetSubscription.TickerShouldBeMapped()); Assert.IsTrue(customDataSubscription.TickerShouldBeMapped()); Assert.AreEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol); } [TestCase("AAPL", typeof(UnlinkedData))] [TestCase("FDTR", typeof(UnlinkedData))] public void AddDataOptionsTickerHasNoChainedUnderlyingSymbols(string ticker, Type customDataType) { SymbolCache.Clear(); var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); var asset = qcAlgorithm.AddOption(ticker); // Dummy here is meant to try to corrupt the SymbolCache. Ideally, SymbolCache should return non-custom data types with higher priority // in case we want to add two custom data types, but still have them associated with the equity from the cache if we're using it. // This covers the case where two idential data subscriptions are created. var dummy = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone); var customData = qcAlgorithm.AddData(customDataType, ticker, Resolution.Daily, qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single().DataTimeZone); // Check to see if we have an underlying symbol when we shouldn't Assert.IsFalse(customData.Symbol.HasUnderlying, $"{customDataType.Name} has an underlying Symbol"); var assetSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Option).Single(); var customDataSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.Where(x => x.SecurityType == SecurityType.Base).Single(); Assert.IsTrue(assetSubscription.TickerShouldBeMapped()); Assert.IsFalse(customDataSubscription.TickerShouldBeMapped()); //Assert.AreNotEqual(assetSubscription.MappedSymbol, customDataSubscription.MappedSymbol); } [Test] public void PythonCustomDataTypes_AreAddedToSubscriptions_Successfully() { var qcAlgorithm = new AlgorithmPythonWrapper("Test_CustomDataAlgorithm"); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); // Initialize contains the statements: // self.AddData(Nifty, "NIFTY") // self.AddData(QuandlFuture, "SCF/CME_CL1_ON", Resolution.Daily) qcAlgorithm.Initialize(); var niftySubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Symbol.Value == "NIFTY"); Assert.IsNotNull(niftySubscription); var niftyFactory = (BaseData)ObjectActivator.GetActivator(niftySubscription.Type).Invoke(new object[] { niftySubscription.Type }); Assert.DoesNotThrow(() => niftyFactory.GetSource(niftySubscription, DateTime.UtcNow, false)); var quandlSubscription = qcAlgorithm.SubscriptionManager.Subscriptions.FirstOrDefault(x => x.Symbol.Value == "SCF/CME_CL1_ON"); Assert.IsNotNull(quandlSubscription); var quandlFactory = (BaseData)ObjectActivator.GetActivator(quandlSubscription.Type).Invoke(new object[] { quandlSubscription.Type }); Assert.DoesNotThrow(() => quandlFactory.GetSource(quandlSubscription, DateTime.UtcNow, false)); } [Test] public void PythonCustomDataTypes_AreAddedToConsolidator_Successfully() { var qcAlgorithm = new AlgorithmPythonWrapper("Test_CustomDataAlgorithm"); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); // Initialize contains the statements: // self.AddData(Nifty, "NIFTY") // self.AddData(QuandlFuture, "SCF/CME_CL1_ON", Resolution.Daily) qcAlgorithm.Initialize(); var niftyConsolidator = new DynamicDataConsolidator(TimeSpan.FromDays(2)); Assert.DoesNotThrow(() => qcAlgorithm.SubscriptionManager.AddConsolidator("NIFTY", niftyConsolidator)); var quandlConsolidator = new DynamicDataConsolidator(TimeSpan.FromDays(2)); Assert.DoesNotThrow(() => qcAlgorithm.SubscriptionManager.AddConsolidator("SCF/CME_CL1_ON", quandlConsolidator)); } [Test] public void AddingInvalidDataTypeThrows() { var qcAlgorithm = new QCAlgorithm(); qcAlgorithm.SubscriptionManager.SetDataManager(new DataManagerStub(qcAlgorithm)); Assert.Throws<ArgumentException>(() => qcAlgorithm.AddData(typeof(double), "double", Resolution.Daily, DateTimeZone.Utc)); } [Test] public void AppendsCustomDataTypeName_ToSecurityIdentifierSymbol() { const string ticker = "ticker"; var algorithm = Algorithm(); var security = algorithm.AddData<Quandl>(ticker); Assert.AreEqual(ticker.ToUpperInvariant(), security.Symbol.Value); Assert.AreEqual($"{ticker.ToUpperInvariant()}.{typeof(Quandl).Name}", security.Symbol.ID.Symbol); Assert.AreEqual(SecurityIdentifier.GenerateBaseSymbol(typeof(Quandl), ticker), security.Symbol.ID.Symbol); } [Test] public void RegistersSecurityIdentifierSymbol_AsTickerString_InSymbolCache() { var algorithm = Algorithm(); Symbol cachedSymbol; var security = algorithm.AddData<Quandl>("ticker"); var symbolCacheAlias = security.Symbol.ID.Symbol; Assert.IsTrue(SymbolCache.TryGetSymbol(symbolCacheAlias, out cachedSymbol)); Assert.AreSame(security.Symbol, cachedSymbol); } [Test] public void DoesNotCauseCollision_WhenRegisteringMultipleDifferentCustomDataTypes_WithSameTicker() { const string ticker = "ticker"; var algorithm = Algorithm(); var security1 = algorithm.AddData<Quandl>(ticker); var security2 = algorithm.AddData<Bitcoin>(ticker); var quandl = algorithm.Securities[security1.Symbol]; Assert.AreSame(security1, quandl); var bitcoin = algorithm.Securities[security2.Symbol]; Assert.AreSame(security2, bitcoin); Assert.AreNotSame(quandl, bitcoin); } private static SubscriptionDataConfig GetMatchingSubscription(Security security, Type type) { // find a subscription matchin the requested type with a higher resolution than requested return (from sub in security.Subscriptions.OrderByDescending(s => s.Resolution) where type.IsAssignableFrom(sub.Type) select sub).FirstOrDefault(); } private static QCAlgorithm Algorithm() { var algorithm = new QCAlgorithm(); algorithm.SubscriptionManager.SetDataManager(new DataManagerStub(algorithm)); return algorithm; } private class TestHistoryProvider : HistoryProviderBase { public string underlyingSymbol = "GOOG"; public string underlyingSymbol2 = "AAPL"; public override int DataPointCount { get; } public Resolution LastResolutionRequest; public override void Initialize(HistoryProviderInitializeParameters parameters) { throw new NotImplementedException(); } public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone) { var now = DateTime.UtcNow; LastResolutionRequest = requests.First().Resolution; var tradeBar1 = new TradeBar(now, underlyingSymbol, 1, 1, 1, 1, 1, TimeSpan.FromDays(1)); var tradeBar2 = new TradeBar(now, underlyingSymbol2, 3, 3, 3, 3, 3, TimeSpan.FromDays(1)); var slice1 = new Slice(now, new List<BaseData> { tradeBar1, tradeBar2 }, new TradeBars(now), new QuoteBars(), new Ticks(), new OptionChains(), new FuturesChains(), new Splits(), new Dividends(now), new Delistings(), new SymbolChangedEvents()); var tradeBar1_2 = new TradeBar(now, underlyingSymbol, 2, 2, 2, 2, 2, TimeSpan.FromDays(1)); var slice2 = new Slice(now, new List<BaseData> { tradeBar1_2 }, new TradeBars(now), new QuoteBars(), new Ticks(), new OptionChains(), new FuturesChains(), new Splits(), new Dividends(now), new Delistings(), new SymbolChangedEvents()); return new[] { slice1, slice2 }; } } } }