context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using GoCardless.Errors; using GoCardless.Exceptions; using GoCardless.Internals; using GoCardless.Resources; using GoCardless.Services; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using JsonSerializerSettings = GoCardless.Internals.JsonSerializerSettings; namespace GoCardless { /// <summary> ///Entry point into the client. /// </summary> public partial class GoCardlessClient { /// <summary> /// This is the singleton HttpClient used if none is passed in via the .Create factory methods. /// See https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.110).aspx#Anchor_5 /// </summary> public static HttpClient DefaultHttpClient { get; set; } = new HttpClient(); public static ushort DefaultNumberOfRetriesOnTimeout { get; set; } = 2; public static TimeSpan DefaultWaitBetweenRetries { get; set; } = TimeSpan.FromSeconds(0.5d); private readonly HttpClient _httpClient; private readonly string _accessToken; private readonly Uri _baseUrl; private readonly bool _errorOnIdempotencyConflict; private GoCardlessClient(string accessToken, string baseUrl, HttpClient httpClient, bool errorOnIdempotencyConflict) { this._httpClient = httpClient ?? DefaultHttpClient; // Disable ExpectContinue when using the Default Http Client if (httpClient == null) { this._httpClient.DefaultRequestHeaders.ExpectContinue = false; } _accessToken = accessToken; _baseUrl = new Uri(baseUrl, UriKind.Absolute); _errorOnIdempotencyConflict = errorOnIdempotencyConflict; } /// <summary> ///Available environments for this client. /// </summary> public enum Environment { /// <summary> ///Live environment (base URL https://api.gocardless.com). /// </summary> LIVE, /// <summary> ///Sandbox environment (base URL https://api-sandbox.gocardless.com). /// </summary> SANDBOX } /// <summary> ///Creates an instance of the client in the live environment. /// ///@param accessToken the access token /// </summary> public static GoCardlessClient Create(string accessToken) { return Create(accessToken, Environment.LIVE); } /// <summary> ///Creates an instance of the client in a specified environment. /// ///@param accessToken the access token ///@param environment the environment /// </summary> public static GoCardlessClient Create(string accessToken, Environment environment, HttpClient httpClient = null) { return Create(accessToken, GetBaseUrl(environment), httpClient, false); } /// <summary> ///Creates an instance of the client running against a custom URL. /// ///@param accessToken the access token ///@param baseUrl the base URL of the API /// </summary> public static GoCardlessClient Create(string accessToken, string baseUrl, HttpClient client = null) { return Create(accessToken, baseUrl, client, false); } /// <summary> ///Creates an instance of the client. /// ///@param accessToken the access token ///@param baseUrl the base URL of the API ///@param errorOnIdempotencyConflict the behaviour for Idemptency Key conflicts /// </summary> public static GoCardlessClient Create(string accessToken, string baseUrl, HttpClient client = null, bool errorOnIdempotencyConflict = false) { return new GoCardlessClient(accessToken, baseUrl, client, errorOnIdempotencyConflict); } private static string GetBaseUrl(Environment env) { switch (env) { case Environment.LIVE: return "https://api.gocardless.com"; case Environment.SANDBOX: return "https://api-sandbox.gocardless.com"; } throw new ArgumentException("Unknown environment:" + env); } internal async Task<T> ExecuteAsync<T>(string method, string path, List<KeyValuePair<string, object>> urlParams, object requestParams, Func<string, Task<T>> fetchById, string payloadKey, RequestSettings requestSettings) where T : ApiResponse { var numberOfRetries = requestSettings?.NumberOfRetriesOnTimeout ?? DefaultNumberOfRetriesOnTimeout; var waitBetweenRetries = requestSettings?.WaitBetweenRetries ?? DefaultWaitBetweenRetries; var cancellationTokenSource = new CancellationTokenSource(); Func<Task<T>> execute = async () => { try { return await ExecuteAsyncInner<T>(method, path, urlParams, requestParams, payloadKey, requestSettings, cancellationTokenSource) .ConfigureAwait(false); } catch (InvalidStateException ex) when (ex.Errors.FirstOrDefault()?.Reason == "idempotent_creation_conflict" && ex.Errors.First().Links?.ContainsKey("conflicting_resource_id") == true) { if (_errorOnIdempotencyConflict) { throw; } var conflictingResourceId = ex.Errors.First().Links.FirstOrDefault().Value; return await fetchById(conflictingResourceId) .ConfigureAwait(false); } }; for (var i = 0; i < numberOfRetries; i++) { try { return await execute().ConfigureAwait(false); } catch (TaskCanceledException exception) when (!cancellationTokenSource.Token.IsCancellationRequested) { // This case represents a timeout, which we want to retry - see // https://stackoverflow.com/questions/10547895/how-can-i-tell-when-httpclient-has-timed-out/32230327 await Task.Delay(waitBetweenRetries); } catch (HttpRequestException exception) { // An HttpRequestException is raised when "[t]he request failed due to // an underlying issue such as network connectivity, DNS failure, // server certificate validation or timeout" await Task.Delay(waitBetweenRetries); } } return await execute().ConfigureAwait(false); } private async Task<T> ExecuteAsyncInner<T>(string method, string path, List<KeyValuePair<string, object>> urlParams, object requestParams, string payloadKey, RequestSettings requestSettings, CancellationTokenSource cancellationTokenSource) where T : ApiResponse { var requestMessage = BuildHttpRequestMessage<T>(method, path, urlParams, requestParams, payloadKey, requestSettings); var responseMessage = await _httpClient.SendAsync(requestMessage, cancellationTokenSource.Token).ConfigureAwait(false); try { if (responseMessage.IsSuccessStatusCode) { var json = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var result = JsonConvert.DeserializeObject<T>(json, new JsonSerializerSettings()); if (result == null) { result = (T)Activator.CreateInstance(typeof(T)); } result.ResponseMessage = responseMessage; return result; } else { var json = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var result = JsonConvert.DeserializeObject<ApiErrorResponse>(json, new JsonSerializerSettings()); result.ResponseMessage = responseMessage; switch (result.Error.Code) { case 401: result.Error.Type = ApiErrorType.AUTHENTICATION_FAILED; break; case 403: result.Error.Type = ApiErrorType.INSUFFICIENT_PERMISSIONS; break; case 429: result.Error.Type = ApiErrorType.RATE_LIMIT_REACHED; break; } throw result.ToException(); } } catch (JsonException) { throw new ApiException(new ApiErrorResponse() { ResponseMessage = responseMessage, Error = new ApiError() { Code = (int) responseMessage.StatusCode, Type = ApiErrorType.GOCARDLESS, Message = "Something went wrong with this request. Please check the ResponseMessage property." } }); } } private HttpRequestMessage BuildHttpRequestMessage<T>(string method, string path, List<KeyValuePair<string, object>> urlParams, object requestParams, string payloadKey, RequestSettings requestSettings) where T : ApiResponse { //insert url arguments into template foreach (var arg in urlParams) { path = path.Replace(":" + arg.Key, Helpers.Stringify(arg.Value)); } //add querystring for GET requests if (method == "GET") { var requestArguments = Helpers.ExtractQueryStringValuesFromObject(requestParams); if (requestArguments.Count > 0) { var queryString = String.Join("&", requestArguments.Select(Helpers.QueryStringArgument)); path += "?" + queryString; } } var httpMethod = new HttpMethod(method); var requestMessage = new HttpRequestMessage(httpMethod, new Uri(_baseUrl, path)); var OSRunningOn = ""; var runtimeFrameworkInformation = ""; #if NETSTANDARD OSRunningOn = System.Runtime.InteropServices.RuntimeInformation.OSDescription; runtimeFrameworkInformation = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; #endif #if NET46 OSRunningOn = System.Environment.OSVersion.VersionString; runtimeFrameworkInformation = System.Runtime.InteropServices.RuntimeEnvironment.GetSystemVersion(); #endif var userAgentInformation = $" gocardless-dotnet/5.2.0 {runtimeFrameworkInformation} {Helpers.CleanupOSDescriptionString(OSRunningOn)}"; requestMessage.Headers.Add("User-Agent", userAgentInformation); requestMessage.Headers.Add("GoCardless-Version", "2015-07-06"); requestMessage.Headers.Add("GoCardless-Client-Version", "5.2.0"); requestMessage.Headers.Add("GoCardless-Client-Library", "gocardless-dotnet"); requestMessage.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", _accessToken); //add request body for non-GETs if (method != "GET" && requestParams != null && !String.IsNullOrWhiteSpace(payloadKey)) { var settings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; var serializer = JsonSerializer.Create(settings); StringBuilder sb = new StringBuilder(); using (var sw = new StringWriter(sb)) { var jo = new JObject(); using (var jsonTextWriter = new LinuxLineEndingJsonTextWriter(sw)) { serializer.Serialize(jsonTextWriter, requestParams); jo[payloadKey] = JToken.Parse(sb.ToString()); } requestMessage.Content = new StringContent(jo.ToString(Formatting.Indented), Encoding.UTF8, "application/json"); } } var hasIdempotencyKey = requestParams as IHasIdempotencyKey; if (hasIdempotencyKey != null) { hasIdempotencyKey.IdempotencyKey = hasIdempotencyKey.IdempotencyKey ?? Guid.NewGuid().ToString(); requestMessage.Headers.TryAddWithoutValidation("Idempotency-Key", hasIdempotencyKey.IdempotencyKey); } if (requestSettings != null) { foreach (var header in requestSettings.Headers) { if (requestMessage.Headers.Contains(header.Key)) { requestMessage.Headers.Remove(header.Key); } requestMessage.Headers.Add(header.Key, header.Value); } } requestSettings?.CustomiseRequestMessage?.Invoke(requestMessage); return requestMessage; } class Helpers { internal static string Stringify(object value) { if (value is bool) return value.ToString().ToLower(); if (value is DateTimeOffset) return WebUtility.UrlEncode(((DateTimeOffset?) value).Value.ToString("o")); var typeInfo = value.GetType().GetTypeInfo(); if (typeInfo.IsArray) { return String.Join(WebUtility.UrlEncode(","), ((IEnumerable) value).Cast<object>().Select(Stringify)); } if (typeInfo.IsEnum) { var memInfo = typeInfo.GetMember(value.ToString()); var attr = memInfo[0].GetCustomAttributes(false).OfType<EnumMemberAttribute>().FirstOrDefault(); return attr?.Value; } return WebUtility.UrlEncode(value.ToString()); } internal static List<KeyValuePair<string, object>> ExtractQueryStringValuesFromObject(object obj) { if (obj == null) return Enumerable.Empty<KeyValuePair<string, object>>().ToList(); var args = new List<KeyValuePair<string, object>>(); var propertyInfos = obj.GetType().GetTypeInfo().GetProperties(); foreach (var propertyInfo in propertyInfos) { var value = propertyInfo.GetValue(obj); if (value != null) { var att = propertyInfo.GetCustomAttribute<JsonPropertyAttribute>(); if (att != null) { var ti = propertyInfo.PropertyType.GetTypeInfo(); var isParameterObject = !ti.IsArray && !ti.IsEnum && ti.Namespace.StartsWith("GoCardless"); if (isParameterObject) { foreach (var inner in ExtractQueryStringValuesFromObject(value)) { args.Add(new KeyValuePair<string, object>($"{att.PropertyName}[{inner.Key}]", inner.Value)); } } else { args.Add(new KeyValuePair<string, object>(att.PropertyName, value)); } } } } return args; } internal static string QueryStringArgument(KeyValuePair<string, object> argument) { var urlEncodedValue = Helpers.Stringify(argument.Value); var urlEncodedKey = WebUtility.UrlEncode(argument.Key); return $"{urlEncodedKey}={urlEncodedValue}"; } // Necessary due to a bug in User Agent header parser when multiple params passed // fixed in later versions of .NET but required until a later date when we upgrade internal static string CleanupOSDescriptionString(string input) { Regex pattern = new Regex("[;:#()~]"); return pattern.Replace(input, "-"); } } } }
// // UUEncoder.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2013-2015 Xamarin Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; namespace MimeKit.Encodings { /// <summary> /// Incrementally encodes content using the Unix-to-Unix encoding. /// </summary> /// <remarks> /// <para>The UUEncoding is an encoding that predates MIME and was used to encode /// binary content such as images and other types of multi-media to ensure /// that the data remained intact when sent via 7bit transports such as SMTP.</para> /// <para>These days, the UUEncoding has largely been deprecated in favour of /// the base64 encoding, however, some older mail clients still use it.</para> /// </remarks> public class UUEncoder : IMimeEncoder { const int MaxInputPerLine = 45; const int MaxOutputPerLine = ((MaxInputPerLine / 3) * 4) + 2; readonly byte[] uubuf = new byte[60]; uint saved; byte nsaved; byte uulen; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Encodings.UUEncoder"/> class. /// </summary> /// <remarks> /// Creates a new Unix-to-Unix encoder. /// </remarks> public UUEncoder () { Reset (); } /// <summary> /// Clone the <see cref="UUEncoder"/> with its current state. /// </summary> /// <remarks> /// Creates a new <see cref="UUEncoder"/> with exactly the same state as the current encoder. /// </remarks> /// <returns>A new <see cref="UUEncoder"/> with identical state.</returns> public IMimeEncoder Clone () { var encoder = new UUEncoder (); Buffer.BlockCopy (uubuf, 0, encoder.uubuf, 0, uubuf.Length); encoder.nsaved = nsaved; encoder.saved = saved; encoder.uulen = uulen; return encoder; } /// <summary> /// Gets the encoding. /// </summary> /// <remarks> /// Gets the encoding that the encoder supports. /// </remarks> /// <value>The encoding.</value> public ContentEncoding Encoding { get { return ContentEncoding.UUEncode; } } /// <summary> /// Estimates the length of the output. /// </summary> /// <remarks> /// Estimates the number of bytes needed to encode the specified number of input bytes. /// </remarks> /// <returns>The estimated output length.</returns> /// <param name="inputLength">The input length.</param> public int EstimateOutputLength (int inputLength) { return (((inputLength + 2) / MaxInputPerLine) * MaxOutputPerLine) + MaxOutputPerLine + 2; } void ValidateArguments (byte[] input, int startIndex, int length, byte[] output) { if (input == null) throw new ArgumentNullException ("input"); if (startIndex < 0 || startIndex > input.Length) throw new ArgumentOutOfRangeException ("startIndex"); if (length < 0 || length > (input.Length - startIndex)) throw new ArgumentOutOfRangeException ("length"); if (output == null) throw new ArgumentNullException ("output"); if (output.Length < EstimateOutputLength (length)) throw new ArgumentException ("The output buffer is not large enough to contain the encoded input.", "output"); } static byte Encode (int c) { return c != 0 ? (byte) (c + 0x20) : (byte) '`'; } unsafe int Encode (byte* input, int length, byte[] outbuf, byte* output, byte *uuptr) { if (length == 0) return 0; byte* inend = input + length; byte* outptr = output; byte* inptr = input; byte* bufptr; byte b0, b1, b2; if ((length + uulen) < 45) { // not enough input to write a full uuencoded line bufptr = uuptr + ((uulen / 3) * 4); } else { bufptr = outptr + 1; if (uulen > 0) { // copy the previous call's uubuf to output int n = (uulen / 3) * 4; Buffer.BlockCopy (uubuf, 0, outbuf, (int) (bufptr - output), n); bufptr += n; } } if (nsaved == 2) { b0 = (byte) ((saved >> 8) & 0xFF); b1 = (byte) (saved & 0xFF); b2 = *inptr++; nsaved = 0; saved = 0; // convert 3 input bytes into 4 uuencoded bytes *bufptr++ = Encode ((b0 >> 2) & 0x3F); *bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F); *bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F); *bufptr++ = Encode (b2 & 0x3F); uulen += 3; } else if (nsaved == 1) { if ((inptr + 2) < inend) { b0 = (byte) (saved & 0xFF); b1 = *inptr++; b2 = *inptr++; nsaved = 0; saved = 0; // convert 3 input bytes into 4 uuencoded bytes *bufptr++ = Encode ((b0 >> 2) & 0x3F); *bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F); *bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F); *bufptr++ = Encode (b2 & 0x3F); uulen += 3; } else { while (inptr < inend) { saved = (saved << 8) | *inptr++; nsaved++; } } } while (inptr < inend) { while (uulen < 45 && (inptr + 3) <= inend) { b0 = *inptr++; b1 = *inptr++; b2 = *inptr++; // convert 3 input bytes into 4 uuencoded bytes *bufptr++ = Encode ((b0 >> 2) & 0x3F); *bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F); *bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F); *bufptr++ = Encode (b2 & 0x3F); uulen += 3; } if (uulen >= 45) { // output the uu line length *outptr = Encode (uulen); outptr += ((uulen / 3) * 4) + 1; *outptr++ = (byte) '\n'; uulen = 0; if ((inptr + 45) <= inend) { // we have enough input to output another full line bufptr = outptr + 1; } else { bufptr = uuptr; } } else { // not enough input to continue... for (nsaved = 0, saved = 0; inptr < inend; nsaved++) saved = (saved << 8) | *inptr++; } } return (int) (outptr - output); } /// <summary> /// Encodes the specified input into the output buffer. /// </summary> /// <remarks> /// <para>Encodes the specified input into the output buffer.</para> /// <para>The output buffer should be large enough to hold all of the /// encoded input. For estimating the size needed for the output buffer, /// see <see cref="EstimateOutputLength"/>.</para> /// </remarks> /// <returns>The number of bytes written to the output buffer.</returns> /// <param name="input">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The length of the input buffer.</param> /// <param name="output">The output buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="input"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="output"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the <paramref name="input"/> byte array. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="output"/> is not large enough to contain the encoded content.</para> /// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the /// necessary length of the <paramref name="output"/> byte array.</para> /// </exception> public int Encode (byte[] input, int startIndex, int length, byte[] output) { ValidateArguments (input, startIndex, length, output); unsafe { fixed (byte* inptr = input, outptr = output, uuptr = uubuf) { return Encode (inptr + startIndex, length, output, outptr, uuptr); } } } unsafe int Flush (byte* input, int length, byte[] outbuf, byte* output, byte* uuptr) { byte* outptr = output; if (length > 0) outptr += Encode (input, length, outbuf, output, uuptr); byte* bufptr = uuptr + ((uulen / 3) * 4); byte uufill = 0; if (nsaved > 0) { while (nsaved < 3) { saved <<= 8; uufill++; nsaved++; } if (nsaved == 3) { // convert 3 input bytes into 4 uuencoded bytes byte b0, b1, b2; b0 = (byte) ((saved >> 16) & 0xFF); b1 = (byte) ((saved >> 8) & 0xFF); b2 = (byte) (saved & 0xFF); *bufptr++ = Encode ((b0 >> 2) & 0x3F); *bufptr++ = Encode (((b0 << 4) | ((b1 >> 4) & 0x0F)) & 0x3F); *bufptr++ = Encode (((b1 << 2) | ((b2 >> 6) & 0x03)) & 0x3F); *bufptr++ = Encode (b2 & 0x3F); uulen += 3; nsaved = 0; saved = 0; } } if (uulen > 0) { int n = (uulen / 3) * 4; *outptr++ = Encode ((uulen - uufill) & 0xFF); Buffer.BlockCopy (uubuf, 0, outbuf, (int) (outptr - output), n); outptr += n; *outptr++ = (byte) '\n'; uulen = 0; } *outptr++ = Encode (uulen & 0xFF); *outptr++ = (byte) '\n'; Reset (); return (int) (outptr - output); } /// <summary> /// Encodes the specified input into the output buffer, flushing any internal buffer state as well. /// </summary> /// <remarks> /// <para>Encodes the specified input into the output buffer, flusing any internal state as well.</para> /// <para>The output buffer should be large enough to hold all of the /// encoded input. For estimating the size needed for the output buffer, /// see <see cref="EstimateOutputLength"/>.</para> /// </remarks> /// <returns>The number of bytes written to the output buffer.</returns> /// <param name="input">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The length of the input buffer.</param> /// <param name="output">The output buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="input"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="output"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the <paramref name="input"/> byte array. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="output"/> is not large enough to contain the encoded content.</para> /// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the /// necessary length of the <paramref name="output"/> byte array.</para> /// </exception> public int Flush (byte[] input, int startIndex, int length, byte[] output) { ValidateArguments (input, startIndex, length, output); unsafe { fixed (byte* inptr = input, outptr = output, uuptr = uubuf) { return Flush (inptr + startIndex, length, output, outptr, uuptr); } } } /// <summary> /// Resets the encoder. /// </summary> /// <remarks> /// Resets the state of the encoder. /// </remarks> public void Reset () { nsaved = 0; saved = 0; uulen = 0; } } }
// *********************************************************************** // Copyright (c) 2012-2014 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.IO; using System.Reflection; using System.Threading; using NUnit.Common; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; using NUnit.Framework.Internal.Execution; namespace NUnit.Framework.Api { /// <summary> /// Implementation of ITestAssemblyRunner /// </summary> public class NUnitTestAssemblyRunner : ITestAssemblyRunner { private static Logger log = InternalTrace.GetLogger("DefaultTestAssemblyRunner"); private ITestAssemblyBuilder _builder; private ManualResetEvent _runComplete = new ManualResetEvent(false); #if !SILVERLIGHT && !NETCF && !PORTABLE // Saved Console.Out and Console.Error private TextWriter _savedOut; private TextWriter _savedErr; #endif #if PARALLEL // Event Pump private EventPump _pump; #endif #region Constructors /// <summary> /// Initializes a new instance of the <see cref="NUnitTestAssemblyRunner"/> class. /// </summary> /// <param name="builder">The builder.</param> public NUnitTestAssemblyRunner(ITestAssemblyBuilder builder) { _builder = builder; } #endregion #region Properties /// <summary> /// The tree of tests that was loaded by the builder /// </summary> public ITest LoadedTest { get; private set; } /// <summary> /// The test result, if a run has completed /// </summary> public ITestResult Result { get { return TopLevelWorkItem == null ? null : TopLevelWorkItem.Result; } } /// <summary> /// Indicates whether a test is loaded /// </summary> public bool IsTestLoaded { get { return LoadedTest != null; } } /// <summary> /// Indicates whether a test is running /// </summary> public bool IsTestRunning { get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Running; } } /// <summary> /// Indicates whether a test run is complete /// </summary> public bool IsTestComplete { get { return TopLevelWorkItem != null && TopLevelWorkItem.State == WorkItemState.Complete; } } /// <summary> /// Our settings, specified when loading the assembly /// </summary> private IDictionary Settings { get; set; } /// <summary> /// The top level WorkItem created for the assembly as a whole /// </summary> private WorkItem TopLevelWorkItem { get; set; } /// <summary> /// The TestExecutionContext for the top level WorkItem /// </summary> private TestExecutionContext Context { get; set; } #endregion #region Public Methods /// <summary> /// Loads the tests found in an Assembly /// </summary> /// <param name="assemblyName">File name of the assembly to load</param> /// <param name="settings">Dictionary of option settings for loading the assembly</param> /// <returns>True if the load was successful</returns> public ITest Load(string assemblyName, IDictionary settings) { Settings = settings; Randomizer.InitialSeed = GetInitialSeed(settings); return LoadedTest = _builder.Build(assemblyName, settings); } /// <summary> /// Loads the tests found in an Assembly /// </summary> /// <param name="assembly">The assembly to load</param> /// <param name="settings">Dictionary of option settings for loading the assembly</param> /// <returns>True if the load was successful</returns> public ITest Load(Assembly assembly, IDictionary settings) { Settings = settings; Randomizer.InitialSeed = GetInitialSeed(settings); return LoadedTest = _builder.Build(assembly, settings); } /// <summary> /// Count Test Cases using a filter /// </summary> /// <param name="filter">The filter to apply</param> /// <returns>The number of test cases found</returns> public int CountTestCases(ITestFilter filter) { if (LoadedTest == null) throw new InvalidOperationException("The CountTestCases method was called but no test has been loaded"); return CountTestCases(LoadedTest, filter); } /// <summary> /// Run selected tests and return a test result. The test is run synchronously, /// and the listener interface is notified as it progresses. /// </summary> /// <param name="listener">Interface to receive EventListener notifications.</param> /// <param name="filter">A test filter used to select tests to be run</param> /// <returns></returns> public ITestResult Run(ITestListener listener, ITestFilter filter) { RunAsync(listener, filter); WaitForCompletion(Timeout.Infinite); return Result; } /// <summary> /// Run selected tests asynchronously, notifying the listener interface as it progresses. /// </summary> /// <param name="listener">Interface to receive EventListener notifications.</param> /// <param name="filter">A test filter used to select tests to be run</param> /// <remarks> /// RunAsync is a template method, calling various abstract and /// virtual methods to be overridden by derived classes. /// </remarks> public void RunAsync(ITestListener listener, ITestFilter filter) { log.Info("Running tests"); if (LoadedTest == null) throw new InvalidOperationException("The Run method was called but no test has been loaded"); CreateTestExecutionContext(listener); TopLevelWorkItem = WorkItem.CreateWorkItem(LoadedTest, filter); TopLevelWorkItem.InitializeContext(Context); TopLevelWorkItem.Completed += OnRunCompleted; StartRun(listener); } /// <summary> /// Wait for the ongoing run to complete. /// </summary> /// <param name="timeout">Time to wait in milliseconds</param> /// <returns>True if the run completed, otherwise false</returns> public bool WaitForCompletion(int timeout) { #if !SILVERLIGHT && !PORTABLE return _runComplete.WaitOne(timeout, false); #else return _runComplete.WaitOne(timeout); #endif } /// <summary> /// Initiate the test run. /// </summary> public void StartRun(ITestListener listener) { #if !SILVERLIGHT && !NETCF && !PORTABLE // Save Console.Out and Error for later restoration _savedOut = Console.Out; _savedErr = Console.Error; Console.SetOut(new TextCapture(Console.Out)); Console.SetError(new TextCapture(Console.Error)); #endif #if PARALLEL QueuingEventListener queue = new QueuingEventListener(); Context.Listener = queue; _pump = new EventPump(listener, queue.Events); _pump.Start(); #else Context.Dispatcher = new SimpleWorkItemDispatcher(); #endif Context.Dispatcher.Dispatch(TopLevelWorkItem); } /// <summary> /// Signal any test run that is in process to stop. Return without error if no test is running. /// </summary> /// <param name="force">If true, kill any test-running threads</param> public void StopRun(bool force) { if (IsTestRunning) { Context.ExecutionStatus = force ? TestExecutionStatus.AbortRequested : TestExecutionStatus.StopRequested; if (force) Context.Dispatcher.CancelRun(); } } #endregion #region Helper Methods /// <summary> /// Create the initial TestExecutionContext used to run tests /// </summary> /// <param name="listener">The ITestListener specified in the RunAsync call</param> private void CreateTestExecutionContext(ITestListener listener) { Context = new TestExecutionContext(); if (Settings.Contains(PackageSettings.DefaultTimeout)) Context.TestCaseTimeout = (int)Settings[PackageSettings.DefaultTimeout]; if (Settings.Contains(PackageSettings.StopOnError)) Context.StopOnError = (bool)Settings[PackageSettings.StopOnError]; if (Settings.Contains(PackageSettings.WorkDirectory)) Context.WorkDirectory = (string)Settings[PackageSettings.WorkDirectory]; else Context.WorkDirectory = Env.DefaultWorkDirectory; // Overriding runners may replace this Context.Listener = listener; #if PARALLEL int levelOfParallelism = GetLevelOfParallelism(); if (levelOfParallelism > 0) { Context.Dispatcher = new ParallelWorkItemDispatcher(levelOfParallelism); // Assembly does not have IApplyToContext attributes applied // when the test is built, so we do it here. // TODO: Generalize this if (LoadedTest.Properties.ContainsKey(PropertyNames.ParallelScope)) Context.ParallelScope = (ParallelScope)LoadedTest.Properties.Get(PropertyNames.ParallelScope) & ~ParallelScope.Self; } else Context.Dispatcher = new SimpleWorkItemDispatcher(); #endif } /// <summary> /// Handle the the Completed event for the top level work item /// </summary> private void OnRunCompleted(object sender, EventArgs e) { #if PARALLEL _pump.Dispose(); #endif #if !SILVERLIGHT && !NETCF && !PORTABLE Console.SetOut(_savedOut); Console.SetError(_savedErr); #endif _runComplete.Set(); } private int CountTestCases(ITest test, ITestFilter filter) { if (!test.IsSuite) return 1; int count = 0; foreach (ITest child in test.Tests) if (filter.Pass(child)) count += CountTestCases(child, filter); return count; } private static int GetInitialSeed(IDictionary settings) { return settings.Contains(PackageSettings.RandomSeed) ? (int)settings[PackageSettings.RandomSeed] : new Random().Next(); } #if PARALLEL private int GetLevelOfParallelism() { return Settings.Contains(PackageSettings.NumberOfTestWorkers) ? (int)Settings[PackageSettings.NumberOfTestWorkers] : (LoadedTest.Properties.ContainsKey(PropertyNames.LevelOfParallelism) ? (int)LoadedTest.Properties.Get(PropertyNames.LevelOfParallelism) #if NETCF : 2); #else : Math.Max(Environment.ProcessorCount, 2)); #endif } #endif #endregion } }
/// /// Author: Ahmed Lacevic /// Date: 12/1/2007 /// Desc: /// /// Revision History: /// ----------------------------------- /// Author: /// Date: /// Desc: using System; using System.Collections.Generic; using System.Text; using System.IO; using System.Globalization; namespace SocialExplorer.IO.FastDBF { /// <summary> /// Use this class to create a record and write it to a dbf file. You can use one record object to write all records!! /// It was designed for this kind of use. You can do this by clearing the record of all data /// (call Clear() method) or setting values to all fields again, then write to dbf file. /// This eliminates creating and destroying objects and optimizes memory use. /// /// Once you create a record the header can no longer be modified, since modifying the header would make a corrupt DBF file. /// </summary> public class DbfRecord { /// <summary> /// Header provides information on all field types, sizes, precision and other useful information about the DBF. /// </summary> private DbfHeader _header = null; /// <summary> /// Dbf data are a mix of ASCII characters and binary, which neatly fit in a byte array. /// BinaryWriter would esentially perform the same conversion using the same Encoding class. /// </summary> private byte[] _data = null; /// <summary> /// Zero based record index. -1 when not set, new records for example. /// </summary> private long _recordIndex = -1; /// <summary> /// Empty Record array reference used to clear fields quickly (or entire record). /// </summary> private readonly byte[] _emptyRecord = null; /// <summary> /// Specifies whether we allow strings to be truncated. If false and string is longer than we can fit in the field, an exception is thrown. /// </summary> private bool _allowStringTruncate = true; /// <summary> /// Specifies whether we allow the decimal portion of numbers to be truncated. /// If false and decimal digits overflow the field, an exception is thrown. /// </summary> private bool _allowDecimalTruncate = false; /// <summary> /// Specifies whether we allow the integer portion of numbers to be truncated. /// If false and integer digits overflow the field, an exception is thrown. /// </summary> private bool _allowIntegerTruncate = false; //array used to clear decimals, we can clear up to 40 decimals which is much more than is allowed under DBF spec anyway. //Note: 48 is ASCII code for 0. private static readonly byte[] _decimalClear = new byte[] {48,48,48,48,48,48,48,48,48,48,48,48,48,48,48, 48,48,48,48,48,48,48,48,48,48,48,48,48,48,48, 48,48,48,48,48,48,48,48,48,48,48,48,48,48,48}; //Warning: do not make this one static because that would not be thread safe!! The reason I have //placed this here is to skip small memory allocation/deallocation which fragments memory in .net. private int[] _tempIntVal = { 0 }; //encoder private readonly Encoding encoding = Encoding.GetEncoding(1252); /// <summary> /// Column Name to Column Index map /// </summary> private readonly Dictionary<string, int> _colNameToIdx = new Dictionary<string, int>(StringComparer.InvariantCulture); /// <summary> /// /// </summary> /// <param name="oHeader">Dbf Header will be locked once a record is created /// since the record size is fixed and if the header was modified it would corrupt the DBF file.</param> public DbfRecord(DbfHeader oHeader) { _header = oHeader; _header.Locked = true; //create a buffer to hold all record data. We will reuse this buffer to write all data to the file. _data = new byte[_header.RecordLength]; // Make sure mData[0] correctly represents 'not deleted' IsDeleted = false; _emptyRecord = _header.EmptyDataRecord; encoding = oHeader.encoding; for (int i = 0; i < oHeader._fields.Count; i++) _colNameToIdx[oHeader._fields[i].Name] = i; } /// <summary> /// Set string data to a column, if the string is longer than specified column length it will be truncated! /// If dbf column type is not a string, input will be treated as dbf column /// type and if longer than length an exception will be thrown. /// </summary> /// <param name="nColIndex"></param> /// <returns></returns> public string this[int nColIndex] { set { DbfColumn ocol = _header[nColIndex]; DbfColumn.DbfColumnType ocolType = ocol.ColumnType; // //if an empty value is passed, we just clear the data, and leave it blank. //note: test have shown that testing for null and checking length is faster than comparing to "" empty str :) //------------------------------------------------------------------------------------------------------------ if (string.IsNullOrEmpty(value)) { //this is like NULL data, set it to empty. i looked at SAS DBF output when a null value exists //and empty data are output. we get the same result, so this looks good. Buffer.BlockCopy(_emptyRecord, ocol.DataAddress, _data, ocol.DataAddress, ocol.Length); } else { //set values according to data type: //------------------------------------------------------------- if (ocolType == DbfColumn.DbfColumnType.Character) { if (!_allowStringTruncate && value.Length > ocol.Length) throw new DbfDataTruncateException("Value not set. String truncation would occur and AllowStringTruncate flag is set to false. To supress this exception change AllowStringTruncate to true."); //BlockCopy copies bytes. First clear the previous value, then set the new one. Buffer.BlockCopy(_emptyRecord, ocol.DataAddress, _data, ocol.DataAddress, ocol.Length); encoding.GetBytes(value, 0, value.Length > ocol.Length ? ocol.Length : value.Length, _data, ocol.DataAddress); } else if (ocolType == DbfColumn.DbfColumnType.Number) { if (ocol.DecimalCount == 0) { //integers //---------------------------------- //throw an exception if integer overflow would occur if (!_allowIntegerTruncate && value.Length > ocol.Length) throw new DbfDataTruncateException("Value not set. Integer does not fit and would be truncated. AllowIntegerTruncate is set to false. To supress this exception set AllowIntegerTruncate to true, although that is not recomended."); //clear all numbers, set to [space]. //----------------------------------------------------- Buffer.BlockCopy(_emptyRecord, 0, _data, ocol.DataAddress, ocol.Length); //set integer part, CAREFUL not to overflow buffer! (truncate instead) //----------------------------------------------------------------------- int nNumLen = value.Length > ocol.Length ? ocol.Length : value.Length; encoding.GetBytes(value, 0, nNumLen, _data, (ocol.DataAddress + ocol.Length - nNumLen)); } else { ///TODO: we can improve perfomance here by not using temp char arrays cDec and cNum, ///simply directly copy from source string using encoding! //break value down into integer and decimal portions //-------------------------------------------------------------------------- int nidxDecimal = value.IndexOf('.'); //index where the decimal point occurs char[] cDec = null; //decimal portion of the number char[] cNum = null; //integer portion if (nidxDecimal > -1) { cDec = value.Substring(nidxDecimal + 1).Trim().ToCharArray(); cNum = value.Substring(0, nidxDecimal).ToCharArray(); //throw an exception if decimal overflow would occur if (!_allowDecimalTruncate && cDec.Length > ocol.DecimalCount) throw new DbfDataTruncateException("Value not set. Decimal does not fit and would be truncated. AllowDecimalTruncate is set to false. To supress this exception set AllowDecimalTruncate to true."); } else cNum = value.ToCharArray(); //throw an exception if integer overflow would occur if (!_allowIntegerTruncate && cNum.Length > ocol.Length - ocol.DecimalCount - 1) throw new DbfDataTruncateException("Value not set. Integer does not fit and would be truncated. AllowIntegerTruncate is set to false. To supress this exception set AllowIntegerTruncate to true, although that is not recomended."); //------------------------------------------------------------------------------------------------------------------ // NUMERIC TYPE //------------------------------------------------------------------------------------------------------------------ //clear all decimals, set to 0. //----------------------------------------------------- Buffer.BlockCopy(_decimalClear, 0, _data, (ocol.DataAddress + ocol.Length - ocol.DecimalCount), ocol.DecimalCount); //clear all numbers, set to [space]. Buffer.BlockCopy(_emptyRecord, 0, _data, ocol.DataAddress, (ocol.Length - ocol.DecimalCount)); //set decimal numbers, CAREFUL not to overflow buffer! (truncate instead) //----------------------------------------------------------------------- if (nidxDecimal > -1) { int nLen = cDec.Length > ocol.DecimalCount ? ocol.DecimalCount : cDec.Length; encoding.GetBytes(cDec, 0, nLen, _data, (ocol.DataAddress + ocol.Length - ocol.DecimalCount)); } //set integer part, CAREFUL not to overflow buffer! (truncate instead) //----------------------------------------------------------------------- int nNumLen = cNum.Length > ocol.Length - ocol.DecimalCount - 1 ? (ocol.Length - ocol.DecimalCount - 1) : cNum.Length; encoding.GetBytes(cNum, 0, nNumLen, _data, ocol.DataAddress + ocol.Length - ocol.DecimalCount - nNumLen - 1); //set decimal point //----------------------------------------------------------------------- _data[ocol.DataAddress + ocol.Length - ocol.DecimalCount - 1] = (byte)'.'; } } else if (ocolType == DbfColumn.DbfColumnType.Float) { //------------------------------------------------------------------------------------------------------------------ // FLOAT TYPE // example: value=" 2.40000000000e+001" Length=19 Decimal-Count=11 //------------------------------------------------------------------------------------------------------------------ // check size, throw exception if value won't fit: if (value.Length > ocol.Length) throw new DbfDataTruncateException("Value not set. Float value does not fit and would be truncated."); double parsed_value; if (!Double.TryParse(value, out parsed_value)) { //value did not parse, input is not correct. throw new DbfDataTruncateException("Value not set. Float value format is bad: '" + value + "' expected format: ' 2.40000000000e+001'"); } //clear value that was present previously Buffer.BlockCopy(_decimalClear, 0, _data, ocol.DataAddress, ocol.Length); //copy new value at location char[] valueAsCharArray = value.ToCharArray(); encoding.GetBytes(valueAsCharArray, 0, valueAsCharArray.Length, _data, ocol.DataAddress); } else if (ocolType == DbfColumn.DbfColumnType.Integer) { //note this is a binary Integer type! //---------------------------------------------- ///TODO: maybe there is a better way to copy 4 bytes from int to byte array. Some memory function or something. _tempIntVal[0] = Convert.ToInt32(value); Buffer.BlockCopy(_tempIntVal, 0, _data, ocol.DataAddress, 4); } else if (ocolType == DbfColumn.DbfColumnType.Memo) { //copy 10 digits... ///TODO: implement MEMO throw new NotImplementedException("Memo data type functionality not implemented yet!"); } else if (ocolType == DbfColumn.DbfColumnType.Boolean) { if (String.Compare(value, "true", true) == 0 || String.Compare(value, "1", true) == 0 || String.Compare(value, "T", true) == 0 || String.Compare(value, "yes", true) == 0 || String.Compare(value, "Y", true) == 0) _data[ocol.DataAddress] = (byte)'T'; else if (value == " " || value == "?") _data[ocol.DataAddress] = (byte)'?'; else _data[ocol.DataAddress] = (byte)'F'; } else if (ocolType == DbfColumn.DbfColumnType.Date) { //try to parse out date value using Date.Parse() function, then set the value DateTime dateval; if (DateTime.TryParse(value, out dateval)) { SetDateValue(nColIndex, dateval); } else throw new InvalidOperationException("Date could not be parsed from source string! Please parse the Date and set the value (you can try using DateTime.Parse() or DateTime.TryParse() functions)."); } else if (ocolType == DbfColumn.DbfColumnType.Binary) throw new InvalidOperationException("Can not use string source to set binary data. Use SetBinaryValue() and GetBinaryValue() functions instead."); else throw new InvalidDataException("Unrecognized data type: " + ocolType.ToString()); } } get { DbfColumn ocol = _header[nColIndex]; return new string(encoding.GetChars(_data, ocol.DataAddress, ocol.Length)); } } /// <summary> /// Set string data to a column, if the string is longer than specified column length it will be truncated! /// If dbf column type is not a string, input will be treated as dbf column /// type and if longer than length an exception will be thrown. /// </summary> /// <param name="nColName"></param> /// <returns></returns> public string this[string nColName] { get { if (_colNameToIdx.ContainsKey(nColName)) return this[_colNameToIdx[nColName]]; throw new InvalidOperationException(string.Format("There's no column with name '{0}'", nColName)); } set { if (_colNameToIdx.ContainsKey(nColName)) this[_colNameToIdx[nColName]] = value; else throw new InvalidOperationException(string.Format("There's no column with name '{0}'", nColName)); } } /// <summary> /// Get date value. /// </summary> /// <param name="nColIndex"></param> /// <returns></returns> public DateTime GetDateValue(int nColIndex) { DbfColumn ocol = _header[nColIndex]; if (ocol.ColumnType == DbfColumn.DbfColumnType.Date) { string sDateVal = encoding.GetString(_data, ocol.DataAddress, ocol.Length); return DateTime.ParseExact(sDateVal, "yyyyMMdd", CultureInfo.InvariantCulture); } else throw new Exception("Invalid data type. Column '" + ocol.Name + "' is not a date column."); } /// <summary> /// Get date value. /// </summary> /// <param name="nColIndex"></param> /// <returns></returns> public void SetDateValue(int nColIndex, DateTime value) { DbfColumn ocol = _header[nColIndex]; DbfColumn.DbfColumnType ocolType = ocol.ColumnType; if (ocolType == DbfColumn.DbfColumnType.Date) { //Format date and set value, date format is like this: yyyyMMdd //------------------------------------------------------------- encoding.GetBytes(value.ToString("yyyyMMdd"), 0, ocol.Length, _data, ocol.DataAddress); } else throw new Exception("Invalid data type. Column is of '" + ocol.ColumnType.ToString() + "' type, not date."); } /// <summary> /// Clears all data in the record. /// </summary> public void Clear() { Buffer.BlockCopy(_emptyRecord, 0, _data, 0, _emptyRecord.Length); _recordIndex = -1; } /// <summary> /// returns a string representation of this record. /// </summary> /// <returns></returns> public override string ToString() { return new string(encoding.GetChars(_data)); } /// <summary> /// Gets/sets a zero based record index. This information is not directly stored in DBF. /// It is the location of this record within the DBF. /// </summary> /// <remarks> /// This property is managed from outside this object, /// CDbfFile object updates it when records are read. The reason we don't set it in the Read() /// function within this object is that the stream can be forward-only so the Position property /// is not available and there is no way to figure out what index the record was unless you /// count how many records were read, and that's exactly what CDbfFile does. /// </remarks> public long RecordIndex { get { return _recordIndex; } set { _recordIndex = value; } } /// <summary> /// Returns/sets flag indicating whether this record was tagged deleted. /// </summary> /// <remarks>Use CDbf4File.Compress() function to rewrite dbf removing records flagged as deleted.</remarks> /// <seealso cref="CDbf4File.Compress() function"/> public bool IsDeleted { get { return _data[0] == '*'; } set { _data[0] = value ? (byte)'*' : (byte)' '; } } /// <summary> /// Specifies whether strings can be truncated. If false and string is longer than can fit in the field, an exception is thrown. /// Default is True. /// </summary> public bool AllowStringTurncate { get { return _allowStringTruncate; } set { _allowStringTruncate = value; } } /// <summary> /// Specifies whether to allow the decimal portion of numbers to be truncated. /// If false and decimal digits overflow the field, an exception is thrown. Default is false. /// </summary> public bool AllowDecimalTruncate { get { return _allowDecimalTruncate; } set { _allowDecimalTruncate = value; } } /// <summary> /// Specifies whether integer portion of numbers can be truncated. /// If false and integer digits overflow the field, an exception is thrown. /// Default is False. /// </summary> public bool AllowIntegerTruncate { get { return _allowIntegerTruncate; } set { _allowIntegerTruncate = value; } } /// <summary> /// Returns header object associated with this record. /// </summary> public DbfHeader Header { get { return _header; } } /// <summary> /// Get column by index. /// </summary> /// <param name="index"></param> /// <returns></returns> public DbfColumn Column(int index) { return _header[index]; } /// <summary> /// Get column by name. /// </summary> /// <param name="index"></param> /// <returns></returns> public DbfColumn Column(string sName) { return _header[sName]; } /// <summary> /// Gets column count from header. /// </summary> public int ColumnCount { get { return _header.ColumnCount; } } /// <summary> /// Finds a column index by searching sequentially through the list. Case is ignored. Returns -1 if not found. /// </summary> /// <param name="sName">Column name.</param> /// <returns>Column index (0 based) or -1 if not found.</returns> public int FindColumn(string sName) { return _header.FindColumn(sName); } /// <summary> /// Writes data to stream. Make sure stream is positioned correctly because we simply write out the data to it. /// </summary> /// <param name="osw"></param> protected internal void Write(Stream osw) { osw.Write(_data, 0, _data.Length); } /// <summary> /// Writes data to stream. Make sure stream is positioned correctly because we simply write out data to it, and clear the record. /// </summary> /// <param name="osw"></param> protected internal void Write(Stream obw, bool bClearRecordAfterWrite) { obw.Write(_data, 0, _data.Length); if (bClearRecordAfterWrite) Clear(); } /// <summary> /// Read record from stream. Returns true if record read completely, otherwise returns false. /// </summary> /// <param name="obr"></param> /// <returns></returns> protected internal bool Read(Stream obr) { return obr.Read(_data, 0, _data.Length) >= _data.Length; } protected internal string ReadValue(Stream obr, int colIndex) { DbfColumn ocol = _header[colIndex]; return new string(encoding.GetChars(_data, ocol.DataAddress, ocol.Length)); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Apis.CloudSecurityToken.v1 { /// <summary>The CloudSecurityToken Service.</summary> public class CloudSecurityTokenService : 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 CloudSecurityTokenService() : this(new Google.Apis.Services.BaseClientService.Initializer()) { } /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public CloudSecurityTokenService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { V1 = new V1Resource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features => new string[0]; /// <summary>Gets the service name.</summary> public override string Name => "sts"; /// <summary>Gets the service base URI.</summary> public override string BaseUri => #if NETSTANDARD1_3 || NETSTANDARD2_0 || NET45 BaseUriOverride ?? "https://sts.googleapis.com/"; #else "https://sts.googleapis.com/"; #endif /// <summary>Gets the service base path.</summary> public override string BasePath => ""; #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri => "https://sts.googleapis.com/batch"; /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath => "batch"; #endif /// <summary>Gets the V1 resource.</summary> public virtual V1Resource V1 { get; } } /// <summary>A base abstract class for CloudSecurityToken requests.</summary> public abstract class CloudSecurityTokenBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { /// <summary>Constructs a new CloudSecurityTokenBaseServiceRequest instance.</summary> protected CloudSecurityTokenBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1 = 0, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2 = 1, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json = 0, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media = 1, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto = 2, } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary> /// API key. Your API key identifies your project and provides you with API access, quota, and reports. Required /// unless you provide an OAuth 2.0 token. /// </summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary> /// Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a /// user, but should not exceed 40 characters. /// </summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes CloudSecurityToken parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add("$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add("callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add("quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add("upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "v1" collection of methods.</summary> public class V1Resource { private const string Resource = "v1"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public V1Resource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary> /// Gets information about a Google OAuth 2.0 access token issued by the Google Cloud [Security Token Service /// API](https://cloud.google.com/iam/docs/reference/sts/rest). /// </summary> /// <param name="body">The body of the request.</param> public virtual IntrospectRequest Introspect(Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenRequest body) { return new IntrospectRequest(service, body); } /// <summary> /// Gets information about a Google OAuth 2.0 access token issued by the Google Cloud [Security Token Service /// API](https://cloud.google.com/iam/docs/reference/sts/rest). /// </summary> public class IntrospectRequest : CloudSecurityTokenBaseServiceRequest<Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenResponse> { /// <summary>Constructs a new Introspect request.</summary> public IntrospectRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1IntrospectTokenRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "introspect"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/introspect"; /// <summary>Initializes Introspect parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary> /// Exchanges a credential for a Google OAuth 2.0 access token. The token asserts an external identity within an /// identity pool, or it applies a Credential Access Boundary to a Google access token. When you call this /// method, do not send the `Authorization` HTTP header in the request. This method does not require the /// `Authorization` header, and using the header can cause the request to fail. /// </summary> /// <param name="body">The body of the request.</param> public virtual TokenRequest Token(Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenRequest body) { return new TokenRequest(service, body); } /// <summary> /// Exchanges a credential for a Google OAuth 2.0 access token. The token asserts an external identity within an /// identity pool, or it applies a Credential Access Boundary to a Google access token. When you call this /// method, do not send the `Authorization` HTTP header in the request. This method does not require the /// `Authorization` header, and using the header can cause the request to fail. /// </summary> public class TokenRequest : CloudSecurityTokenBaseServiceRequest<Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenResponse> { /// <summary>Constructs a new Token request.</summary> public TokenRequest(Google.Apis.Services.IClientService service, Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.CloudSecurityToken.v1.Data.GoogleIdentityStsV1ExchangeTokenRequest Body { get; set; } /// <summary>Returns the body of the request.</summary> protected override object GetBody() => Body; /// <summary>Gets the method name.</summary> public override string MethodName => "token"; /// <summary>Gets the HTTP method.</summary> public override string HttpMethod => "POST"; /// <summary>Gets the REST path.</summary> public override string RestPath => "v1/token"; /// <summary>Initializes Token parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.CloudSecurityToken.v1.Data { /// <summary>Associates `members`, or principals, with a `role`.</summary> public class GoogleIamV1Binding : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The condition that is associated with this binding. If the condition evaluates to `true`, then this binding /// applies to the current request. If the condition evaluates to `false`, then this binding does not apply to /// the current request. However, a different role binding might grant the same role to one or more of the /// principals in this binding. To learn which resources support conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("condition")] public virtual GoogleTypeExpr Condition { get; set; } /// <summary> /// Specifies the principals requesting access for a Cloud Platform resource. `members` can have the following /// values: * `allUsers`: A special identifier that represents anyone who is on the internet; with or without a /// Google account. * `allAuthenticatedUsers`: A special identifier that represents anyone who is authenticated /// with a Google account or a service account. * `user:{emailid}`: An email address that represents a specific /// Google account. For example, `alice@example.com` . * `serviceAccount:{emailid}`: An email address that /// represents a service account. For example, `my-other-app@appspot.gserviceaccount.com`. * `group:{emailid}`: /// An email address that represents a Google group. For example, `admins@example.com`. * /// `deleted:user:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a user that /// has been recently deleted. For example, `alice@example.com?uid=123456789012345678901`. If the user is /// recovered, this value reverts to `user:{emailid}` and the recovered user retains the role in the binding. * /// `deleted:serviceAccount:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing a /// service account that has been recently deleted. For example, /// `my-other-app@appspot.gserviceaccount.com?uid=123456789012345678901`. If the service account is undeleted, /// this value reverts to `serviceAccount:{emailid}` and the undeleted service account retains the role in the /// binding. * `deleted:group:{emailid}?uid={uniqueid}`: An email address (plus unique identifier) representing /// a Google group that has been recently deleted. For example, `admins@example.com?uid=123456789012345678901`. /// If the group is recovered, this value reverts to `group:{emailid}` and the recovered group retains the role /// in the binding. * `domain:{domain}`: The G Suite domain (primary) that represents all the users of that /// domain. For example, `google.com` or `example.com`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("members")] public virtual System.Collections.Generic.IList<string> Members { get; set; } /// <summary> /// Role that is assigned to the list of `members`, or principals. For example, `roles/viewer`, `roles/editor`, /// or `roles/owner`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("role")] public virtual string Role { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An access boundary defines the upper bound of what a principal may access. It includes a list of access boundary /// rules that each defines the resource that may be allowed as well as permissions that may be used on those /// resources. /// </summary> public class GoogleIdentityStsV1AccessBoundary : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A list of access boundary rules which defines the upper bound of the permission a principal may carry. If /// multiple rules are specified, the effective access boundary is the union of all the access boundary rules /// attached. One access boundary can contain at most 10 rules. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundaryRules")] public virtual System.Collections.Generic.IList<GoogleIdentityStsV1AccessBoundaryRule> AccessBoundaryRules { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>An access boundary rule defines an upper bound of IAM permissions on a single resource.</summary> public class GoogleIdentityStsV1AccessBoundaryRule : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The availability condition further constrains the access allowed by the access boundary rule. If the /// condition evaluates to `true`, then this access boundary rule will provide access to the specified resource, /// assuming the principal has the required permissions for the resource. If the condition does not evaluate to /// `true`, then access to the specified resource will not be available. Note that all access boundary rules in /// an access boundary are evaluated together as a union. As such, another access boundary rule may allow access /// to the resource, even if this access boundary rule does not allow access. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). The maximum length of the /// `expression` field is 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availabilityCondition")] public virtual GoogleTypeExpr AvailabilityCondition { get; set; } /// <summary> /// A list of permissions that may be allowed for use on the specified resource. The only supported values in /// the list are IAM roles, following the format of google.iam.v1.Binding.role. Example value: /// `inRole:roles/logging.viewer` for predefined roles and /// `inRole:organizations/{ORGANIZATION_ID}/roles/logging.viewer` for custom roles. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availablePermissions")] public virtual System.Collections.Generic.IList<string> AvailablePermissions { get; set; } /// <summary> /// The full resource name of a Google Cloud resource entity. The format definition is at /// https://cloud.google.com/apis/design/resource_names. Example value: /// `//cloudresourcemanager.googleapis.com/projects/my-project`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availableResource")] public virtual string AvailableResource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for ExchangeToken.</summary> public class GoogleIdentityStsV1ExchangeTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The full resource name of the identity provider; for example: /// `//iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/`. Required when /// exchanging an external credential for a Google access token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audience")] public virtual string Audience { get; set; } /// <summary> /// Required. The grant type. Must be `urn:ietf:params:oauth:grant-type:token-exchange`, which indicates a token /// exchange. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("grantType")] public virtual string GrantType { get; set; } /// <summary> /// A set of features that Security Token Service supports, in addition to the standard OAuth 2.0 token /// exchange, formatted as a serialized JSON object of Options. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("options")] public virtual string Options { get; set; } /// <summary> /// Required. An identifier for the type of requested security token. Must be /// `urn:ietf:params:oauth:token-type:access_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("requestedTokenType")] public virtual string RequestedTokenType { get; set; } /// <summary> /// The OAuth 2.0 scopes to include on the resulting access token, formatted as a list of space-delimited, /// case-sensitive strings. Required when exchanging an external credential for a Google access token. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("scope")] public virtual string Scope { get; set; } /// <summary> /// Required. The input token. This token is either an external credential issued by a workload identity pool /// provider, or a short-lived access token issued by Google. If the token is an OIDC JWT, it must use the JWT /// format defined in [RFC 7523](https://tools.ietf.org/html/rfc7523), and the `subject_token_type` must be /// either `urn:ietf:params:oauth:token-type:jwt` or `urn:ietf:params:oauth:token-type:id_token`. The following /// headers are required: - `kid`: The identifier of the signing key securing the JWT. - `alg`: The /// cryptographic algorithm securing the JWT. Must be `RS256` or `ES256`. The following payload fields are /// required. For more information, see [RFC 7523, Section 3](https://tools.ietf.org/html/rfc7523#section-3): - /// `iss`: The issuer of the token. The issuer must provide a discovery document at the URL /// `/.well-known/openid-configuration`, where `` is the value of this field. The document must be formatted /// according to section 4.2 of the [OIDC 1.0 Discovery /// specification](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfigurationResponse). - /// `iat`: The issue time, in seconds, since the Unix epoch. Must be in the past. - `exp`: The expiration time, /// in seconds, since the Unix epoch. Must be less than 48 hours after `iat`. Shorter expiration times are more /// secure. If possible, we recommend setting an expiration time less than 6 hours. - `sub`: The identity /// asserted in the JWT. - `aud`: For workload identity pools, this must be a value specified in the allowed /// audiences for the workload identity pool provider, or one of the audiences allowed by default if no /// audiences were specified. See /// https://cloud.google.com/iam/docs/reference/rest/v1/projects.locations.workloadIdentityPools.providers#oidc /// Example header: ``` { "alg": "RS256", "kid": "us-east-11" } ``` Example payload: ``` { "iss": /// "https://accounts.google.com", "iat": 1517963104, "exp": 1517966704, "aud": /// "//iam.googleapis.com/projects/1234567890123/locations/global/workloadIdentityPools/my-pool/providers/my-provider", /// "sub": "113475438248934895348", "my_claims": { "additional_claim": "value" } } ``` If `subject_token` is for /// AWS, it must be a serialized `GetCallerIdentity` token. This token contains the same information as a /// request to the AWS /// [`GetCallerIdentity()`](https://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity) method, /// as well as the AWS [signature](https://docs.aws.amazon.com/general/latest/gr/signing_aws_api_requests.html) /// for the request information. Use Signature Version 4. Format the request as URL-encoded JSON, and set the /// `subject_token_type` parameter to `urn:ietf:params:aws:token-type:aws4_request`. The following parameters /// are required: - `url`: The URL of the AWS STS endpoint for `GetCallerIdentity()`, such as /// `https://sts.amazonaws.com?Action=GetCallerIdentity&amp;amp;Version=2011-06-15`. Regional endpoints are also /// supported. - `method`: The HTTP request method: `POST`. - `headers`: The HTTP request headers, which must /// include: - `Authorization`: The request signature. - `x-amz-date`: The time you will send the request, /// formatted as an [ISO8601 /// Basic](https://docs.aws.amazon.com/general/latest/gr/sigv4_elements.html#sigv4_elements_date) string. This /// value is typically set to the current time and is used to help prevent replay attacks. - `host`: The /// hostname of the `url` field; for example, `sts.amazonaws.com`. - `x-goog-cloud-target-resource`: The full, /// canonical resource name of the workload identity pool provider, with or without an `https:` prefix. To help /// ensure data integrity, we recommend including this header in the `SignedHeaders` field of the signed /// request. For example: //iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/ /// https://iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/ If you are using /// temporary security credentials provided by AWS, you must also include the header `x-amz-security-token`, /// with the value set to the session token. The following example shows a `GetCallerIdentity` token: ``` { /// "headers": [ {"key": "x-amz-date", "value": "20200815T015049Z"}, {"key": "Authorization", "value": /// "AWS4-HMAC-SHA256+Credential=$credential,+SignedHeaders=host;x-amz-date;x-goog-cloud-target-resource,+Signature=$signature"}, /// {"key": "x-goog-cloud-target-resource", "value": /// "//iam.googleapis.com/projects//locations/global/workloadIdentityPools//providers/"}, {"key": "host", /// "value": "sts.amazonaws.com"} . ], "method": "POST", "url": /// "https://sts.amazonaws.com?Action=GetCallerIdentity&amp;amp;Version=2011-06-15" } ``` You can also use a /// Google-issued OAuth 2.0 access token with this field to obtain an access token with new security attributes /// applied, such as a Credential Access Boundary. In this case, set `subject_token_type` to /// `urn:ietf:params:oauth:token-type:access_token`. If an access token already contains security attributes, /// you cannot apply additional security attributes. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("subjectToken")] public virtual string SubjectToken { get; set; } /// <summary> /// Required. An identifier that indicates the type of the security token in the `subject_token` parameter. /// Supported values are `urn:ietf:params:oauth:token-type:jwt`, `urn:ietf:params:oauth:token-type:id_token`, /// `urn:ietf:params:aws:token-type:aws4_request`, and `urn:ietf:params:oauth:token-type:access_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("subjectTokenType")] public virtual string SubjectTokenType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for ExchangeToken.</summary> public class GoogleIdentityStsV1ExchangeTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// An OAuth 2.0 security token, issued by Google, in response to the token exchange request. Tokens can vary in /// size, depending in part on the size of mapped claims, up to a maximum of 12288 bytes (12 KB). Google /// reserves the right to change the token size and the maximum length at any time. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("access_token")] public virtual string AccessToken { get; set; } /// <summary> /// The amount of time, in seconds, between the time when the access token was issued and the time when the /// access token will expire. This field is absent when the `subject_token` in the request is a Google-issued, /// short-lived access token. In this case, the access token has the same expiration time as the /// `subject_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("expires_in")] public virtual System.Nullable<int> ExpiresIn { get; set; } /// <summary>The token type. Always matches the value of `requested_token_type` from the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("issued_token_type")] public virtual string IssuedTokenType { get; set; } /// <summary>The type of access token. Always has the value `Bearer`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("token_type")] public virtual string TokenType { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Request message for IntrospectToken.</summary> public class GoogleIdentityStsV1IntrospectTokenRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>Required. The OAuth 2.0 security token issued by the Security Token Service API.</summary> [Newtonsoft.Json.JsonPropertyAttribute("token")] public virtual string Token { get; set; } /// <summary> /// Optional. The type of the given token. Supported values are `urn:ietf:params:oauth:token-type:access_token` /// and `access_token`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("tokenTypeHint")] public virtual string TokenTypeHint { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Response message for IntrospectToken.</summary> public class GoogleIdentityStsV1IntrospectTokenResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>A boolean value that indicates whether the provided access token is currently active.</summary> [Newtonsoft.Json.JsonPropertyAttribute("active")] public virtual System.Nullable<bool> Active { get; set; } /// <summary>The client identifier for the OAuth 2.0 client that requested the provided token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("client_id")] public virtual string ClientId { get; set; } /// <summary> /// The expiration timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this /// token will expire. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("exp")] public virtual System.Nullable<long> Exp { get; set; } /// <summary> /// The issued timestamp, measured in the number of seconds since January 1 1970 UTC, indicating when this token /// was originally issued. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("iat")] public virtual System.Nullable<long> Iat { get; set; } /// <summary>The issuer of the provided token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("iss")] public virtual string Iss { get; set; } /// <summary>A list of scopes associated with the provided token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("scope")] public virtual string Scope { get; set; } /// <summary> /// The unique user ID associated with the provided token. For Google Accounts, this value is based on the /// Google Account's user ID. For federated identities, this value is based on the identity pool ID and the /// value of the mapped `google.subject` attribute. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("sub")] public virtual string Sub { get; set; } /// <summary> /// The human-readable identifier for the token principal subject. For example, if the provided token is /// associated with a workload identity pool, this field contains a value in the following format: /// `principal://iam.googleapis.com/projects//locations/global/workloadIdentityPools//subject/` /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("username")] public virtual string Username { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An `Options` object configures features that the Security Token Service supports, but that are not supported by /// standard OAuth 2.0 token exchange endpoints, as defined in https://tools.ietf.org/html/rfc8693. /// </summary> public class GoogleIdentityStsV1Options : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// An access boundary that defines the upper bound of permissions the credential may have. The value should be /// a JSON object of AccessBoundary. The access boundary can include up to 10 rules. The size of the parameter /// value should not exceed 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundary")] public virtual GoogleIdentityStsV1AccessBoundary AccessBoundary { get; set; } /// <summary> /// The intended audience(s) of the credential. The audience value(s) should be the name(s) of services intended /// to receive the credential. Example: `["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]`. /// A maximum of 5 audiences can be included. For each provided audience, the maximum length is 262 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audiences")] public virtual System.Collections.Generic.IList<string> Audiences { get; set; } /// <summary> /// A Google project used for quota and billing purposes when the credential is used to access Google APIs. The /// provided project overrides the project bound to the credential. The value must be a project number or a /// project ID. Example: `my-sample-project-191923`. The maximum length is 32 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userProject")] public virtual string UserProject { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An access boundary defines the upper bound of what a principal may access. It includes a list of access boundary /// rules that each defines the resource that may be allowed as well as permissions that may be used on those /// resources. /// </summary> public class GoogleIdentityStsV1betaAccessBoundary : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// A list of access boundary rules which defines the upper bound of the permission a principal may carry. If /// multiple rules are specified, the effective access boundary is the union of all the access boundary rules /// attached. One access boundary can contain at most 10 rules. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundaryRules")] public virtual System.Collections.Generic.IList<GoogleIdentityStsV1betaAccessBoundaryRule> AccessBoundaryRules { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>An access boundary rule defines an upper bound of IAM permissions on a single resource.</summary> public class GoogleIdentityStsV1betaAccessBoundaryRule : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// The availability condition further constrains the access allowed by the access boundary rule. If the /// condition evaluates to `true`, then this access boundary rule will provide access to the specified resource, /// assuming the principal has the required permissions for the resource. If the condition does not evaluate to /// `true`, then access to the specified resource will not be available. Note that all access boundary rules in /// an access boundary are evaluated together as a union. As such, another access boundary rule may allow access /// to the resource, even if this access boundary rule does not allow access. To learn which resources support /// conditions in their IAM policies, see the [IAM /// documentation](https://cloud.google.com/iam/help/conditions/resource-policies). The maximum length of the /// `expression` field is 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availabilityCondition")] public virtual GoogleTypeExpr AvailabilityCondition { get; set; } /// <summary> /// A list of permissions that may be allowed for use on the specified resource. The only supported values in /// the list are IAM roles, following the format of google.iam.v1.Binding.role. Example value: /// `inRole:roles/logging.viewer` for predefined roles and /// `inRole:organizations/{ORGANIZATION_ID}/roles/logging.viewer` for custom roles. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availablePermissions")] public virtual System.Collections.Generic.IList<string> AvailablePermissions { get; set; } /// <summary> /// The full resource name of a Google Cloud resource entity. The format definition is at /// https://cloud.google.com/apis/design/resource_names. Example value: /// `//cloudresourcemanager.googleapis.com/projects/my-project`. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("availableResource")] public virtual string AvailableResource { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// An `Options` object configures features that the Security Token Service supports, but that are not supported by /// standard OAuth 2.0 token exchange endpoints, as defined in https://tools.ietf.org/html/rfc8693. /// </summary> public class GoogleIdentityStsV1betaOptions : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// An access boundary that defines the upper bound of permissions the credential may have. The value should be /// a JSON object of AccessBoundary. The access boundary can include up to 10 rules. The size of the parameter /// value should not exceed 2048 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("accessBoundary")] public virtual GoogleIdentityStsV1betaAccessBoundary AccessBoundary { get; set; } /// <summary> /// The intended audience(s) of the credential. The audience value(s) should be the name(s) of services intended /// to receive the credential. Example: `["https://pubsub.googleapis.com/", "https://storage.googleapis.com/"]`. /// A maximum of 5 audiences can be included. For each provided audience, the maximum length is 262 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("audiences")] public virtual System.Collections.Generic.IList<string> Audiences { get; set; } /// <summary> /// A Google project used for quota and billing purposes when the credential is used to access Google APIs. The /// provided project overrides the project bound to the credential. The value must be a project number or a /// project ID. Example: `my-sample-project-191923`. The maximum length is 32 characters. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("userProject")] public virtual string UserProject { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary> /// Represents a textual expression in the Common Expression Language (CEL) syntax. CEL is a C-like expression /// language. The syntax and semantics of CEL are documented at https://github.com/google/cel-spec. Example /// (Comparison): title: "Summary size limit" description: "Determines if a summary is less than 100 chars" /// expression: "document.summary.size() &amp;lt; 100" Example (Equality): title: "Requestor is owner" description: /// "Determines if requestor is the document owner" expression: "document.owner == request.auth.claims.email" /// Example (Logic): title: "Public documents" description: "Determine whether the document should be publicly /// visible" expression: "document.type != 'private' &amp;amp;&amp;amp; document.type != 'internal'" Example (Data /// Manipulation): title: "Notification string" description: "Create a notification string with a timestamp." /// expression: "'New message received at ' + string(document.create_time)" The exact variables and functions that /// may be referenced within an expression are determined by the service that evaluates it. See the service /// documentation for additional information. /// </summary> public class GoogleTypeExpr : Google.Apis.Requests.IDirectResponseSchema { /// <summary> /// Optional. Description of the expression. This is a longer text which describes the expression, e.g. when /// hovered over it in a UI. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("description")] public virtual string Description { get; set; } /// <summary>Textual representation of an expression in Common Expression Language syntax.</summary> [Newtonsoft.Json.JsonPropertyAttribute("expression")] public virtual string Expression { get; set; } /// <summary> /// Optional. String indicating the location of the expression for error reporting, e.g. a file name and a /// position in the file. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("location")] public virtual string Location { get; set; } /// <summary> /// Optional. Title for the expression, i.e. a short string describing its purpose. This can be used e.g. in UIs /// which allow to enter the expression. /// </summary> [Newtonsoft.Json.JsonPropertyAttribute("title")] public virtual string Title { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// Distributed as part of TiledSharp, Copyright 2012 Marshall Ward // Licensed under the Apache License, Version 2.0 // http://www.apache.org/licenses/LICENSE-2.0 using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Globalization; using System.Xml.Linq; namespace TiledSharp { public class TmxObjectGroup : ITmxElement { public string Name {get; private set;} // TODO: Legacy (Tiled Java) attributes (x, y, width, height) public TmxColor Color {get; private set;} public DrawOrderType DrawOrder {get; private set;} public double Opacity {get; private set;} public bool Visible {get; private set;} public double OffsetX {get; private set;} public double OffsetY {get; private set;} public TmxList<TmxObject> Objects {get; private set;} public PropertyDict Properties {get; private set;} public TmxObjectGroup(XElement xObjectGroup) { Name = (string) xObjectGroup.Attribute("name") ?? String.Empty; Color = new TmxColor(xObjectGroup.Attribute("color")); Opacity = (double?) xObjectGroup.Attribute("opacity") ?? 1.0; Visible = (bool?) xObjectGroup.Attribute("visible") ?? true; OffsetX = (double?) xObjectGroup.Attribute("offsetx") ?? 0.0; OffsetY = (double?) xObjectGroup.Attribute("offsety") ?? 0.0; var drawOrderDict = new Dictionary<string, DrawOrderType> { {"unknown", DrawOrderType.UnknownOrder}, {"topdown", DrawOrderType.IndexOrder}, {"index", DrawOrderType.TopDown} }; var drawOrderValue = (string) xObjectGroup.Attribute("draworder"); if (drawOrderValue != null) DrawOrder = drawOrderDict[drawOrderValue]; Objects = new TmxList<TmxObject>(); foreach (var e in xObjectGroup.Elements("object")) Objects.Add(new TmxObject(e)); Properties = new PropertyDict(xObjectGroup.Element("properties")); } } public class TmxObject : ITmxElement { // Many TmxObjectTypes are distinguished by null values in fields // It might be smart to subclass TmxObject public int Id {get; private set;} public string Name {get; private set;} public TmxObjectType ObjectType {get; private set;} public string Type {get; private set;} public double X {get; private set;} public double Y {get; private set;} public double Width {get; private set;} public double Height {get; private set;} public double Rotation {get; private set;} public TmxLayerTile Tile {get; private set;} public bool Visible {get; private set;} public TmxText Text { get; private set; } public Collection<TmxObjectPoint> Points {get; private set;} public PropertyDict Properties {get; private set;} public TmxObject(XElement xObject) { Id = (int?)xObject.Attribute("id") ?? 0; Name = (string)xObject.Attribute("name") ?? String.Empty; X = (double)xObject.Attribute("x"); Y = (double)xObject.Attribute("y"); Width = (double?)xObject.Attribute("width") ?? 0.0; Height = (double?)xObject.Attribute("height") ?? 0.0; Type = (string)xObject.Attribute("type") ?? String.Empty; Visible = (bool?)xObject.Attribute("visible") ?? true; Rotation = (double?)xObject.Attribute("rotation") ?? 0.0; // Assess object type and assign appropriate content var xGid = xObject.Attribute("gid"); var xEllipse = xObject.Element("ellipse"); var xPolygon = xObject.Element("polygon"); var xPolyline = xObject.Element("polyline"); if (xGid != null) { Tile = new TmxLayerTile((uint)xGid, Convert.ToInt32(Math.Round(X)), Convert.ToInt32(Math.Round(X))); ObjectType = TmxObjectType.Tile; } else if (xEllipse != null) { ObjectType = TmxObjectType.Ellipse; } else if (xPolygon != null) { Points = ParsePoints(xPolygon); ObjectType = TmxObjectType.Polygon; } else if (xPolyline != null) { Points = ParsePoints(xPolyline); ObjectType = TmxObjectType.Polyline; } else ObjectType = TmxObjectType.Basic; var xText = xObject.Element("text"); if (xText != null) { Text = new TmxText(xText); } Properties = new PropertyDict(xObject.Element("properties")); } public Collection<TmxObjectPoint> ParsePoints(XElement xPoints) { var points = new Collection<TmxObjectPoint>(); var pointString = (string)xPoints.Attribute("points"); var pointStringPair = pointString.Split(' '); foreach (var s in pointStringPair) { var pt = new TmxObjectPoint(s); points.Add(pt); } return points; } } public class TmxObjectPoint { public double X {get; private set;} public double Y {get; private set;} public TmxObjectPoint(double x, double y) { X = x; Y = y; } public TmxObjectPoint(string s) { var pt = s.Split(','); X = double.Parse(pt[0], NumberStyles.Float, CultureInfo.InvariantCulture); Y = double.Parse(pt[1], NumberStyles.Float, CultureInfo.InvariantCulture); } } public class TmxText { public string FontFamily { get; private set; } public int PixelSize { get; private set; } public bool Wrap { get; private set; } public TmxColor Color { get; private set; } public bool Bold { get; private set; } public bool Italic { get; private set; } public bool Underline { get; private set; } public bool Strikeout { get; private set; } public bool Kerning { get; private set; } public TmxAlignment Alignment { get; private set; } public string Value { get; private set; } public TmxText(XElement xText) { FontFamily = (string)xText.Attribute("fontfamily") ?? "sand-serif"; PixelSize = (int?)xText.Attribute("pixelsize") ?? 16; Wrap = (bool?)xText.Attribute("wrap") ?? false; Color = new TmxColor(xText.Attribute("color")); Bold = (bool?)xText.Attribute("bold") ?? false; Italic = (bool?)xText.Attribute("italic") ?? false; Underline = (bool?)xText.Attribute("underline") ?? false; Strikeout = (bool?)xText.Attribute("strikeout") ?? false; Kerning = (bool?)xText.Attribute("kerning") ?? true; Alignment = new TmxAlignment(xText.Attribute("halign"), xText.Attribute("valign")); Value = xText.Value; } } public class TmxAlignment { public TmxHorizontalAlignment Horizontal { get; private set; } public TmxVerticalAlignment Vertical { get; private set; } public TmxAlignment(XAttribute halign, XAttribute valign) { var xHorizontal = (string)halign ?? "Left"; Horizontal = (TmxHorizontalAlignment)Enum.Parse(typeof(TmxHorizontalAlignment), FirstLetterToUpperCase(xHorizontal)); var xVertical = (string)valign ?? "Top"; Vertical = (TmxVerticalAlignment)Enum.Parse(typeof(TmxVerticalAlignment), FirstLetterToUpperCase(xVertical)); } private string FirstLetterToUpperCase(string str) { if (string.IsNullOrEmpty(str)) { return str; } return str[0].ToString().ToUpper() + str.Substring(1); } } public enum TmxObjectType { Basic, Tile, Ellipse, Polygon, Polyline } public enum DrawOrderType { UnknownOrder = -1, TopDown, IndexOrder } public enum TmxHorizontalAlignment { Left, Center, Right, Justify } public enum TmxVerticalAlignment { Top, Center, Bottom } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using NUnit.Framework; using SqlCE4Umbraco; using Umbraco.Core; using Umbraco.Core.IO; using umbraco.DataLayer; using Umbraco.Core.Models.EntityBase; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Tests.TestHelpers { /// <summary> /// Common helper properties and methods useful to testing /// </summary> public static class TestHelper { /// <summary> /// Clears an initialized database /// </summary> public static void ClearDatabase() { var databaseSettings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName]; var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false) as SqlCEHelper; if (dataHelper == null) throw new InvalidOperationException("The sql helper for unit tests must be of type SqlCEHelper, check the ensure the connection string used for this test is set to use SQLCE"); dataHelper.ClearDatabase(); } public static void DropForeignKeys(string table) { var databaseSettings = ConfigurationManager.ConnectionStrings[Constants.System.UmbracoConnectionName]; var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false) as SqlCEHelper; if (dataHelper == null) throw new InvalidOperationException("The sql helper for unit tests must be of type SqlCEHelper, check the ensure the connection string used for this test is set to use SQLCE"); dataHelper.DropForeignKeys(table); } /// <summary> /// Gets the current assembly directory. /// </summary> /// <value>The assembly directory.</value> static public string CurrentAssemblyDirectory { get { var codeBase = typeof(TestHelper).Assembly.CodeBase; var uri = new Uri(codeBase); var path = uri.LocalPath; return Path.GetDirectoryName(path); } } /// <summary> /// Maps the given <paramref name="relativePath"/> making it rooted on <see cref="CurrentAssemblyDirectory"/>. <paramref name="relativePath"/> must start with <code>~/</code> /// </summary> /// <param name="relativePath">The relative path.</param> /// <returns></returns> public static string MapPathForTest(string relativePath) { if (!relativePath.StartsWith("~/")) throw new ArgumentException("relativePath must start with '~/'", "relativePath"); return relativePath.Replace("~/", CurrentAssemblyDirectory + "/"); } public static void InitializeContentDirectories() { CreateDirectories(new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews, SystemDirectories.Media, SystemDirectories.AppPlugins }); } public static void CleanContentDirectories() { CleanDirectories(new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews, SystemDirectories.Media }); } public static void CreateDirectories(string[] directories) { foreach (var directory in directories) { var directoryInfo = new DirectoryInfo(IOHelper.MapPath(directory)); if (directoryInfo.Exists == false) Directory.CreateDirectory(IOHelper.MapPath(directory)); } } public static void CleanDirectories(string[] directories) { var preserves = new Dictionary<string, string[]> { { SystemDirectories.Masterpages, new[] {"dummy.txt"} }, { SystemDirectories.MvcViews, new[] {"dummy.txt"} } }; foreach (var directory in directories) { var directoryInfo = new DirectoryInfo(IOHelper.MapPath(directory)); var preserve = preserves.ContainsKey(directory) ? preserves[directory] : null; if (directoryInfo.Exists) directoryInfo.GetFiles().Where(x => preserve == null || preserve.Contains(x.Name) == false).ForEach(x => x.Delete()); } } public static void CleanUmbracoSettingsConfig() { var currDir = new DirectoryInfo(CurrentAssemblyDirectory); var umbracoSettingsFile = Path.Combine(currDir.Parent.Parent.FullName, "config", "umbracoSettings.config"); if (File.Exists(umbracoSettingsFile)) File.Delete(umbracoSettingsFile); } public static void AssertAllPropertyValuesAreEquals(object actual, object expected, string dateTimeFormat = null, Func<IEnumerable, IEnumerable> sorter = null, string[] ignoreProperties = null) { var properties = expected.GetType().GetProperties(); foreach (var property in properties) { //ignore properties that are attributed with this var att = property.GetCustomAttribute<EditorBrowsableAttribute>(false); if (att != null && att.State == EditorBrowsableState.Never) continue; if (ignoreProperties != null && ignoreProperties.Contains(property.Name)) continue; var expectedValue = property.GetValue(expected, null); var actualValue = property.GetValue(actual, null); if (((actualValue is string) == false) && actualValue is IEnumerable) { AssertListsAreEquals(property, (IEnumerable)actualValue, (IEnumerable)expectedValue, dateTimeFormat, sorter); } else if (dateTimeFormat.IsNullOrWhiteSpace() == false && actualValue is DateTime) { // round to second else in some cases tests can fail ;-( var expectedDateTime = (DateTime) expectedValue; expectedDateTime = expectedDateTime.AddTicks(-(expectedDateTime.Ticks%TimeSpan.TicksPerSecond)); var actualDateTime = (DateTime) actualValue; actualDateTime = actualDateTime.AddTicks(-(actualDateTime.Ticks % TimeSpan.TicksPerSecond)); Assert.AreEqual(expectedDateTime.ToString(dateTimeFormat), actualDateTime.ToString(dateTimeFormat), "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } else { Assert.AreEqual(expectedValue, actualValue, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } } } private static void AssertListsAreEquals(PropertyInfo property, IEnumerable actualList, IEnumerable expectedList, string dateTimeFormat, Func<IEnumerable, IEnumerable> sorter) { if (sorter == null) { //this is pretty hackerific but saves us some code to write sorter = enumerable => { //semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison var entities = enumerable.OfType<IEntity>().ToList(); if (entities.Count > 0) { return entities.OrderBy(x => x.Id); } else { return enumerable; } }; } var actualListEx = sorter(actualList).Cast<object>().ToList(); var expectedListEx = sorter(expectedList).Cast<object>().ToList(); if (actualListEx.Count != expectedListEx.Count) Assert.Fail("Collection {0}.{1} does not match. Expected IEnumerable containing {2} elements but was IEnumerable containing {3} elements", property.PropertyType.Name, property.Name, expectedListEx.Count, actualListEx.Count); for (int i = 0; i < actualListEx.Count; i++) { var actualValue = actualListEx[i]; var expectedValue = expectedListEx[i]; if (((actualValue is string) == false) && actualValue is IEnumerable) { AssertListsAreEquals(property, (IEnumerable)actualValue, (IEnumerable)expectedValue, dateTimeFormat, sorter); } else if (dateTimeFormat.IsNullOrWhiteSpace() == false && actualValue is DateTime) { Assert.AreEqual(((DateTime)expectedValue).ToString(dateTimeFormat), ((DateTime)actualValue).ToString(dateTimeFormat), "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } else { Assert.AreEqual(expectedValue, actualValue, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } } } public static void DeleteDirectory(string path) { Try(() => { if (Directory.Exists(path) == false) return; foreach (var file in Directory.EnumerateFiles(path, "*", SearchOption.AllDirectories)) File.Delete(file); }); Try(() => { if (Directory.Exists(path) == false) return; Directory.Delete(path, true); }); } public static void TryAssert(Action action, int maxTries = 5, int waitMilliseconds = 200) { Try<AssertionException>(action, maxTries, waitMilliseconds); } public static void Try(Action action, int maxTries = 5, int waitMilliseconds = 200) { Try<Exception>(action, maxTries, waitMilliseconds); } public static void Try<T>(Action action, int maxTries = 5, int waitMilliseconds = 200) where T : Exception { var tries = 0; while (true) { try { action(); break; } catch (T) { if (tries++ > maxTries) throw; Thread.Sleep(waitMilliseconds); } } } } }
using System; using System.Data; using Csla; using Csla.Data; using ParentLoadSoftDelete.DataAccess; using ParentLoadSoftDelete.DataAccess.ERCLevel; namespace ParentLoadSoftDelete.Business.ERCLevel { /// <summary> /// F05_SubContinent_ReChild (editable child object).<br/> /// This is a generated base class of <see cref="F05_SubContinent_ReChild"/> business object. /// </summary> /// <remarks> /// This class is an item of <see cref="F04_SubContinent"/> collection. /// </remarks> [Serializable] public partial class F05_SubContinent_ReChild : BusinessBase<F05_SubContinent_ReChild> { #region State Fields [NotUndoable] [NonSerialized] internal int subContinent_ID2 = 0; #endregion #region Business Properties /// <summary> /// Maintains metadata about <see cref="SubContinent_Child_Name"/> property. /// </summary> public static readonly PropertyInfo<string> SubContinent_Child_NameProperty = RegisterProperty<string>(p => p.SubContinent_Child_Name, "Countries Child Name"); /// <summary> /// Gets or sets the Countries Child Name. /// </summary> /// <value>The Countries Child Name.</value> public string SubContinent_Child_Name { get { return GetProperty(SubContinent_Child_NameProperty); } set { SetProperty(SubContinent_Child_NameProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Creates a new <see cref="F05_SubContinent_ReChild"/> object. /// </summary> /// <returns>A reference to the created <see cref="F05_SubContinent_ReChild"/> object.</returns> internal static F05_SubContinent_ReChild NewF05_SubContinent_ReChild() { return DataPortal.CreateChild<F05_SubContinent_ReChild>(); } /// <summary> /// Factory method. Loads a <see cref="F05_SubContinent_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> /// <returns>A reference to the fetched <see cref="F05_SubContinent_ReChild"/> object.</returns> internal static F05_SubContinent_ReChild GetF05_SubContinent_ReChild(SafeDataReader dr) { F05_SubContinent_ReChild obj = new F05_SubContinent_ReChild(); // show the framework that this is a child object obj.MarkAsChild(); obj.Fetch(dr); obj.MarkOld(); // check all object rules and property rules obj.BusinessRules.CheckRules(); return obj; } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="F05_SubContinent_ReChild"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public F05_SubContinent_ReChild() { // Use factory methods and do not use direct creation. // show the framework that this is a child object MarkAsChild(); } #endregion #region Data Access /// <summary> /// Loads default values for the <see cref="F05_SubContinent_ReChild"/> object properties. /// </summary> [Csla.RunLocal] protected override void Child_Create() { var args = new DataPortalHookArgs(); OnCreate(args); base.Child_Create(); } /// <summary> /// Loads a <see cref="F05_SubContinent_ReChild"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(SubContinent_Child_NameProperty, dr.GetString("SubContinent_Child_Name")); // parent properties subContinent_ID2 = dr.GetInt32("SubContinent_ID2"); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Inserts a new <see cref="F05_SubContinent_ReChild"/> object in the database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Insert(F04_SubContinent parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnInsertPre(args); var dal = dalManager.GetProvider<IF05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { dal.Insert( parent.SubContinent_ID, SubContinent_Child_Name ); } OnInsertPost(args); } } /// <summary> /// Updates in the database all changes made to the <see cref="F05_SubContinent_ReChild"/> object. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_Update(F04_SubContinent parent) { if (!IsDirty) return; using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnUpdatePre(args); var dal = dalManager.GetProvider<IF05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { dal.Update( parent.SubContinent_ID, SubContinent_Child_Name ); } OnUpdatePost(args); } } /// <summary> /// Self deletes the <see cref="F05_SubContinent_ReChild"/> object from database. /// </summary> /// <param name="parent">The parent object.</param> [Transactional(TransactionalTypes.TransactionScope)] private void Child_DeleteSelf(F04_SubContinent parent) { using (var dalManager = DalFactoryParentLoadSoftDelete.GetManager()) { var args = new DataPortalHookArgs(); OnDeletePre(args); var dal = dalManager.GetProvider<IF05_SubContinent_ReChildDal>(); using (BypassPropertyChecks) { dal.Delete(parent.SubContinent_ID); } OnDeletePost(args); } } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting all defaults for object creation. /// </summary> partial void OnCreate(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after setting query parameters and before the delete operation. /// </summary> partial void OnDeletePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Delete, after the delete operation, before Commit(). /// </summary> partial void OnDeletePost(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); /// <summary> /// Occurs after setting query parameters and before the update operation. /// </summary> partial void OnUpdatePre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the update operation, before setting back row identifiers (RowVersion) and Commit(). /// </summary> partial void OnUpdatePost(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after setting query parameters and before the insert operation. /// </summary> partial void OnInsertPre(DataPortalHookArgs args); /// <summary> /// Occurs in DataPortal_Insert, after the insert operation, before setting back row identifiers (ID and RowVersion) and Commit(). /// </summary> partial void OnInsertPost(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace LumiSoft.Net.SIP.Message { /// <summary> /// Implements SIP "directive" value. Defined in RFC 3841. /// </summary> /// <remarks> /// <code> /// RFC 3841 Syntax: /// directive = proxy-directive / cancel-directive / fork-directive / recurse-directive / /// parallel-directive / queue-directive /// proxy-directive = "proxy" / "redirect" /// cancel-directive = "cancel" / "no-cancel" /// fork-directive = "fork" / "no-fork" /// recurse-directive = "recurse" / "no-recurse" /// parallel-directive = "parallel" / "sequential" /// queue-directive = "queue" / "no-queue" /// </code> /// </remarks> public class SIP_t_Directive : SIP_t_Value { #region enum DirectiveType /// <summary> /// Proccess directives. Defined in rfc 3841 9.1. /// </summary> public enum DirectiveType { /// <summary> /// This directive indicates whether the caller would like each server to proxy request. /// </summary> Proxy, /// <summary> /// This directive indicates whether the caller would like each server to redirect request. /// </summary> Redirect, /// <summary> /// This directive indicates whether the caller would like each proxy server to send a CANCEL /// request to forked branches. /// </summary> Cancel, /// <summary> /// This directive indicates whether the caller would NOT want each proxy server to send a CANCEL /// request to forked branches. /// </summary> NoCancel, /// <summary> /// This type of directive indicates whether a proxy should fork a request. /// </summary> Fork, /// <summary> /// This type of directive indicates whether a proxy should proxy to only a single address. /// The server SHOULD proxy the request to the "best" address (generally the one with the highest q-value). /// </summary> NoFork, /// <summary> /// This directive indicates whether a proxy server receiving a 3xx response should send /// requests to the addresses listed in the response. /// </summary> Recurse, /// <summary> /// This directive indicates whether a proxy server receiving a 3xx response should forward /// the list of addresses upstream towards the caller. /// </summary> NoRecurse, /// <summary> /// This directive indicates whether the caller would like the proxy server to proxy /// the request to all known addresses at once. /// </summary> Parallel, /// <summary> /// This directive indicates whether the caller would like the proxy server to go through /// all known addresses sequentially, contacting the next address only after it has received /// a non-2xx or non-6xx final response for the previous one. /// </summary> Sequential, /// <summary> /// This directive indicates whether if the called party is temporarily unreachable, caller /// wants to have its call queued. /// </summary> Queue, /// <summary> /// This directive indicates whether if the called party is temporarily unreachable, caller /// don't want its call to be queued. /// </summary> NoQueue } #endregion private DirectiveType m_Directive = DirectiveType.Fork; /// <summary> /// Default constructor. /// </summary> public SIP_t_Directive() { } #region method Parse /// <summary> /// Parses "directive" from specified value. /// </summary> /// <param name="value">SIP "directive" value.</param> /// <exception cref="ArgumentNullException">Raised when <b>value</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public void Parse(string value) { if(value == null){ throw new ArgumentNullException("value"); } Parse(new StringReader(value)); } /// <summary> /// Parses "directive" from specified reader. /// </summary> /// <param name="reader">Reader from where to parse.</param> /// <exception cref="ArgumentNullException">Raised when <b>reader</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public override void Parse(StringReader reader) { /* directive = proxy-directive / cancel-directive / fork-directive / recurse-directive / parallel-directive / queue-directive proxy-directive = "proxy" / "redirect" cancel-directive = "cancel" / "no-cancel" fork-directive = "fork" / "no-fork" recurse-directive = "recurse" / "no-recurse" parallel-directive = "parallel" / "sequential" queue-directive = "queue" / "no-queue" */ if(reader == null){ throw new ArgumentNullException("reader"); } // Get Method string word = reader.ReadWord(); if(word == null){ throw new SIP_ParseException("'directive' value is missing !"); } if(word.ToLower() == "proxy"){ m_Directive = DirectiveType.Proxy; } else if(word.ToLower() == "redirect"){ m_Directive = DirectiveType.Redirect; } else if(word.ToLower() == "cancel"){ m_Directive = DirectiveType.Cancel; } else if(word.ToLower() == "no-cancel"){ m_Directive = DirectiveType.NoCancel; } else if(word.ToLower() == "fork"){ m_Directive = DirectiveType.Fork; } else if(word.ToLower() == "no-fork"){ m_Directive = DirectiveType.NoFork; } else if(word.ToLower() == "recurse"){ m_Directive = DirectiveType.Recurse; } else if(word.ToLower() == "no-recurse"){ m_Directive = DirectiveType.NoRecurse; } else if(word.ToLower() == "parallel"){ m_Directive = DirectiveType.Parallel; } else if(word.ToLower() == "sequential"){ m_Directive = DirectiveType.Sequential; } else if(word.ToLower() == "queue"){ m_Directive = DirectiveType.Queue; } else if(word.ToLower() == "no-queue"){ m_Directive = DirectiveType.NoQueue; } else{ throw new SIP_ParseException("Invalid 'directive' value !"); } } #endregion #region method ToStringValue /// <summary> /// Converts this to valid "directive" value. /// </summary> /// <returns>Returns "directive" value.</returns> public override string ToStringValue() { /* directive = proxy-directive / cancel-directive / fork-directive / recurse-directive / parallel-directive / queue-directive proxy-directive = "proxy" / "redirect" cancel-directive = "cancel" / "no-cancel" fork-directive = "fork" / "no-fork" recurse-directive = "recurse" / "no-recurse" parallel-directive = "parallel" / "sequential" queue-directive = "queue" / "no-queue" */ if(m_Directive == DirectiveType.Proxy){ return "proxy"; } else if(m_Directive == DirectiveType.Redirect){ return "redirect"; } else if(m_Directive == DirectiveType.Cancel){ return "cancel"; } else if(m_Directive == DirectiveType.NoCancel){ return "no-cancel"; } else if(m_Directive == DirectiveType.Fork){ return "fork"; } else if(m_Directive == DirectiveType.NoFork){ return "no-fork"; } else if(m_Directive == DirectiveType.Recurse){ return "recurse"; } else if(m_Directive == DirectiveType.NoRecurse){ return "no-recurse"; } else if(m_Directive == DirectiveType.Parallel){ return "parallel"; } else if(m_Directive == DirectiveType.Sequential){ return "sequential"; } else if(m_Directive == DirectiveType.Queue){ return "queue"; } else if(m_Directive == DirectiveType.NoQueue){ return "no-queue"; } else{ throw new ArgumentException("Invalid property Directive value, this should never happen !"); } } #endregion #region Properties Implementation /// <summary> /// Gets or sets directive. /// </summary> public DirectiveType Directive { get{ return m_Directive; } set{ m_Directive = value; } } #endregion } }
using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Infoplus.Model { /// <summary> /// /// </summary> [DataContract] public partial class ReplenishmentPlan : IEquatable<ReplenishmentPlan> { /// <summary> /// Initializes a new instance of the <see cref="ReplenishmentPlan" /> class. /// Initializes a new instance of the <see cref="ReplenishmentPlan" />class. /// </summary> /// <param name="WarehouseId">WarehouseId (required).</param> /// <param name="PickFaceAssignmentSmartFilterId">PickFaceAssignmentSmartFilterId (required).</param> /// <param name="Name">Name (required).</param> /// <param name="CustomFields">CustomFields.</param> public ReplenishmentPlan(int? WarehouseId = null, int? PickFaceAssignmentSmartFilterId = null, string Name = null, Dictionary<string, Object> CustomFields = null) { // to ensure "WarehouseId" is required (not null) if (WarehouseId == null) { throw new InvalidDataException("WarehouseId is a required property for ReplenishmentPlan and cannot be null"); } else { this.WarehouseId = WarehouseId; } // to ensure "PickFaceAssignmentSmartFilterId" is required (not null) if (PickFaceAssignmentSmartFilterId == null) { throw new InvalidDataException("PickFaceAssignmentSmartFilterId is a required property for ReplenishmentPlan and cannot be null"); } else { this.PickFaceAssignmentSmartFilterId = PickFaceAssignmentSmartFilterId; } // to ensure "Name" is required (not null) if (Name == null) { throw new InvalidDataException("Name is a required property for ReplenishmentPlan and cannot be null"); } else { this.Name = Name; } this.CustomFields = CustomFields; } /// <summary> /// Gets or Sets Id /// </summary> [DataMember(Name="id", EmitDefaultValue=false)] public int? Id { get; private set; } /// <summary> /// Gets or Sets CreateDate /// </summary> [DataMember(Name="createDate", EmitDefaultValue=false)] public DateTime? CreateDate { get; private set; } /// <summary> /// Gets or Sets ModifyDate /// </summary> [DataMember(Name="modifyDate", EmitDefaultValue=false)] public DateTime? ModifyDate { get; private set; } /// <summary> /// Gets or Sets WarehouseId /// </summary> [DataMember(Name="warehouseId", EmitDefaultValue=false)] public int? WarehouseId { get; set; } /// <summary> /// Gets or Sets PickFaceAssignmentSmartFilterId /// </summary> [DataMember(Name="pickFaceAssignmentSmartFilterId", EmitDefaultValue=false)] public int? PickFaceAssignmentSmartFilterId { get; set; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Gets or Sets CustomFields /// </summary> [DataMember(Name="customFields", EmitDefaultValue=false)] public Dictionary<string, Object> CustomFields { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ReplenishmentPlan {\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" CreateDate: ").Append(CreateDate).Append("\n"); sb.Append(" ModifyDate: ").Append(ModifyDate).Append("\n"); sb.Append(" WarehouseId: ").Append(WarehouseId).Append("\n"); sb.Append(" PickFaceAssignmentSmartFilterId: ").Append(PickFaceAssignmentSmartFilterId).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" CustomFields: ").Append(CustomFields).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as ReplenishmentPlan); } /// <summary> /// Returns true if ReplenishmentPlan instances are equal /// </summary> /// <param name="other">Instance of ReplenishmentPlan to be compared</param> /// <returns>Boolean</returns> public bool Equals(ReplenishmentPlan other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.CreateDate == other.CreateDate || this.CreateDate != null && this.CreateDate.Equals(other.CreateDate) ) && ( this.ModifyDate == other.ModifyDate || this.ModifyDate != null && this.ModifyDate.Equals(other.ModifyDate) ) && ( this.WarehouseId == other.WarehouseId || this.WarehouseId != null && this.WarehouseId.Equals(other.WarehouseId) ) && ( this.PickFaceAssignmentSmartFilterId == other.PickFaceAssignmentSmartFilterId || this.PickFaceAssignmentSmartFilterId != null && this.PickFaceAssignmentSmartFilterId.Equals(other.PickFaceAssignmentSmartFilterId) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.CustomFields == other.CustomFields || this.CustomFields != null && this.CustomFields.SequenceEqual(other.CustomFields) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.Id != null) hash = hash * 59 + this.Id.GetHashCode(); if (this.CreateDate != null) hash = hash * 59 + this.CreateDate.GetHashCode(); if (this.ModifyDate != null) hash = hash * 59 + this.ModifyDate.GetHashCode(); if (this.WarehouseId != null) hash = hash * 59 + this.WarehouseId.GetHashCode(); if (this.PickFaceAssignmentSmartFilterId != null) hash = hash * 59 + this.PickFaceAssignmentSmartFilterId.GetHashCode(); if (this.Name != null) hash = hash * 59 + this.Name.GetHashCode(); if (this.CustomFields != null) hash = hash * 59 + this.CustomFields.GetHashCode(); return hash; } } } }
using Orleans.Persistence.AdoNet.Storage; using Orleans.Providers; using Orleans.Runtime; using Orleans.Serialization; using System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Configuration; using Orleans.Configuration.Overrides; namespace Orleans.Storage { /// <summary> /// Logging codes used by <see cref="AdoNetGrainStorage"/>. /// </summary> /// <remarks> These are taken from <em>Orleans.Providers.ProviderErrorCode</em> and <em>Orleans.Providers.AzureProviderErrorCode</em>.</remarks> internal enum RelationalStorageProviderCodes { //These is from Orleans.Providers.ProviderErrorCode and Orleans.Providers.AzureProviderErrorCode. ProvidersBase = 200000, RelationalProviderBase = ProvidersBase + 400, RelationalProviderDeleteError = RelationalProviderBase + 8, RelationalProviderInitProvider = RelationalProviderBase + 9, RelationalProviderNoDeserializer = RelationalProviderBase + 10, RelationalProviderNoStateFound = RelationalProviderBase + 11, RelationalProviderClearing = RelationalProviderBase + 12, RelationalProviderCleared = RelationalProviderBase + 13, RelationalProviderReading = RelationalProviderBase + 14, RelationalProviderRead = RelationalProviderBase + 15, RelationalProviderReadError = RelationalProviderBase + 16, RelationalProviderWriting = RelationalProviderBase + 17, RelationalProviderWrote = RelationalProviderBase + 18, RelationalProviderWriteError = RelationalProviderBase + 19 } public static class AdoNetGrainStorageFactory { public static IGrainStorage Create(IServiceProvider services, string name) { var optionsMonitor = services.GetRequiredService<IOptionsMonitor<AdoNetGrainStorageOptions>>(); var clusterOptions = services.GetProviderClusterOptions(name); return ActivatorUtilities.CreateInstance<AdoNetGrainStorage>(services, Options.Create(optionsMonitor.Get(name)), name, clusterOptions); } } /// <summary> /// A storage provider for writing grain state data to relational storage. /// </summary> /// <remarks> /// <para> /// Required configuration params: <c>DataConnectionString</c> /// </para> /// <para> /// Optional configuration params: /// <c>AdoInvariant</c> -- defaults to <c>System.Data.SqlClient</c> /// <c>UseJsonFormat</c> -- defaults to <c>false</c> /// <c>UseXmlFormat</c> -- defaults to <c>false</c> /// <c>UseBinaryFormat</c> -- defaults to <c>true</c> /// </para> /// </remarks> [DebuggerDisplay("Name = {Name}, ConnectionString = {Storage.ConnectionString}")] public class AdoNetGrainStorage: IGrainStorage, ILifecycleParticipant<ISiloLifecycle> { private SerializationManager serializationManager; /// <summary> /// Tag for BinaryFormatSerializer /// </summary> public const string BinaryFormatSerializerTag = "BinaryFormatSerializer"; /// <summary> /// Tag for JsonFormatSerializer /// </summary> public const string JsonFormatSerializerTag = "JsonFormatSerializer"; /// <summary> /// Tag for XmlFormatSerializer /// </summary> public const string XmlFormatSerializerTag = "XmlFormatSerializer"; /// <summary> /// The Service ID for which this relational provider is used. /// </summary> private readonly string serviceId; private readonly ILogger logger; /// <summary> /// The storage used for back-end operations. /// </summary> private IRelationalStorage Storage { get; set; } /// <summary> /// These chars are delimiters when used to extract a class base type from a class /// that is either <see cref="Type.AssemblyQualifiedName"/> or <see cref="Type.FullName"/>. /// <see cref="ExtractBaseClass(string)"/>. /// </summary> private static char[] BaseClassExtractionSplitDelimeters { get; } = new[] { '[', ']' }; /// <summary> /// The default query to initialize this structure from the Orleans database. /// </summary> public const string DefaultInitializationQuery = "SELECT QueryKey, QueryText FROM OrleansQuery WHERE QueryKey = 'WriteToStorageKey' OR QueryKey = 'ReadFromStorageKey' OR QueryKey = 'ClearStorageKey'"; /// <summary> /// The queries currently used. When this is updated, the new queries will take effect immediately. /// </summary> public RelationalStorageProviderQueries CurrentOperationalQueries { get; set; } /// <summary> /// A strategy to pick a serializer or a deserializer for storage operations. This can be used to: /// 1) Add a custom serializer or deserializer for use in storage provider operations. /// 2) In combination with serializer or deserializer to update stored object version. /// 3) Per-grain storage format selection /// 4) Switch storage format first by reading using the save format and then writing in the new format. /// </summary> public IStorageSerializationPicker StorageSerializationPicker { get; set; } /// <summary> /// The hash generator used to hash natural keys, grain ID and grain type to a more narrow index. /// </summary> public IStorageHasherPicker HashPicker { get; set; } = new StorageHasherPicker(new[] { new OrleansDefaultHasher() }); private readonly AdoNetGrainStorageOptions options; private readonly IProviderRuntime providerRuntime; private readonly string name; public AdoNetGrainStorage( ILogger<AdoNetGrainStorage> logger, IProviderRuntime providerRuntime, IOptions<AdoNetGrainStorageOptions> options, IOptions<ClusterOptions> clusterOptions, string name) { this.options = options.Value; this.providerRuntime = providerRuntime; this.name = name; this.logger = logger; this.serviceId = clusterOptions.Value.ServiceId; } public void Participate(ISiloLifecycle lifecycle) { lifecycle.Subscribe(OptionFormattingUtilities.Name<AdoNetGrainStorage>(this.name), this.options.InitStage, Init, Close); } /// <summary>Clear state data function for this storage provider.</summary> /// <see cref="IGrainStorage.ClearStateAsync(string, GrainReference, IGrainState)"/>. public async Task ClearStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { //It assumed these parameters are always valid. If not, an exception will be thrown, //even if not as clear as when using explicitly checked parameters. var grainId = GrainIdAndExtensionAsString(grainReference); var baseGrainType = ExtractBaseClass(grainType); if(logger.IsEnabled(LogLevel.Trace)) { logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderClearing, LogString("Clearing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); } string storageVersion = null; try { var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes()); var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType)); var clearRecord = (await Storage.ReadAsync(CurrentOperationalQueries.ClearState, command => { command.AddParameter("GrainIdHash", grainIdHash); command.AddParameter("GrainIdN0", grainId.N0Key); command.AddParameter("GrainIdN1", grainId.N1Key); command.AddParameter("GrainTypeHash", grainTypeHash); command.AddParameter("GrainTypeString", baseGrainType); command.AddParameter("GrainIdExtensionString", grainId.StringKey); command.AddParameter("ServiceId", serviceId); command.AddParameter("GrainStateVersion", !string.IsNullOrWhiteSpace(grainState.ETag) ? int.Parse(grainState.ETag, CultureInfo.InvariantCulture) : default(int?)); }, (selector, resultSetCount, token) => Task.FromResult(selector.GetValue(0).ToString()), CancellationToken.None).ConfigureAwait(false)); storageVersion = clearRecord.SingleOrDefault(); } catch(Exception ex) { logger.Error((int)RelationalStorageProviderCodes.RelationalProviderDeleteError, LogString("Error clearing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex); throw; } const string OperationString = "ClearState"; var inconsistentStateException = CheckVersionInconsistency(OperationString, serviceId, this.name, storageVersion, grainState.ETag, baseGrainType, grainId.ToString()); if(inconsistentStateException != null) { throw inconsistentStateException; } //No errors found, the version of the state held by the grain can be updated and also the state. grainState.ETag = storageVersion; if(logger.IsEnabled(LogLevel.Trace)) { logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderCleared, LogString("Cleared grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); } } /// <summary> Read state data function for this storage provider.</summary> /// <see cref="IGrainStorage.ReadStateAsync(string, GrainReference, IGrainState)"/>. public async Task ReadStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { //It assumed these parameters are always valid. If not, an exception will be thrown, even if not as clear //as with explicitly checked parameters. var grainId = GrainIdAndExtensionAsString(grainReference); var baseGrainType = ExtractBaseClass(grainType); if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderReading, LogString("Reading grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); } try { SerializationChoice choice =StorageSerializationPicker.PickDeserializer(serviceId, this.name, baseGrainType, grainReference, grainState, null); if(choice.Deserializer == null) { var errorString = LogString("No deserializer found", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString()); logger.Error((int)RelationalStorageProviderCodes.RelationalProviderNoDeserializer, errorString); throw new InvalidOperationException(errorString); } var commandBehavior = choice.PreferStreaming ? CommandBehavior.SequentialAccess : CommandBehavior.Default; var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes()); var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType)); var readRecords = (await Storage.ReadAsync(CurrentOperationalQueries.ReadFromStorage, (command => { command.AddParameter("GrainIdHash", grainIdHash); command.AddParameter("GrainIdN0", grainId.N0Key); command.AddParameter("GrainIdN1", grainId.N1Key); command.AddParameter("GrainTypeHash", grainTypeHash); command.AddParameter("GrainTypeString", baseGrainType); command.AddParameter("GrainIdExtensionString", grainId.StringKey); command.AddParameter("ServiceId", serviceId); }), async (selector, resultSetCount, token) => { object storageState = null; int? version; if(choice.PreferStreaming) { //When streaming via ADO.NET, using CommandBehavior.SequentialAccess, the order of //the columns on how they are read needs to be exactly this. const int binaryColumnPositionInSelect = 0; const int xmlColumnPositionInSelect = 1; const int jsonColumnPositionInSelect = 2; var streamSelector = (DbDataReader)selector; if(!(await streamSelector.IsDBNullAsync(binaryColumnPositionInSelect))) { using(var downloadStream = streamSelector.GetStream(binaryColumnPositionInSelect, Storage)) { storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type); } } if(!(await streamSelector.IsDBNullAsync(xmlColumnPositionInSelect))) { using(var downloadStream = streamSelector.GetTextReader(xmlColumnPositionInSelect)) { storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type); } } if(!(await streamSelector.IsDBNullAsync(jsonColumnPositionInSelect))) { using(var downloadStream = streamSelector.GetTextReader(jsonColumnPositionInSelect)) { storageState = choice.Deserializer.Deserialize(downloadStream, grainState.Type); } } version = await streamSelector.GetValueAsync<int?>("Version"); } else { //All but one of these should be null. All will be read and an appropriate deserializer picked. //NOTE: When streaming will be implemented, it is worthwhile to optimize this so that the defined //serializer will be picked and then streaming tried according to its tag. object payload; payload = selector.GetValueOrDefault<byte[]>("PayloadBinary"); if(payload == null) { payload = selector.GetValueOrDefault<string>("PayloadXml"); } if(payload == null) { payload = selector.GetValueOrDefault<string>("PayloadJson"); } if(payload != null) { storageState = choice.Deserializer.Deserialize(payload, grainState.Type); } version = selector.GetNullableInt32("Version"); } return Tuple.Create(storageState, version?.ToString(CultureInfo.InvariantCulture)); }, CancellationToken.None, commandBehavior).ConfigureAwait(false)).SingleOrDefault(); object state = readRecords != null ? readRecords.Item1 : null; string etag = readRecords != null ? readRecords.Item2 : null; if(state == null) { logger.Info((int)RelationalStorageProviderCodes.RelationalProviderNoStateFound, LogString("Null grain state read (default will be instantiated)", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); state = Activator.CreateInstance(grainState.Type); } grainState.State = state; grainState.ETag = etag; if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderRead, LogString("Read grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); } } catch(Exception ex) { logger.Error((int)RelationalStorageProviderCodes.RelationalProviderReadError, LogString("Error reading grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex); throw; } } /// <summary> Write state data function for this storage provider.</summary> /// <see cref="IGrainStorage.WriteStateAsync"/> public async Task WriteStateAsync(string grainType, GrainReference grainReference, IGrainState grainState) { //It assumed these parameters are always valid. If not, an exception will be thrown, even if not as clear //as with explicitly checked parameters. var data = grainState.State; var grainId = GrainIdAndExtensionAsString(grainReference); var baseGrainType = ExtractBaseClass(grainType); if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderWriting, LogString("Writing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); } string storageVersion = null; try { var grainIdHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(grainId.GetHashBytes()); var grainTypeHash = HashPicker.PickHasher(serviceId, this.name, baseGrainType, grainReference, grainState).Hash(Encoding.UTF8.GetBytes(baseGrainType)); var writeRecord = await Storage.ReadAsync(CurrentOperationalQueries.WriteToStorage, command => { command.AddParameter("GrainIdHash", grainIdHash); command.AddParameter("GrainIdN0", grainId.N0Key); command.AddParameter("GrainIdN1", grainId.N1Key); command.AddParameter("GrainTypeHash", grainTypeHash); command.AddParameter("GrainTypeString", baseGrainType); command.AddParameter("GrainIdExtensionString", grainId.StringKey); command.AddParameter("ServiceId", serviceId); command.AddParameter("GrainStateVersion", !string.IsNullOrWhiteSpace(grainState.ETag) ? int.Parse(grainState.ETag, CultureInfo.InvariantCulture) : default(int?)); SerializationChoice serializer = StorageSerializationPicker.PickSerializer(serviceId, this.name, baseGrainType, grainReference, grainState); command.AddParameter("PayloadBinary", (byte[])(serializer.Serializer.Tag == BinaryFormatSerializerTag ? serializer.Serializer.Serialize(data) : null)); command.AddParameter("PayloadJson", (string)(serializer.Serializer.Tag == JsonFormatSerializerTag ? serializer.Serializer.Serialize(data) : null)); command.AddParameter("PayloadXml", (string)(serializer.Serializer.Tag == XmlFormatSerializerTag ? serializer.Serializer.Serialize(data) : null)); }, (selector, resultSetCount, token) => { return Task.FromResult(selector.GetNullableInt32("NewGrainStateVersion").ToString()); }, CancellationToken.None).ConfigureAwait(false); storageVersion = writeRecord.SingleOrDefault(); } catch(Exception ex) { logger.Error((int)RelationalStorageProviderCodes.RelationalProviderWriteError, LogString("Error writing grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString(), ex.Message), ex); throw; } const string OperationString = "WriteState"; var inconsistentStateException = CheckVersionInconsistency(OperationString, serviceId, this.name, storageVersion, grainState.ETag, baseGrainType, grainId.ToString()); if(inconsistentStateException != null) { throw inconsistentStateException; } //No errors found, the version of the state held by the grain can be updated. grainState.ETag = storageVersion; if (logger.IsEnabled(LogLevel.Trace)) { logger.Trace((int)RelationalStorageProviderCodes.RelationalProviderWrote, LogString("Wrote grain state", serviceId, this.name, grainState.ETag, baseGrainType, grainId.ToString())); } } /// <summary> Initialization function for this storage provider. </summary> private async Task Init(CancellationToken cancellationToken) { this.serializationManager = providerRuntime.ServiceProvider.GetRequiredService<SerializationManager>(); //NOTE: StorageSerializationPicker should be defined outside and given as a parameter in constructor or via Init in IProviderConfiguration perhaps. //Currently this limits one's options to much to the current situation of providing only one serializer for serialization and deserialization //with no regard to state update or serializer changes. Maybe have this serialized as a JSON in props and read via a key? StorageSerializationPicker = new DefaultRelationalStoragePicker(this.ConfigureDeserializers(options, providerRuntime), this.ConfigureSerializers(options, providerRuntime)); Storage = RelationalStorage.CreateInstance(options.Invariant, options.ConnectionString); var queries = await Storage.ReadAsync(DefaultInitializationQuery, command => { }, (selector, resultSetCount, token) => { return Task.FromResult(Tuple.Create(selector.GetValue<string>("QueryKey"), selector.GetValue<string>("QueryText"))); }).ConfigureAwait(false); CurrentOperationalQueries = new RelationalStorageProviderQueries( queries.Single(i => i.Item1 == "WriteToStorageKey").Item2, queries.Single(i => i.Item1 == "ReadFromStorageKey").Item2, queries.Single(i => i.Item1 == "ClearStorageKey").Item2); logger.Info((int)RelationalStorageProviderCodes.RelationalProviderInitProvider, $"Initialized storage provider: ServiceId={serviceId} ProviderName={this.name} Invariant={Storage.InvariantName} ConnectionString={Storage.ConnectionString}."); } /// <summary> /// Close this provider /// </summary> private Task Close(CancellationToken token) { return Task.CompletedTask; } /// <summary> /// Checks for version inconsistency as defined in the database scripts. /// </summary> /// <param name="serviceId">Service Id.</param> /// <param name="providerName">The name of this storage provider.</param> /// <param name="operation">The operation attempted.</param> /// <param name="storageVersion">The version from storage.</param> /// <param name="grainVersion">The grain version.</param> /// <param name="normalizedGrainType">Grain type without generics information.</param> /// <param name="grainId">The grain ID.</param> /// <returns>An exception for throwing or <em>null</em> if no violation was detected.</returns> /// <remarks>This means that the version was not updated in the database or the version storage version was something else than null /// when the grain version was null, meaning effectively a double activation and save.</remarks> private static InconsistentStateException CheckVersionInconsistency(string operation, string serviceId, string providerName, string storageVersion, string grainVersion, string normalizedGrainType, string grainId) { //If these are the same, it means no row was inserted or updated in the storage. //Effectively it means the UPDATE or INSERT conditions failed due to ETag violation. //Also if grainState.ETag storageVersion is null and storage comes back as null, //it means two grains were activated an the other one succeeded in writing its state. // //NOTE: the storage could return also the new and old ETag (Version), but currently it doesn't. if(storageVersion == grainVersion || storageVersion == string.Empty) { //TODO: Note that this error message should be canonical across back-ends. return new InconsistentStateException($"Version conflict ({operation}): ServiceId={serviceId} ProviderName={providerName} GrainType={normalizedGrainType} GrainId={grainId} ETag={grainVersion}."); } return null; } /// <summary> /// Writes a consistent log message from the given parameters. /// </summary> /// <param name="operationProlog">A free form prolog information to log.</param> /// <param name="serviceId">Service Id.</param> /// <param name="providerName">The name of this storage provider.</param> /// <param name="version">The grain version.</param> /// <param name="normalizedGrainType">Grain type without generics information.</param> /// <param name="grainId">The grain ID.</param> /// <param name="exceptionMessage">An optional exception message information to log.</param> /// <returns>A log string to be printed.</returns> private string LogString(string operationProlog, string serviceId, string providerName, string version, string normalizedGrainType, string grainId, string exceptionMessage = null) { const string Exception = " Exception="; return $"{operationProlog}: ServiceId={serviceId} ProviderName={providerName} GrainType={normalizedGrainType} GrainId={grainId} ETag={version}{(exceptionMessage != null ? Exception + exceptionMessage : string.Empty)}."; } /// <summary> /// Extracts a grain ID as a string and appends the key extension with '#' infix is present. /// </summary> /// <param name="grainReference">The reference from which to extract the ID.</param> /// <returns>The grain ID as a string.</returns> /// <remarks>This likely should exist in Orleans core in more optimized form.</remarks> private static AdoGrainKey GrainIdAndExtensionAsString(GrainReference grainReference) { //Kudos for https://github.com/tsibelman for the algorithm. See more at https://github.com/dotnet/orleans/issues/1905. string keyExtension; AdoGrainKey key; if(grainReference.IsPrimaryKeyBasedOnLong()) { key = new AdoGrainKey(grainReference.GetPrimaryKeyLong(out keyExtension), keyExtension); } else { key = new AdoGrainKey(grainReference.GetPrimaryKey(out keyExtension), keyExtension); } return key; } /// <summary> /// Extracts a base class from a string that is either <see cref="Type.AssemblyQualifiedName"/> or /// <see cref="Type.FullName"/> or returns the one given as a parameter if no type is given. /// </summary> /// <param name="typeName">The base class name to give.</param> /// <returns>The extracted base class or the one given as a parameter if it didn't have a generic part.</returns> private static string ExtractBaseClass(string typeName) { var genericPosition = typeName.IndexOf("`", StringComparison.OrdinalIgnoreCase); if (genericPosition != -1) { //The following relies the generic argument list to be in form as described //at https://msdn.microsoft.com/en-us/library/w3f99sx1.aspx. var split = typeName.Split(BaseClassExtractionSplitDelimeters, StringSplitOptions.RemoveEmptyEntries); var stripped = new Queue<string>(split.Where(i => i.Length > 1 && i[0] != ',').Select(WithoutAssemblyVersion)); return ReformatClassName(stripped); } return typeName; string WithoutAssemblyVersion(string input) { var asmNameIndex = input.IndexOf(','); if (asmNameIndex >= 0) { var asmVersionIndex = input.IndexOf(',', asmNameIndex + 1); if (asmVersionIndex >= 0) return input.Substring(0, asmVersionIndex); return input.Substring(0, asmNameIndex); } return input; } string ReformatClassName(Queue<string> segments) { var simpleTypeName = segments.Dequeue(); var arity = GetGenericArity(simpleTypeName); if (arity <= 0) return simpleTypeName; var args = new List<string>(arity); for (var i = 0; i < arity; i++) { args.Add(ReformatClassName(segments)); } return $"{simpleTypeName}[{string.Join(",", args.Select(arg => $"[{arg}]"))}]"; } int GetGenericArity(string input) { var arityIndex = input.IndexOf("`", StringComparison.OrdinalIgnoreCase); if (arityIndex != -1) { return int.Parse(input.Substring(arityIndex + 1)); } return 0; } } private ICollection<IStorageDeserializer> ConfigureDeserializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime) { var deserializers = new List<IStorageDeserializer>(); if(options.UseJsonFormat) { var typeResolver = providerRuntime.ServiceProvider.GetRequiredService<ITypeResolver>(); var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory), options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling); options.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); deserializers.Add(new OrleansStorageDefaultJsonDeserializer(jsonSettings, JsonFormatSerializerTag)); } if(options.UseXmlFormat) { deserializers.Add(new OrleansStorageDefaultXmlDeserializer(XmlFormatSerializerTag)); } //if none are set true, configure binary format serializer by default if(!options.UseXmlFormat && !options.UseJsonFormat) { deserializers.Add(new OrleansStorageDefaultBinaryDeserializer(this.serializationManager, BinaryFormatSerializerTag)); } return deserializers; } private ICollection<IStorageSerializer> ConfigureSerializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime) { var serializers = new List<IStorageSerializer>(); if(options.UseJsonFormat) { var typeResolver = providerRuntime.ServiceProvider.GetRequiredService<ITypeResolver>(); var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory), options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling); options.ConfigureJsonSerializerSettings?.Invoke(jsonSettings); serializers.Add(new OrleansStorageDefaultJsonSerializer(jsonSettings, JsonFormatSerializerTag)); } if(options.UseXmlFormat) { serializers.Add(new OrleansStorageDefaultXmlSerializer(XmlFormatSerializerTag)); } //if none are set true, configure binary format serializer by default if (!options.UseXmlFormat && !options.UseJsonFormat) { serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializationManager, BinaryFormatSerializerTag)); } return serializers; } } }
/** * Copyright 2013 Mehran Ziadloo * WSS: A WebSocket Server written in C# and .Net (Mono) * (https://github.com/ziadloo/WSS) * * 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 Base; using System.Text.RegularExpressions; using System.Security.Cryptography; using System.Text; namespace Protocol { public class Draft10 : Draft { protected static readonly string rfc_guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; #region implemented abstract members of Draft for server public override Header ParseClientRequestHandshake(List<byte> buffer) { int bufferUsed = 0; Header h = _parseClientHandshake(buffer, ref bufferUsed); string v = h.Get("Sec-WebSocket-Version"); int vv = Int32.Parse(v.Trim()); if (vv != 7 && vv != 8) { throw new Exception(); } buffer.RemoveRange(0, bufferUsed); return h; } public override byte[] CreateServerResponseHandshake(Header header) { Header h = _createResponseHandshake(header); return h.ToBytes(); } public override Frame ParseClientFrameBytes(List<byte> buffer) { if (buffer.Count < 2) { return null; } byte opcode = (byte)(buffer[0] & 0x0F); bool isMasked = Convert.ToBoolean((buffer[1] & 0x80) >> 7);//(buffer[1] & 0x01) == 1; int payloadLength = (byte) (buffer[1] & 0x7F); Frame.OpCodeType op; switch (opcode) { case 1: op = Frame.OpCodeType.Text; break; case 2: op = Frame.OpCodeType.Binary; break; case 8: op = Frame.OpCodeType.Close; break; case 9: op = Frame.OpCodeType.Ping; break; case 10: op = Frame.OpCodeType.Pong; break; default: // Close connection on unknown opcode: op = Frame.OpCodeType.Close; break; } byte[] mask; int payloadOffset; int dataLength; if (payloadLength == 126) { mask = buffer.GetRange(4, 4).ToArray(); payloadOffset = 8; byte[] temp = buffer.GetRange(2, 2).ToArray(); Array.Reverse(temp); dataLength = BitConverter.ToUInt16(temp, 0) + payloadOffset; } else if (payloadLength == 127) { mask = buffer.GetRange(10, 4).ToArray(); payloadOffset = 14; byte[] temp = buffer.GetRange(2, 8).ToArray(); Array.Reverse(temp); dataLength = (int)(BitConverter.ToUInt64(temp, 0)) + payloadOffset; } else { mask = buffer.GetRange(2, 4).ToArray(); payloadOffset = 6; dataLength = payloadLength + payloadOffset; } /** * We have to check for large frames here. socket_recv cuts at 1024 bytes * so if websocket-frame is > 1024 bytes we have to wait until whole * data is transferd. */ if (buffer.Count < dataLength) { return null; } if (isMasked) { int j; for (int i = payloadOffset; i < dataLength; i++) { j = i - payloadOffset; buffer[i] = (byte)(buffer[i] ^ mask[j % 4]); } } else { payloadOffset = payloadOffset - 4; } switch (op) { case Frame.OpCodeType.Binary: { byte[] data = buffer.GetRange(payloadOffset, dataLength - payloadOffset).ToArray(); buffer.RemoveRange(0, dataLength); return new Frame(data); } case Frame.OpCodeType.Text: { byte[] data = buffer.GetRange(payloadOffset, dataLength - payloadOffset).ToArray(); buffer.RemoveRange(0, dataLength); return new Frame(System.Text.Encoding.UTF8.GetString(data)); } default: { byte[] data = buffer.GetRange(payloadOffset, dataLength - payloadOffset).ToArray(); buffer.RemoveRange(0, dataLength); return new Frame(op, data); } } } public override byte[] CreateServerFrameBytes(Frame frame) { byte[] data = new byte[0]; if (frame.Data != null) { data = frame.Data; } else if (frame.Message != null) { data = System.Text.Encoding.UTF8.GetBytes(frame.Message); } List<byte> frameBytes = new List<byte>(); int payloadLength = data.Length; frameBytes.Add(0); switch (frame.OpCode) { case Frame.OpCodeType.Text: // first byte indicates FIN, Text-Frame (10000001): frameBytes[0] = 129; break; case Frame.OpCodeType.Close: // first byte indicates FIN, Close Frame(10001000): frameBytes[0] = 136; break; case Frame.OpCodeType.Ping: // first byte indicates FIN, Ping frame (10001001): frameBytes[0] = 137; break; case Frame.OpCodeType.Pong: // first byte indicates FIN, Pong frame (10001010): frameBytes[0] = 138; break; } // set mask and payload length (using 1, 3 or 9 bytes) if (payloadLength > 65535) { byte[] temp = BitConverter.GetBytes((long)payloadLength); Array.Reverse(temp); frameBytes.Add(0); frameBytes[1] = 127; for (int i = 0; i < 8; i++) { frameBytes.Add(0); frameBytes[i+2] = temp[i]; } // most significant bit MUST be 0 (close connection if frame too big) if (frameBytes[2] > 127) { //$this->close(1004); } } else if (payloadLength > 125) { byte[] temp = BitConverter.GetBytes((Int16)payloadLength); frameBytes.Add(0); frameBytes[1] = 126; frameBytes.Add(0); frameBytes[2] = temp[1]; frameBytes.Add(0); frameBytes[3] = temp[0]; } else { frameBytes.Add(0); frameBytes[1] = (byte)(payloadLength); } // append payload to frame: for (int i = 0; i < payloadLength; i++) { frameBytes.Add(data[i]); } return frameBytes.ToArray(); } #endregion #region implemented abstract members of Draft for client public override byte[] CreateClientRequestHandshake(string url, out string expectedAccept) { Header header = _createRequestHandshake(url, out expectedAccept); return header.ToBytes(); } public override Header ParseServerResponseHandshake(List<byte> buffer) { int bufferUsed = 0; Header h = _parseServerHandshake(buffer, ref bufferUsed); string v = h.Get("Sec-WebSocket-Version"); int vv = Int32.Parse(v.Trim()); if (vv != 7 && vv != 8) { throw new Exception(); } buffer.RemoveRange(0, bufferUsed); return h; } public override byte[] CreateClientFrameBytes(Frame frame) { byte[] data = new byte[0]; if (frame.Data != null) { data = frame.Data; } else if (frame.Message != null) { data = System.Text.Encoding.UTF8.GetBytes(frame.Message); } List<byte> frameBytes = new List<byte>(); int payloadLength = data.Length; frameBytes.Add(0); if (payloadLength < 126) { frameBytes.Add((byte)payloadLength); } else if (payloadLength < 65536) { frameBytes.Add((byte)126); frameBytes.Add((byte)(payloadLength / 256)); frameBytes.Add((byte)(payloadLength % 256)); } else { frameBytes.Add((byte)127); int left = payloadLength; int unit = 256; byte[] fragment = new byte[10]; for (int i = 9; i > 1; i--) { fragment[i] = (byte)(left % unit); left = left / unit; if (left == 0) { break; } } for (int i = 2; i < 10; i++) { frameBytes.Add(fragment[i]); } } //Set FIN frameBytes[0] = (byte)((byte)frame.OpCode | 0x80); //Set mask bit frameBytes[1] = (byte)(frameBytes[1] | 0x80); //Mask byte[] mask = new byte[4]; for (int i = 0; i < 4; i++) { mask[i] = (byte)(DateTime.Now.Ticks % 256); frameBytes.Add(mask[i]); } for (var i = 0; i < payloadLength; i++) { frameBytes.Add((byte)(data[i] ^ mask[i % 4])); } return frameBytes.ToArray(); } public override Frame ParseServerFrameBytes(List<byte> buffer) { if (buffer.Count < 2) { return null; } // FIN Frame.FinType fin = (buffer[0] & 0x80) == 0x80 ? Frame.FinType.Final : Frame.FinType.More; // RSV1 Frame.RsvType rsv1 = (buffer[0] & 0x40) == 0x40 ? Frame.RsvType.On : Frame.RsvType.Off; // RSV2 Frame.RsvType rsv2 = (buffer[0] & 0x20) == 0x20 ? Frame.RsvType.On : Frame.RsvType.Off; // RSV3 Frame.RsvType rsv3 = (buffer[0] & 0x10) == 0x10 ? Frame.RsvType.On : Frame.RsvType.Off; // Opcode Frame.OpCodeType opcode = (Frame.OpCodeType)(buffer[0] & 0x0f); // MASK var isMasked = (buffer[1] & 0x80) == 0x80; // Payload len var payloadLength = (byte)(buffer[1] & 0x7f); var extLength = payloadLength < 126 ? 0 : payloadLength == 126 ? 2 : 8; if ((opcode == Frame.OpCodeType.Close || opcode == Frame.OpCodeType.Ping || opcode == Frame.OpCodeType.Pong) && payloadLength > 125) { throw new Exception("The payload length of a control frame must be 125 bytes or less."); //return createCloseFrame(CloseStatusCode.INCONSISTENT_DATA, "The payload length of a control frame must be 125 bytes or less.", Mask.UNMASK); } if (extLength > 0 && buffer.Count < extLength) { throw new Exception("'Extended Payload Length' of a frame cannot be read from the data stream."); //return createCloseFrame(CloseStatusCode.ABNORMAL, "'Extended Payload Length' of a frame cannot be read from the data stream.", Mask.UNMASK); } //Mask byte[] mask = new byte[0]; int payloadOffset = 2; int dataLength; if (isMasked) { if (buffer.Count <= payloadOffset + 4) { throw new Exception("Unfinished buffer"); } mask = buffer.GetRange(payloadOffset, 4).ToArray(); payloadOffset += 4; } if (payloadLength < 126) { dataLength = payloadLength; } else if (payloadLength == 126) { byte[] temp = buffer.GetRange(payloadOffset, 2).ToArray(); payloadOffset += 2; Array.Reverse(temp); dataLength = BitConverter.ToUInt16(temp, 0); } else { byte[] temp = buffer.GetRange(payloadOffset, 8).ToArray(); payloadOffset += 8; Array.Reverse(temp); dataLength = (int)(BitConverter.ToUInt64(temp, 0)); } /** * We have to check for large frames here. socket_recv cuts at 1024 bytes * so if websocket-frame is > 1024 bytes we have to wait until whole * data is transferd. */ if (buffer.Count < dataLength + payloadOffset) { return null; } Frame f; switch (opcode) { case Frame.OpCodeType.Binary: { byte[] data = buffer.GetRange(payloadOffset, dataLength).ToArray(); if (isMasked) { for (int i = 0; i < data.Length; i++) { data[i] = (byte)(data[i] ^ mask[i % 4]); } } buffer.RemoveRange(0, dataLength + payloadOffset); f = new Frame(data); break; } case Frame.OpCodeType.Text: { byte[] data = buffer.GetRange(payloadOffset, dataLength).ToArray(); if (isMasked) { for (int i = 0; i < data.Length; i++) { data[i] = (byte)(data[i] ^ mask[i % 4]); } } buffer.RemoveRange(0, dataLength + payloadOffset); f = new Frame(System.Text.Encoding.UTF8.GetString(data)); break; } default: { byte[] data = buffer.GetRange(payloadOffset, dataLength).ToArray(); if (isMasked) { for (int i = 0; i < data.Length; i++) { data[i] = (byte)(data[i] ^ mask[i % 4]); } } buffer.RemoveRange(0, dataLength + payloadOffset); f = new Frame(opcode, data); break; } } f.Fin = fin; f.Rsv1 = rsv1; f.Rsv2 = rsv2; f.Rsv3 = rsv3; return f; } #endregion protected Header _parseClientHandshake(List<byte> buffer, ref int bufferUsed) { bufferUsed = 0; if (buffer.Count == 0) { return null; } string request = ReadOneLine(buffer); // check for valid http-header: Regex r = new Regex("^GET (\\S+) HTTP\\/1.1$"); Match matches = r.Match(request); if (!matches.Success) { throw new Exception(); } // check for valid application: bufferUsed += request.Length + 2; Header header = new Header(matches.Groups[1].ToString()); // generate headers array: string line; r = new Regex("^(\\S+): (.*)$"); while ((line = ReadOneLine(buffer, bufferUsed)) != null) { bufferUsed += line.Length + 2; line = line.TrimStart(); matches = r.Match(line); if (matches.Success) { header.Set(matches.Groups[1].ToString(), matches.Groups[2].ToString()); } } return header; } protected Header _parseServerHandshake(List<byte> buffer, ref int bufferUsed) { bufferUsed = 0; if (buffer.Count == 0) { return null; } string request = ReadOneLine(buffer); // check for valid http-header: Regex r = new Regex("^HTTP/1.1 .*$"); Match matches = r.Match(request); if (!matches.Success) { throw new Exception(); } // check for valid application: bufferUsed += request.Length + 2; Header header = new Header(matches.Groups[0].ToString()); // generate headers array: string line; r = new Regex("^(\\S+): (.*)$"); while ((line = ReadOneLine(buffer, bufferUsed)) != null) { bufferUsed += line.Length + 2; line = line.TrimStart(); matches = r.Match(line); if (matches.Success) { header.Set(matches.Groups[1].ToString(), matches.Groups[2].ToString()); } } return header; } protected Header _createResponseHandshake(Header header) { string secKey = header.Get("sec-websocket-key"); string secAccept = ""; { var rawAnswer = secKey.Trim() + rfc_guid; secAccept = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes(rawAnswer))); } Header h = new Header("HTTP/1.1 101 Switching Protocols"); h.Set("Upgrade", "websocket"); h.Set("Connection", "Upgrade"); h.Set("Sec-WebSocket-Accept", secAccept); if (header.Get("sec-websocket-protocol") != null && header.Get("sec-websocket-protocol").Trim() != "") { h.Set("Sec-WebSocket-Protocol", header.URL.Substring(1)); } return h; } protected Header _createRequestHandshake(string url, out string expectedAccept) { Regex regex = new Regex(@"^([^:]+)://([^/:]+)(:(\d+))?(/.*)?$"); Match mtch = regex.Match(url.Trim()); if (!mtch.Success) { throw new Exception ("Invalid URL: " + url); } string protocol = mtch.Groups[1].Value; string server = mtch.Groups[2].Value; string port = mtch.Groups[4].Value; string path = mtch.Groups[5].Value; string secKey = Convert.ToBase64String(Encoding.ASCII.GetBytes(Guid.NewGuid().ToString().Substring(0, 16))); expectedAccept = Convert.ToBase64String(SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(secKey + rfc_guid))); Header header = new Header(String.Format("GET {0} HTTP/1.1", string.IsNullOrEmpty(path) ? "/" : path)); header.Set("Upgrade", "WebSocket"); header.Set("Connection", "Upgrade"); header.Set("Sec-WebSocket-Version", "13"); header.Set("Sec-WebSocket-Key", secKey); if (string.IsNullOrEmpty(port)) { header.Set("Host", server); } else { header.Set("Host", server + ":" + port); } header.Set("Origin", server); return header; } } }
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using System.Collections.Generic; using System.Linq; using OpenTK; using OpenTK.Graphics; using osu.Framework.Allocation; using osu.Framework.Extensions.Color4Extensions; using osu.Framework.Graphics; using osu.Framework.Graphics.Colour; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics.Textures; using osu.Framework.Localisation; using osu.Game.Beatmaps; using osu.Game.Graphics; using osu.Game.Graphics.Sprites; using osu.Game.Graphics.UserInterface; using osu.Game.Rulesets.Scoring; using osu.Game.Screens.Play; using osu.Game.Screens.Select.Leaderboards; using osu.Game.Users; using osu.Framework.Graphics.Shapes; using osu.Framework.Extensions; namespace osu.Game.Screens.Ranking { public class ResultsPageScore : ResultsPage { private ScoreCounter scoreCounter; public ResultsPageScore(Score score, WorkingBeatmap beatmap) : base(score, beatmap) { } private FillFlowContainer<DrawableScoreStatistic> statisticsContainer; [BackgroundDependencyLoader] private void load(OsuColour colours) { const float user_header_height = 120; Children = new Drawable[] { new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = user_header_height }, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.White, }, } }, new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, Children = new Drawable[] { new UserHeader(Score.User) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = user_header_height, }, new DrawableRank(Score.Rank) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Size = new Vector2(150, 60), Margin = new MarginPadding(20), }, new Container { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, RelativeSizeAxes = Axes.X, Height = 60, Children = new Drawable[] { new SongProgressGraph { RelativeSizeAxes = Axes.Both, Alpha = 0.5f, Objects = Beatmap.Beatmap.HitObjects, }, scoreCounter = new SlowScoreCounter(6) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Y = 10, TextSize = 56, }, } }, new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Colour = colours.PinkDarker, Shadow = false, Font = @"Exo2.0-Bold", TextSize = 16, Text = "total score", Margin = new MarginPadding { Bottom = 15 }, }, new BeatmapDetails(Beatmap.BeatmapInfo) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Bottom = 10 }, }, new DateTimeDisplay(Score.Date.LocalDateTime) { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new Container { RelativeSizeAxes = Axes.X, Size = new Vector2(0.75f, 1), Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Margin = new MarginPadding { Top = 10, Bottom = 10 }, Children = new Drawable[] { new Box { Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0), colours.GrayC.Opacity(0.9f)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, new Box { Anchor = Anchor.TopRight, Origin = Anchor.TopRight, Colour = ColourInfo.GradientHorizontal( colours.GrayC.Opacity(0.9f), colours.GrayC.Opacity(0)), RelativeSizeAxes = Axes.Both, Size = new Vector2(0.5f, 1), }, } }, statisticsContainer = new FillFlowContainer<DrawableScoreStatistic> { AutoSizeAxes = Axes.Both, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Direction = FillDirection.Horizontal, LayoutDuration = 200, LayoutEasing = Easing.OutQuint } } } }; statisticsContainer.ChildrenEnumerable = Score.Statistics.OrderByDescending(p => p.Key).Select(s => new DrawableScoreStatistic(s)); } protected override void LoadComplete() { base.LoadComplete(); Schedule(() => { scoreCounter.Increment(Score.TotalScore); int delay = 0; foreach (var s in statisticsContainer.Children) { s.FadeOut() .Then(delay += 200) .FadeIn(300 + delay, Easing.Out); } }); } private class DrawableScoreStatistic : Container { private readonly KeyValuePair<HitResult, object> statistic; public DrawableScoreStatistic(KeyValuePair<HitResult, object> statistic) { this.statistic = statistic; AutoSizeAxes = Axes.Both; Margin = new MarginPadding { Left = 5, Right = 5 }; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new OsuSpriteText { Text = statistic.Value.ToString().PadLeft(4, '0'), Colour = colours.Gray7, TextSize = 30, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, new OsuSpriteText { Text = statistic.Key.GetDescription(), Colour = colours.Gray7, Font = @"Exo2.0-Bold", Y = 26, Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, }, }; } } private class DateTimeDisplay : Container { private readonly DateTime date; public DateTimeDisplay(DateTime date) { this.date = date; AutoSizeAxes = Axes.Y; Width = 140; Masking = true; CornerRadius = 5; } [BackgroundDependencyLoader] private void load(OsuColour colours) { Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = colours.Gray6, }, new OsuSpriteText { Origin = Anchor.CentreLeft, Anchor = Anchor.CentreLeft, Text = date.ToShortDateString(), Padding = new MarginPadding { Horizontal = 10, Vertical = 5 }, Colour = Color4.White, }, new OsuSpriteText { Origin = Anchor.CentreRight, Anchor = Anchor.CentreRight, Text = date.ToShortTimeString(), Padding = new MarginPadding { Horizontal = 10, Vertical = 5 }, Colour = Color4.White, } }; } } private class BeatmapDetails : Container { private readonly BeatmapInfo beatmap; private readonly OsuSpriteText title; private readonly OsuSpriteText artist; private readonly OsuSpriteText versionMapper; public BeatmapDetails(BeatmapInfo beatmap) { this.beatmap = beatmap; AutoSizeAxes = Axes.Both; Children = new Drawable[] { new FillFlowContainer { Direction = FillDirection.Vertical, RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Children = new Drawable[] { title = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 24, Font = @"Exo2.0-BoldItalic", }, artist = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 20, Font = @"Exo2.0-BoldItalic", }, versionMapper = new OsuSpriteText { Anchor = Anchor.TopCentre, Origin = Anchor.TopCentre, Shadow = false, TextSize = 16, Font = @"Exo2.0-Bold", }, } } }; } [BackgroundDependencyLoader] private void load(OsuColour colours, LocalisationEngine localisation) { title.Colour = artist.Colour = colours.BlueDarker; versionMapper.Colour = colours.Gray8; var creator = beatmap.Metadata.Author?.Username; if (!string.IsNullOrEmpty(creator)) { versionMapper.Text = $"mapped by {creator}"; if (!string.IsNullOrEmpty(beatmap.Version)) versionMapper.Text = $"{beatmap.Version} - " + versionMapper.Text; } title.Current = localisation.GetUnicodePreference(beatmap.Metadata.TitleUnicode, beatmap.Metadata.Title); artist.Current = localisation.GetUnicodePreference(beatmap.Metadata.ArtistUnicode, beatmap.Metadata.Artist); } } private class UserHeader : Container { private readonly User user; private readonly Sprite cover; public UserHeader(User user) { this.user = user; Children = new Drawable[] { cover = new Sprite { RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fill, Anchor = Anchor.Centre, Origin = Anchor.Centre, }, new OsuSpriteText { Font = @"Exo2.0-RegularItalic", Text = user.Username, Anchor = Anchor.BottomCentre, Origin = Anchor.BottomCentre, TextSize = 30, Padding = new MarginPadding { Bottom = 10 }, } }; } [BackgroundDependencyLoader] private void load(TextureStore textures) { if (!string.IsNullOrEmpty(user.CoverUrl)) cover.Texture = textures.Get(user.CoverUrl); } } private class SlowScoreCounter : ScoreCounter { protected override double RollingDuration => 3000; protected override Easing RollingEasing => Easing.OutPow10; public SlowScoreCounter(uint leading = 0) : base(leading) { DisplayedCountSpriteText.Shadow = false; DisplayedCountSpriteText.Font = @"Venera-Light"; UseCommaSeparator = true; } } } }
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ namespace ASC.Mail.Net.SIP.Stack { #region usings using System; using System.Globalization; using System.IO; using System.Text; using Message; #endregion /// <summary> /// SIP server response. Related RFC 3261. /// </summary> public class SIP_Response : SIP_Message { #region Members private readonly SIP_Request m_pRequest; private string m_ReasonPhrase = ""; private double m_SipVersion = 2.0d; private int m_StatusCode = 100; #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> public SIP_Response() {} /// <summary> /// SIP_Request.CreateResponse constructor. /// </summary> /// <param name="request">Owner request.</param> internal SIP_Response(SIP_Request request) { m_pRequest = request; } #endregion #region Properties /// <summary> /// Gets or sets reponse reasong phrase. This just StatusCode describeing text. /// </summary> public string ReasonPhrase { get { return m_ReasonPhrase; } set { if (value == null) { throw new ArgumentNullException("ReasonPhrase"); } m_ReasonPhrase = value; } } /// <summary> /// Gets SIP request which response it is. This value is null if this is stateless response. /// </summary> public SIP_Request Request { get { return m_pRequest; } } /// <summary> /// Gets or sets SIP version. /// </summary> /// <exception cref="ArgumentException">Is raised when invalid SIP version value passed.</exception> public double SipVersion { get { return m_SipVersion; } set { if (value < 1) { throw new ArgumentException("Property SIP version must be >= 1.0 !"); } m_SipVersion = value; } } /// <summary> /// Gets or sets response status code. This value must be between 100 and 999. /// </summary> /// <exception cref="ArgumentException">Is raised when value is out of allowed range.</exception> public int StatusCode { get { return m_StatusCode; } set { if (value < 1 || value > 999) { throw new ArgumentException("Property 'StatusCode' value must be >= 100 && <= 999 !"); } m_StatusCode = value; } } /// <summary> /// Gets or sets SIP Status-Code with Reason-Phrase (Status-Code SP Reason-Phrase). /// </summary> public string StatusCode_ReasonPhrase { get { return m_StatusCode + " " + m_ReasonPhrase; } set { // Status-Code SP Reason-Phrase if (value == null) { throw new ArgumentNullException("StatusCode_ReasonPhrase"); } string[] code_reason = value.Split(new[] {' '}, 2); if (code_reason.Length != 2) { throw new ArgumentException( "Invalid property 'StatusCode_ReasonPhrase' Reason-Phrase value !"); } try { StatusCode = Convert.ToInt32(code_reason[0]); } catch { throw new ArgumentException( "Invalid property 'StatusCode_ReasonPhrase' Status-Code value !"); } ReasonPhrase = code_reason[1]; } } /// <summary> /// Gets SIP status code type. /// </summary> public SIP_StatusCodeType StatusCodeType { get { if (m_StatusCode >= 100 && m_StatusCode < 200) { return SIP_StatusCodeType.Provisional; } else if (m_StatusCode >= 200 && m_StatusCode < 300) { return SIP_StatusCodeType.Success; } else if (m_StatusCode >= 300 && m_StatusCode < 400) { return SIP_StatusCodeType.Redirection; } else if (m_StatusCode >= 400 && m_StatusCode < 500) { return SIP_StatusCodeType.RequestFailure; } else if (m_StatusCode >= 500 && m_StatusCode < 600) { return SIP_StatusCodeType.ServerFailure; } else if (m_StatusCode >= 600 && m_StatusCode < 700) { return SIP_StatusCodeType.GlobalFailure; } else { throw new Exception("Unknown SIP StatusCodeType !"); } } } #endregion #region Methods /// <summary> /// Parses SIP_Response from byte array. /// </summary> /// <param name="data">Valid SIP response data.</param> /// <returns>Returns parsed SIP_Response obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>data</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Response Parse(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } return Parse(new MemoryStream(data)); } /// <summary> /// Parses SIP_Response from stream. /// </summary> /// <param name="stream">Stream what contains valid SIP response.</param> /// <returns>Returns parsed SIP_Response obeject.</returns> /// <exception cref="ArgumentNullException">Raised when <b>stream</b> is null.</exception> /// <exception cref="SIP_ParseException">Raised when invalid SIP message.</exception> public static SIP_Response Parse(Stream stream) { /* Syntax: SIP-Version SP Status-Code SP Reason-Phrase SIP-Message */ if (stream == null) { throw new ArgumentNullException("stream"); } SIP_Response retVal = new SIP_Response(); // Parse Response-line StreamLineReader r = new StreamLineReader(stream); r.Encoding = "utf-8"; string[] version_code_text = r.ReadLineString().Split(new[] {' '}, 3); if (version_code_text.Length != 3) { throw new SIP_ParseException( "Invalid SIP Status-Line syntax ! Syntax: {SIP-Version SP Status-Code SP Reason-Phrase}."); } // SIP-Version try { retVal.SipVersion = Convert.ToDouble(version_code_text[0].Split('/')[1], NumberFormatInfo.InvariantInfo); } catch { throw new SIP_ParseException("Invalid Status-Line SIP-Version value !"); } // Status-Code try { retVal.StatusCode = Convert.ToInt32(version_code_text[1]); } catch { throw new SIP_ParseException("Invalid Status-Line Status-Code value !"); } // Reason-Phrase retVal.ReasonPhrase = version_code_text[2]; // Parse SIP-Message retVal.InternalParse(stream); return retVal; } /// <summary> /// Clones this request. /// </summary> /// <returns>Returns new cloned request.</returns> public SIP_Response Copy() { SIP_Response retVal = Parse(ToByteData()); return retVal; } /// <summary> /// Checks if SIP response has all required values as response line,header fields and their values. /// Throws Exception if not valid SIP response. /// </summary> public void Validate() { // Via: + branch prameter // To: // From: // CallID: // CSeq if (Via.GetTopMostValue() == null) { throw new SIP_ParseException("Via: header field is missing !"); } if (Via.GetTopMostValue().Branch == null) { throw new SIP_ParseException("Via: header fields branch parameter is missing !"); } if (To == null) { throw new SIP_ParseException("To: header field is missing !"); } if (From == null) { throw new SIP_ParseException("From: header field is missing !"); } if (CallID == null) { throw new SIP_ParseException("CallID: header field is missing !"); } if (CSeq == null) { throw new SIP_ParseException("CSeq: header field is missing !"); } // TODO: INVITE 2xx must have only 1 contact header with SIP or SIPS. } /// <summary> /// Stores SIP_Response to specified stream. /// </summary> /// <param name="stream">Stream where to store.</param> public void ToStream(Stream stream) { // Status-Line = SIP-Version SP Status-Code SP Reason-Phrase CRLF // Add response-line byte[] responseLine = Encoding.UTF8.GetBytes("SIP/" + SipVersion.ToString("f1").Replace(',', '.') + " " + StatusCode + " " + ReasonPhrase + "\r\n"); stream.Write(responseLine, 0, responseLine.Length); // Add SIP-message InternalToStream(stream); } /// <summary> /// Converts this response to raw srver response data. /// </summary> /// <returns></returns> public byte[] ToByteData() { MemoryStream retVal = new MemoryStream(); ToStream(retVal); return retVal.ToArray(); } /// <summary> /// Returns response as string. /// </summary> /// <returns>Returns response as string.</returns> public override string ToString() { return Encoding.UTF8.GetString(ToByteData()); } #endregion } }
// // CompositeTrackSourceContents.cs // // Author: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Reflection; using System.Collections.Generic; using Gtk; using Mono.Unix; using Hyena.Data; using Hyena.Data.Gui; using Hyena.Widgets; using Banshee.Sources; using Banshee.ServiceStack; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; using Banshee.Gui; using Banshee.Collection.Gui; using ScrolledWindow=Gtk.ScrolledWindow; namespace Banshee.Sources.Gui { public class CompositeTrackSourceContents : FilteredListSourceContents, ITrackModelSourceContents { private QueryFilterView<string> genre_view; private YearListView year_view; private ArtistListView artist_view; private ArtistListView albumartist_view; private AlbumListView album_view; private TrackListView track_view; private InterfaceActionService action_service; private ActionGroup configure_browser_actions; private static readonly string name = "albumartist"; public static readonly SchemaEntry<int> PaneTopPosition = new SchemaEntry<int> ( String.Format ("{0}.{1}.browser.top", PersistentPaneController.NamespacePrefix, name), "position", DEFAULT_PANE_TOP_POSITION, "Artist/Album Browser Container Top Position", "The position of the Artist/Album browser pane container, when placed at the top" ); public static readonly SchemaEntry<int> PaneLeftPosition = new SchemaEntry<int> ( String.Format ("{0}.{1}.browser.left", PersistentPaneController.NamespacePrefix, name), "position", DEFAULT_PANE_LEFT_POSITION, "Artist/Album Browser Container Left Position", "The position of the Artist/Album browser pane container, when placed on the left" ); private static string menu_xml = @" <ui> <menubar name=""MainMenu""> <menu name=""ViewMenu"" action=""ViewMenuAction""> <placeholder name=""BrowserViews""> <menu name=""BrowserContentMenu"" action=""BrowserContentMenuAction""> <menuitem name=""ShowArtistFilter"" action=""ShowArtistFilterAction"" /> <separator /> <menuitem name=""ShowTrackArtistFilter"" action=""ShowTrackArtistFilterAction"" /> <menuitem name=""ShowAlbumArtistFilter"" action=""ShowAlbumArtistFilterAction"" /> <separator /> <menuitem name=""ShowGenreFilter"" action=""ShowGenreFilterAction"" /> <menuitem name=""ShowYearFilter"" action=""ShowYearFilterAction"" /> </menu> <separator /> </placeholder> </menu> </menubar> </ui> "; static void ParentVisible (Widget widget, bool visible) { if (null == widget.Parent) return; widget.Parent.Visible = visible; } public CompositeTrackSourceContents () : base (name, PaneTopPosition, PaneLeftPosition) { action_service = ServiceManager.Get<InterfaceActionService> (); if (action_service.FindActionGroup ("BrowserConfiguration") == null) { configure_browser_actions = new ActionGroup ("BrowserConfiguration"); configure_browser_actions.Add (new ActionEntry [] { new ActionEntry ("BrowserContentMenuAction", null, Catalog.GetString ("Browser Content"), null, Catalog.GetString ("Configure the filters available in the browser"), null) }); configure_browser_actions.Add (new ToggleActionEntry [] { new ToggleActionEntry ("ShowArtistFilterAction", null, Catalog.GetString ("Show Artist Filter"), null, Catalog.GetString ("Show a list of artists to filter by"), null, ArtistFilterVisible.Get ())}); configure_browser_actions.Add (new RadioActionEntry [] { new RadioActionEntry ("ShowTrackArtistFilterAction", null, Catalog.GetString ("Show all Artists"), null, Catalog.GetString ("Show all artists in the artist filter"), 0), new RadioActionEntry ("ShowAlbumArtistFilterAction", null, Catalog.GetString ("Show Album Artists"), null, Catalog.GetString ("Show only album artists, not artists with only single tracks"), 1), }, ArtistFilterType.Get ().Equals ("artist") ? 0 : 1 , null); configure_browser_actions.Add (new ToggleActionEntry [] { new ToggleActionEntry ("ShowGenreFilterAction", null, Catalog.GetString ("Show Genre Filter"), null, Catalog.GetString ("Show a list of genres to filter by"), null, GenreFilterVisible.Get ())}); configure_browser_actions.Add (new ToggleActionEntry [] { new ToggleActionEntry ("ShowYearFilterAction", null, Catalog.GetString ("Show Year Filter"), null, Catalog.GetString ("Show a list of years to filter by"), null, YearFilterVisible.Get ())}); action_service.AddActionGroup (configure_browser_actions); action_service.UIManager.AddUiFromString (menu_xml); } action_service.FindAction("BrowserConfiguration.ShowArtistFilterAction").Activated += OnArtistFilterVisibilityChanged; action_service.FindAction("BrowserConfiguration.ShowGenreFilterAction").Activated += OnGenreFilterChanged;; action_service.FindAction("BrowserConfiguration.ShowYearFilterAction").Activated += OnYearFilterChanged;; var artist_filter_action = action_service.FindAction("BrowserConfiguration.ShowTrackArtistFilterAction") as RadioAction; var albumartist_filter_action = action_service.FindAction("BrowserConfiguration.ShowAlbumArtistFilterAction") as RadioAction; artist_filter_action.Changed += OnArtistFilterChanged; artist_filter_action.Sensitive = ArtistFilterVisible.Get (); albumartist_filter_action.Changed += OnArtistFilterChanged; albumartist_filter_action.Sensitive = ArtistFilterVisible.Get (); } private void OnArtistFilterVisibilityChanged (object o, EventArgs args) { ToggleAction action = (ToggleAction)o; ClearFilterSelections (); ArtistFilterVisible.Set (action.Active); if (artist_view !=null && artist_view.Parent !=null) { artist_view.Parent.Visible = ArtistFilterVisible.Get (); } else if (albumartist_view != null && albumartist_view.Parent != null) { albumartist_view.Parent.Visible = ArtistFilterVisible.Get (); } action_service.FindAction("BrowserConfiguration.ShowTrackArtistFilterAction").Sensitive = ArtistFilterVisible.Get (); action_service.FindAction("BrowserConfiguration.ShowAlbumArtistFilterAction").Sensitive = ArtistFilterVisible.Get (); } private void OnGenreFilterChanged (object o, EventArgs args) { ToggleAction action = (ToggleAction)o; ClearFilterSelections (); GenreFilterVisible.Set (action.Active); Widget genre_view_widget = (Widget)genre_view; genre_view_widget.Parent.Visible = GenreFilterVisible.Get (); } private void OnYearFilterChanged (object o, EventArgs args) { ToggleAction action = (ToggleAction)o; ClearFilterSelections (); YearFilterVisible.Set (action.Active); Widget year_view_widget = (Widget)year_view; year_view_widget.Parent.Visible = YearFilterVisible.Get (); } private void OnArtistFilterChanged (object o, ChangedArgs args) { var new_artist_view = args.Current.Value == 0 ? artist_view : albumartist_view; var old_artist_view = args.Current.Value == 1 ? artist_view : albumartist_view; SwapView (old_artist_view, new_artist_view); ArtistFilterType.Set (args.Current.Value == 1 ? "albumartist" : "artist"); } private void SwapView<T> (ListView<T> oldView, ListView<T> newView) { List<ScrolledWindow> new_filter_list = new List<ScrolledWindow> (); List<ScrolledWindow> old_filter_list = new List<ScrolledWindow> (filter_scrolled_windows); foreach (ScrolledWindow fw in old_filter_list) { bool contains = false; foreach (Widget child in fw.AllChildren) { if (child == oldView) { contains = true; } } if (contains) { Widget view_widget = (Widget)newView; if (view_widget.Parent == null) { SetupFilterView (newView); } ScrolledWindow win = (ScrolledWindow)view_widget.Parent; new_filter_list.Add (win); } else { new_filter_list.Add (fw); } } filter_scrolled_windows = new_filter_list; ClearFilterSelections (); Layout (); } protected override void InitializeViews () { SetupMainView (track_view = new TrackListView ()); SetupFilterView (genre_view = new QueryFilterView<string> (Catalog.GetString ("Not Set"))); artist_view = new ArtistListView (); albumartist_view = new ArtistListView (); if (ArtistFilterType.Get ().Equals ("artist")) { SetupFilterView (artist_view); } else { SetupFilterView (albumartist_view); } SetupFilterView (year_view = new YearListView ()); SetupFilterView (album_view = new AlbumListView ()); } protected override void OnShown () { base.OnShown (); ParentVisible(genre_view, GenreFilterVisible.Get ()); switch (ArtistFilterType.Get ()) { case "artist": ParentVisible(artist_view, ArtistFilterVisible.Get ()); ParentVisible(albumartist_view, false); break; case "albumartist": ParentVisible (albumartist_view, ArtistFilterVisible.Get ()); ParentVisible (artist_view, false); break; } ParentVisible(year_view, YearFilterVisible.Get ()); } protected override void ClearFilterSelections () { if (genre_view.Model != null) { genre_view.Selection.Clear (); } if (artist_view.Model != null) { artist_view.Selection.Clear (); } if (albumartist_view.Model != null) { albumartist_view.Selection.Clear (); } if (album_view.Model != null) { album_view.Selection.Clear (); } if (year_view.Model != null) { year_view.Selection.Clear (); } } IListView<TrackInfo> ITrackModelSourceContents.TrackView { get { return track_view; } } public TrackListView TrackView { get { return track_view; } } public TrackListModel TrackModel { get { return (TrackListModel)track_view.Model; } } protected override bool ActiveSourceCanHasBrowser { get { if (null == source) { return false; } return ((ITrackModelSource) source).ShowBrowser; } } #region Implement ISourceContents public override bool SetSource (ISource source) { ITrackModelSource track_source = source as ITrackModelSource; IFilterableSource filterable_source = source as IFilterableSource; if (track_source == null) { return false; } base.SetSource (source); SetModel (track_view, track_source.TrackModel); bool genre_view_model_set = false; if (filterable_source != null && filterable_source.CurrentFilters != null) { foreach (IListModel model in filterable_source.CurrentFilters) { if (model is IListModel<ArtistInfo> && model is DatabaseArtistListModel) SetModel (artist_view, (model as IListModel<ArtistInfo>)); else if (model is IListModel<ArtistInfo> && model is DatabaseAlbumArtistListModel) SetModel (albumartist_view, (model as IListModel<ArtistInfo>)); else if (model is IListModel<AlbumInfo>) SetModel (album_view, (model as IListModel<AlbumInfo>)); else if (model is IListModel<QueryFilterInfo<string>> && !genre_view_model_set) { SetModel (genre_view, (model as IListModel<QueryFilterInfo<string>>)); genre_view_model_set = true; } else if (model is DatabaseYearListModel) SetModel (year_view, model as IListModel<YearInfo>); else Hyena.Log.DebugFormat ("CompositeTrackSourceContents got non-album/artist filter model: {0}", model); } } ClearFilterSelections (); track_view.HeaderVisible = true; return true; } public override void ResetSource () { source = null; SetModel (track_view, null); SetModel (artist_view, null); SetModel (albumartist_view, null); SetModel (album_view, null); SetModel (year_view, null); SetModel (genre_view, null); track_view.HeaderVisible = false; } #endregion public static readonly SchemaEntry<bool> ArtistFilterVisible = new SchemaEntry<bool> ( "browser", "show_artist_filter", true, "Artist Filter Visibility", "Whether or not to show the Artist filter" ); public static readonly SchemaEntry<string> ArtistFilterType = new SchemaEntry<string> ( "browser", "artist_filter_type", "artist", "Artist/AlbumArtist Filter Type", "Whether to show all artists or just album artists in the artist filter; either 'artist' or 'albumartist'" ); public static readonly SchemaEntry<bool> GenreFilterVisible = new SchemaEntry<bool> ( "browser", "show_genre_filter", false, "Genre Filter Visibility", "Whether or not to show the Genre filter" ); public static readonly SchemaEntry<bool> YearFilterVisible = new SchemaEntry<bool> ( "browser", "show_year_filter", false, "Year Filter Visibility", "Whether or not to show the Year filter" ); } }
/* * 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 Mono.Addins; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Capabilities; using OpenSim.Framework.Servers; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using Caps = OpenSim.Framework.Capabilities.Caps; using PermissionMask = OpenSim.Framework.PermissionMask; namespace OpenSim.Region.ClientStack.Linden { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "NewFileAgentInventoryVariablePriceModule")] public class NewFileAgentInventoryVariablePriceModule : INonSharedRegionModule { // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private IAssetService m_assetService; private bool m_dumpAssetsToFile = false; private bool m_enabled = true; private int m_levelUpload = 0; private Scene m_scene; #region Region Module interfaceBase Members public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene pScene) { m_scene = pScene; } public void Initialise(IConfigSource source) { IConfig meshConfig = source.Configs["Mesh"]; if (meshConfig == null) return; m_enabled = meshConfig.GetBoolean("AllowMeshUpload", true); m_levelUpload = meshConfig.GetInt("LevelUpload", 0); } public void RegionLoaded(Scene scene) { // m_assetService = m_scene.RequestModuleInterface<IAssetService>(); m_scene.EventManager.OnRegisterCaps += RegisterCaps; } public void RemoveRegion(Scene scene) { m_scene.EventManager.OnRegisterCaps -= RegisterCaps; m_scene = null; } #endregion Region Module interfaceBase Members #region Region Module interface public string Name { get { return "NewFileAgentInventoryVariablePriceModule"; } } public void Close() { } public void RegisterCaps(UUID agentID, Caps caps) { if (!m_enabled) return; UUID capID = UUID.Random(); // m_log.Debug("[NEW FILE AGENT INVENTORY VARIABLE PRICE]: /CAPS/" + capID); caps.RegisterHandler( "NewFileAgentInventoryVariablePrice", new LLSDStreamhandler<LLSDAssetUploadRequest, LLSDNewFileAngentInventoryVariablePriceReplyResponse>( "POST", "/CAPS/" + capID.ToString(), req => NewAgentInventoryRequest(req, agentID), "NewFileAgentInventoryVariablePrice", agentID.ToString())); } #endregion Region Module interface public LLSDNewFileAngentInventoryVariablePriceReplyResponse NewAgentInventoryRequest(LLSDAssetUploadRequest llsdRequest, UUID agentID) { //TODO: The Mesh uploader uploads many types of content. If you're going to implement a Money based limit // you need to be aware of this //if (llsdRequest.asset_type == "texture" || // llsdRequest.asset_type == "animation" || // llsdRequest.asset_type == "sound") // { // check user level ScenePresence avatar = null; IClientAPI client = null; m_scene.TryGetScenePresence(agentID, out avatar); if (avatar != null) { client = avatar.ControllingClient; if (avatar.UserLevel < m_levelUpload) { if (client != null) client.SendAgentAlertMessage("Unable to upload asset. Insufficient permissions.", false); LLSDNewFileAngentInventoryVariablePriceReplyResponse errorResponse = new LLSDNewFileAngentInventoryVariablePriceReplyResponse(); errorResponse.rsvp = ""; errorResponse.state = "error"; return errorResponse; } } // check funds IMoneyModule mm = m_scene.RequestModuleInterface<IMoneyModule>(); if (mm != null) { if (!mm.UploadCovered(agentID, mm.UploadCharge)) { if (client != null) client.SendAgentAlertMessage("Unable to upload asset. Insufficient funds.", false); LLSDNewFileAngentInventoryVariablePriceReplyResponse errorResponse = new LLSDNewFileAngentInventoryVariablePriceReplyResponse(); errorResponse.rsvp = ""; errorResponse.state = "error"; return errorResponse; } } // } string assetName = llsdRequest.name; string assetDes = llsdRequest.description; string capsBase = "/CAPS/NewFileAgentInventoryVariablePrice/"; UUID newAsset = UUID.Random(); UUID newInvItem = UUID.Random(); UUID parentFolder = llsdRequest.folder_id; string uploaderPath = Util.RandomClass.Next(5000, 8000).ToString("0000") + "/"; AssetUploader uploader = new AssetUploader(assetName, assetDes, newAsset, newInvItem, parentFolder, llsdRequest.inventory_type, llsdRequest.asset_type, capsBase + uploaderPath, MainServer.Instance, m_dumpAssetsToFile); MainServer.Instance.AddStreamHandler( new BinaryStreamHandler( "POST", capsBase + uploaderPath, uploader.uploaderCaps, "NewFileAgentInventoryVariablePrice", agentID.ToString())); string protocol = "http://"; if (MainServer.Instance.UseSSL) protocol = "https://"; string uploaderURL = protocol + m_scene.RegionInfo.ExternalHostName + ":" + MainServer.Instance.Port.ToString() + capsBase + uploaderPath; LLSDNewFileAngentInventoryVariablePriceReplyResponse uploadResponse = new LLSDNewFileAngentInventoryVariablePriceReplyResponse(); uploadResponse.rsvp = uploaderURL; uploadResponse.state = "upload"; uploadResponse.resource_cost = 0; uploadResponse.upload_price = 0; uploader.OnUpLoad += //UploadCompleteHandler; delegate( string passetName, string passetDescription, UUID passetID, UUID pinventoryItem, UUID pparentFolder, byte[] pdata, string pinventoryType, string passetType) { UploadCompleteHandler(passetName, passetDescription, passetID, pinventoryItem, pparentFolder, pdata, pinventoryType, passetType, agentID); }; return uploadResponse; } public void UploadCompleteHandler(string assetName, string assetDescription, UUID assetID, UUID inventoryItem, UUID parentFolder, byte[] data, string inventoryType, string assetType, UUID AgentID) { // m_log.DebugFormat( // "[NEW FILE AGENT INVENTORY VARIABLE PRICE MODULE]: Upload complete for {0}", inventoryItem); sbyte assType = 0; sbyte inType = 0; if (inventoryType == "sound") { inType = 1; assType = 1; } else if (inventoryType == "animation") { inType = 19; assType = 20; } else if (inventoryType == "wearable") { inType = 18; switch (assetType) { case "bodypart": assType = 13; break; case "clothing": assType = 5; break; } } else if (inventoryType == "mesh") { inType = (sbyte)InventoryType.Mesh; assType = (sbyte)AssetType.Mesh; } AssetBase asset; asset = new AssetBase(assetID, assetName, assType, AgentID.ToString()); asset.Data = data; if (m_scene.AssetService != null) m_scene.AssetService.Store(asset); InventoryItemBase item = new InventoryItemBase(); item.Owner = AgentID; item.CreatorId = AgentID.ToString(); item.ID = inventoryItem; item.AssetID = asset.FullID; item.Description = assetDescription; item.Name = assetName; item.AssetType = assType; item.InvType = inType; item.Folder = parentFolder; item.CurrentPermissions = (uint)(PermissionMask.Move | PermissionMask.Copy | PermissionMask.Modify | PermissionMask.Transfer); item.BasePermissions = (uint)PermissionMask.All; item.EveryOnePermissions = 0; item.NextPermissions = (uint)PermissionMask.All; item.CreationDate = Util.UnixTimeSinceEpoch(); m_scene.AddInventoryItem(item); } } }
using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.TestTools.UnitTesting; using MQTTnet.Client; using MQTTnet.Client.Options; using MQTTnet.Client.Publishing; using MQTTnet.Client.Receiving; using MQTTnet.Client.Subscribing; using MQTTnet.Client.Unsubscribing; using MQTTnet.Formatter; using MQTTnet.Protocol; using MQTTnet.Server; using MQTTnet.Tests.Mockups; namespace MQTTnet.Tests.MQTTv5 { [TestClass] public sealed class Client_Tests { public TestContext TestContext { get; set; } [TestMethod] public async Task Connect_With_New_Mqtt_Features() { using (var testEnvironment = new TestEnvironment(TestContext)) { await testEnvironment.StartServer(); // This test can be also executed against "broker.hivemq.com" to validate package format. var client = await testEnvironment.ConnectClient( new MqttClientOptionsBuilder() //.WithTcpServer("broker.hivemq.com") .WithTcpServer("127.0.0.1", testEnvironment.ServerPort) .WithProtocolVersion(MqttProtocolVersion.V500) .WithTopicAliasMaximum(20) .WithReceiveMaximum(20) .WithWillMessage(new MqttApplicationMessageBuilder().WithTopic("abc").Build()) .WithWillDelayInterval(20) .Build()); MqttApplicationMessage receivedMessage = null; await client.SubscribeAsync("a"); client.UseApplicationMessageReceivedHandler(context => { receivedMessage = context.ApplicationMessage; }); await client.PublishAsync(new MqttApplicationMessageBuilder() .WithTopic("a") .WithPayload("x") .WithUserProperty("a", "1") .WithUserProperty("b", "2") .WithPayloadFormatIndicator(MqttPayloadFormatIndicator.CharacterData) .WithAtLeastOnceQoS() .Build()); await Task.Delay(500); Assert.IsNotNull(receivedMessage); Assert.AreEqual(2, receivedMessage.UserProperties.Count); } } [TestMethod] public async Task Connect() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500).Build()); } } [TestMethod] public async Task Connect_And_Disconnect() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); await client.DisconnectAsync(); } } [TestMethod] public async Task Subscribe() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); var result = await client.SubscribeAsync(new MqttClientSubscribeOptions() { SubscriptionIdentifier = 1, TopicFilters = new List<MqttTopicFilter> { new MqttTopicFilter {Topic = "a", QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce} } }); await client.DisconnectAsync(); Assert.AreEqual(1, result.Items.Count); Assert.AreEqual(MqttClientSubscribeResultCode.GrantedQoS1, result.Items[0].ResultCode); } } [TestMethod] public async Task Unsubscribe() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); await client.SubscribeAsync("a"); var result = await client.UnsubscribeAsync("a"); await client.DisconnectAsync(); Assert.AreEqual(1, result.Items.Count); Assert.AreEqual(MqttClientUnsubscribeResultCode.Success, result.Items[0].ReasonCode); } } [TestMethod] public async Task Publish_QoS_0() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); var result = await client.PublishAsync("a", "b"); await client.DisconnectAsync(); Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode); } } [TestMethod] public async Task Publish_QoS_1() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); var result = await client.PublishAsync("a", "b", MqttQualityOfServiceLevel.AtLeastOnce); await client.DisconnectAsync(); Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode); } } [TestMethod] public async Task Publish_QoS_2() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); var result = await client.PublishAsync("a", "b", MqttQualityOfServiceLevel.ExactlyOnce); await client.DisconnectAsync(); Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode); } } [TestMethod] public async Task Publish_With_Properties() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var client = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500)); var applicationMessage = new MqttApplicationMessageBuilder() .WithTopic("Hello") .WithPayload("World") .WithAtMostOnceQoS() .WithUserProperty("x", "1") .WithUserProperty("y", "2") .WithResponseTopic("response") .WithContentType("text") .WithMessageExpiryInterval(50) .WithCorrelationData(new byte[12]) .WithTopicAlias(2) .Build(); var result = await client.PublishAsync(applicationMessage); await client.DisconnectAsync(); Assert.AreEqual(MqttClientPublishReasonCode.Success, result.ReasonCode); } } [TestMethod] public async Task Subscribe_And_Publish() { using (var testEnvironment = new TestEnvironment()) { await testEnvironment.StartServer(); var receivedMessages = new List<MqttApplicationMessageReceivedEventArgs>(); var client1 = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500).WithClientId("client1")); client1.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => { lock (receivedMessages) { receivedMessages.Add(e); } }); await client1.SubscribeAsync("a"); var client2 = await testEnvironment.ConnectClient(o => o.WithProtocolVersion(MqttProtocolVersion.V500).WithClientId("client2")); await client2.PublishAsync("a", "b"); await Task.Delay(500); await client2.DisconnectAsync(); await client1.DisconnectAsync(); Assert.AreEqual(1, receivedMessages.Count); Assert.AreEqual("client1", receivedMessages[0].ClientId); Assert.AreEqual("a", receivedMessages[0].ApplicationMessage.Topic); Assert.AreEqual("b", receivedMessages[0].ApplicationMessage.ConvertPayloadToString()); } } [TestMethod] public async Task Publish_And_Receive_New_Properties() { using (var testEnvironment = new TestEnvironment(TestContext)) { await testEnvironment.StartServer(); var receiver = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)); await receiver.SubscribeAsync("#"); MqttApplicationMessage receivedMessage = null; receiver.UseApplicationMessageReceivedHandler(c => { receivedMessage = c.ApplicationMessage; }); var sender = await testEnvironment.ConnectClient(new MqttClientOptionsBuilder().WithProtocolVersion(MqttProtocolVersion.V500)); var applicationMessage = new MqttApplicationMessageBuilder() .WithTopic("Hello") .WithPayload("World") .WithAtMostOnceQoS() .WithUserProperty("x", "1") .WithUserProperty("y", "2") .WithResponseTopic("response") .WithContentType("text") .WithMessageExpiryInterval(50) .WithCorrelationData(new byte[12]) .WithTopicAlias(2) .Build(); await sender.PublishAsync(applicationMessage); await Task.Delay(500); Assert.IsNotNull(receivedMessage); Assert.AreEqual(applicationMessage.Topic, receivedMessage.Topic); Assert.AreEqual(applicationMessage.TopicAlias, receivedMessage.TopicAlias); Assert.AreEqual(applicationMessage.ContentType, receivedMessage.ContentType); Assert.AreEqual(applicationMessage.ResponseTopic, receivedMessage.ResponseTopic); Assert.AreEqual(applicationMessage.MessageExpiryInterval, receivedMessage.MessageExpiryInterval); CollectionAssert.AreEqual(applicationMessage.CorrelationData, receivedMessage.CorrelationData); CollectionAssert.AreEqual(applicationMessage.Payload, receivedMessage.Payload); CollectionAssert.AreEqual(applicationMessage.UserProperties, receivedMessage.UserProperties); } } } }
// // Copyright 2011, Novell, Inc. // Copyright 2011, Regan Sarwas // // // 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. // // // PdfKit.cs: Bindings for the PdfKit API // using System; using System.Drawing; using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.ObjCRuntime; // Verify/Test Delegate Models // Check for missing NullAllowed on all object properties // Test methods returning typed arrays in lieu of NSArray // Check classes with no public inits - Should I make the constructors private? // Check the few abnormal properties namespace MonoMac.PdfKit { [BaseType (typeof (NSObject), Name="PDFAction")] public interface PdfAction { //This is an abstract superclass with no public init - should it have a private constructor?? //As it is, I can create instances, that segfault when you access the type method. //marking the method as [Abstract] doesn't work because the subclasses do not explictly //define this method (although they implement it) [Export ("type")] string Type { get; } } [BaseType (typeof (PdfAction), Name="PDFActionGoTo")] public interface PdfActionGoTo { [Export ("initWithDestination:")] IntPtr Constructor (PdfDestination destination); [Export ("destination")] PdfDestination Destination { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionNamed")] public interface PdfActionNamed { [Export ("initWithName:")] IntPtr Constructor (PdfActionNamedName name); [Export ("name")] PdfActionNamedName Name { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionRemoteGoTo")] public interface PdfActionRemoteGoTo { [Export ("initWithPageIndex:atPoint:fileURL:")] IntPtr Constructor (int pageIndex, PointF point, NSUrl fileUrl); [Export ("pageIndex")] int PageIndex { get; set; } [Export ("point")] PointF Point { get; set; } [Export ("URL")] NSUrl Url { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionResetForm")] public interface PdfActionResetForm { //has a public Init ??? //NSArray of NSString [Export ("fields"), NullAllowed] string [] Fields { get; set; } [Export ("fieldsIncludedAreCleared")] bool FieldsIncludedAreCleared { get; set; } } [BaseType (typeof (PdfAction), Name="PDFActionURL")] public interface PdfActionUrl { [Export ("initWithURL:")] IntPtr Constructor (NSUrl url); [Export ("URL")] NSUrl Url { get; set; } } [BaseType (typeof (NSObject), Name="PDFAnnotation")] public interface PdfAnnotation { [Export ("initWithBounds:")] IntPtr Constructor (RectangleF bounds); [Export ("page")] PdfPage Page { get; } [Export ("type")] string Type { get; } [Export ("bounds")] RectangleF Bounds { get; set; } [Export ("modificationDate")] NSDate ModificationDate { get; set; } [Export ("userName")] string UserName { get; set; } [Export ("popup")] PdfAnnotationPopup Popup { get; set; } [Export ("shouldDisplay")] bool ShouldDisplay { get; set; } [Export ("shouldPrint")] bool ShouldPrint { get; set; } [Export ("border")] PdfBorder Border { get; set; } [Export ("color")] NSColor Color { get; set; } [Export ("mouseUpAction")] PdfAction MouseUpAction { get; set; } [Export ("contents")] string Contents { get; set; } [Export ("toolTip")] string ToolTip { get; } [Export ("hasAppearanceStream")] bool HasAppearanceStream { get; } [Export ("removeAllAppearanceStreams")] void RemoveAllAppearanceStreams (); [Export ("drawWithBox:")] void Draw (PdfDisplayBox box); } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationButtonWidget")] public interface PdfAnnotationButtonWidget { [Export ("controlType")] PdfWidgetControlType ControlType { get; set; } [Export ("state")] int State { get; set; } [Export ("highlighted")] bool Highlighted { [Bind ("isHighlighted")] get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("allowsToggleToOff")] bool AllowsToggleToOff { get; } [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("caption")] string Caption { get; set; } [Export ("fieldName")] string FieldName { get; set; } [Export ("onStateValue")] string OnStateValue { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationChoiceWidget")] public interface PdfAnnotationChoiceWidget { [Export ("stringValue")] string Text { get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("fieldName")] string FieldName { get; set; } [Export ("isListChoice")] bool IsListChoice { get; set; } // NSArray of NSString [Export ("choices")] string [] Choices { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationCircle")] public interface PdfAnnotationCircle { [Export ("interiorColor")] NSColor InteriorColor { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationFreeText")] public interface PdfAnnotationFreeText { [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("alignment")] NSTextAlignment Alignment { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationInk")] public interface PdfAnnotationInk { [Export ("paths")] NSBezierPath [] Paths { get; } [Export ("addBezierPath:")] void AddBezierPathpath (NSBezierPath path); [Export ("removeBezierPath:")] void RemoveBezierPathpath (NSBezierPath path); } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationLine")] public interface PdfAnnotationLine { [Export ("startPoint")] PointF StartPoint { get; set; } [Export ("endPoint")] PointF EndPoint { get; set; } [Export ("startLineStyle")] PdfLineStyle StartLineStyle { get; set; } [Export ("endLineStyle")] PdfLineStyle EndLineStyle { get; set; } [Export ("interiorColor")] NSColor InteriorColor { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationLink")] public interface PdfAnnotationLink { [Export ("destination")] PdfDestination Destination { get; set; } [Export ("URL")] NSUrl Url { get; set; } [Export ("setHighlighted:")] void SetHighlighted (bool highlighted); } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationMarkup")] public interface PdfAnnotationMarkup { //bindings cannot box PointF[] to NSArray [Export ("quadrilateralPoints")] NSArray QuadrilateralPoints { get; set; } //PointF [] QuadrilateralPoints { get; set; } [Export ("markupType")] PdfMarkupType MarkupType { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationPopup")] public interface PdfAnnotationPopup { [Export ("isOpen")] bool IsOpen { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationSquare")] public interface PdfAnnotationSquare { [Export ("interiorColor")] NSColor InteriorColor { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationStamp")] public interface PdfAnnotationStamp { [Export ("name")] string Name { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationText")] public interface PdfAnnotationText { [Export ("iconType")] PdfTextAnnotationIconType IconType { get; set; } } [BaseType (typeof (PdfAnnotation), Name="PDFAnnotationTextWidget")] public interface PdfAnnotationTextWidget { [Export ("stringValue")] string StringValue { get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("rotation")] int Rotation { get; set; } [Export ("font")] NSFont Font { get; set; } [Export ("fontColor")] NSColor FontColor { get; set; } [Export ("alignment")] NSTextAlignment Alignment { get; set; } [Export ("maximumLength")] int MaximumLength { get; set; } [Export ("fieldName")] string FieldName { get; set; } } [BaseType (typeof (NSObject), Name="PDFBorder")] public interface PdfBorder { [Export ("style")] PdfBorderStyle Style { get; set; } [Export ("lineWidth")] float LineWidth { get; set; } [Export ("horizontalCornerRadius")] float HorizontalCornerRadius { get; set; } [Export ("verticalCornerRadius")] float VerticalCornerRadius { get; set; } //FIXME //NSArray of NSNumber see Docs say see NSBezierPath, which uses float [] [Export ("dashPattern")] NSArray DashPattern { get; set; } //float [] DashPattern { get; set; } [Export ("drawInRect:")] void Draw (RectangleF rect); } [BaseType (typeof (NSObject), Name="PDFDestination")] public interface PdfDestination { [Export ("initWithPage:atPoint:")] IntPtr Constructor (PdfPage page, PointF point); [Export ("page")] PdfPage Page { get; } [Export ("point")] PointF Point { get; } //Should Compare be more more .Net ified ? [Export ("compare:")] NSComparisonResult Compare (PdfDestination destination); } //Add attributes for delegates/events [BaseType (typeof (NSObject), Name="PDFDocument", Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (PdfDocumentDelegate)})] public interface PdfDocument { [Export ("initWithURL:")] IntPtr Constructor (NSUrl url); [Export ("initWithData:")] IntPtr Constructor (NSData data); [Export ("documentURL")] NSUrl DocumentUrl { get; } //[Export ("documentRef")] //CGPdfDocumentRef DocumentRef { get; } [Export ("documentAttributes")] NSDictionary DocumentAttributes { get; set; } [Export ("majorVersion")] int MajorVersion { get; } [Export ("minorVersion")] int MinorVersion { get; } [Export ("isEncrypted")] bool IsEncrypted { get; } [Export ("isLocked")] bool IsLocked { get; } [Export ("unlockWithPassword:")] bool Unlock (string password); [Export ("allowsPrinting")] bool AllowsPrinting { get; } [Export ("allowsCopying")] bool AllowsCopying { get; } [Export ("permissionsStatus")] PdfDocumentPermissions PermissionsStatus { get; } [Export ("string")] string Text { get; } [Export ("delegate", ArgumentSemantic.Assign), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] PdfDocumentDelegate Delegate { get; set; } [Export ("dataRepresentation")] NSData GetDataRepresentation (); [Export ("dataRepresentationWithOptions:")] NSData GetDataRepresentation (NSDictionary options); [Export ("writeToFile:")] bool Write (string path); [Export ("writeToFile:withOptions:")] bool Write (string path, NSDictionary options); [Export ("writeToURL:")] bool Write (NSUrl url); [Export ("writeToURL:withOptions:")] bool Write (NSUrl url, NSDictionary options); [Export ("outlineRoot")] PdfOutline OutlineRoot { get; set; } [Export ("outlineItemForSelection:")] PdfOutline OutlineItem (PdfSelection selection); [Export ("pageCount")] int PageCount { get; } [Export ("pageAtIndex:")] PdfPage GetPage (int index); [Export ("indexForPage:")] int GetPageIndex (PdfPage page); [Export ("insertPage:atIndex:")] void InsertPage (PdfPage page, int index); [Export ("removePageAtIndex:")] void RemovePage (int index); [Export ("exchangePageAtIndex:withPageAtIndex:")] void ExchangePages (int indexA, int indexB); // Check on how Classes map to Types [Export ("pageClass")] Class PageClass { get; } // Shouldn't options should be a bit flag of comparison methods - find enum. [Export ("findString:withOptions:")] PdfSelection [] Find (string text, int options); [Export ("beginFindString:withOptions:")] void FindAsync (string text, int options); [Export ("beginFindStrings:withOptions:")] void FindAsync (string [] text, int options); [Export ("findString:fromSelection:withOptions:")] PdfSelection Find (string text, PdfSelection selection, int options); [Export ("isFinding")] bool IsFinding { get; } [Export ("cancelFindString")] void CancelFind (); [Export ("selectionForEntireDocument")] PdfSelection SelectEntireDocument (); [Export ("selectionFromPage:atPoint:toPage:atPoint:")] PdfSelection GetSelection (PdfPage startPage, PointF startPoint, PdfPage endPage, PointF endPoint); [Export ("selectionFromPage:atCharacterIndex:toPage:atCharacterIndex:")] PdfSelection GetSelection (PdfPage startPage, int startCharIndex, PdfPage endPage, int endCharIndex); } [BaseType (typeof (NSObject))] [Model] public interface PdfDocumentDelegate { [Export ("didMatchString:"), EventArgs ("PdfSelection")] void DidMatchString (PdfSelection sender); //the delegate method needs to take at least one parameter //[Export ("classForPage"), DelegateName ("ClassForPageDelegate"), DefaultValue (null)] //Class ClassForPage (); [Export ("classForAnnotationClass:"), DelegateName ("ClassForAnnotationClassDelegate"), DefaultValue (null)] Class ClassForAnnotationClass (Class sender); [Export ("documentDidEndDocumentFind:"), EventArgs ("NSNotification")] void FindFinished (NSNotification notification); [Export ("documentDidBeginPageFind:"), EventArgs ("NSNotification")] void PageFindStarted (NSNotification notification); [Export ("documentDidEndPageFind:"), EventArgs ("NSNotification")] void PageFindFinished (NSNotification notification); [Export ("documentDidFindMatch:"), EventArgs ("NSNotification")] void MatchFound (NSNotification notification); } [BaseType (typeof (NSObject), Name="PDFOutline")] public interface PdfOutline { // Why did this have a special init???? // Constructor/class needs special documentation on how to use one that is created (not obtained from another object). [Export ("document")] PdfDocument Document { get; } [Export ("parent")] PdfOutline Parent { get; } [Export ("numberOfChildren")] int ChildrenCount { get; } [Export ("index")] int Index { get; } [Export ("childAtIndex:")] PdfOutline Child (int index); [Export ("insertChild:atIndex:")] void InsertChild (PdfOutline child, int index); [Export ("removeFromParent")] void RemoveFromParent (); [Export ("label")] string Label { get; set; } [Export ("isOpen")] bool IsOpen { get; set; } [Export ("destination")] PdfDestination Destination { get; set; } [Export ("action")] PdfAction Action { get; set; } } [BaseType (typeof (NSObject), Name="PDFPage")] public interface PdfPage { [Export ("initWithImage:")] IntPtr Constructor (NSImage image); [Export ("document")] PdfDocument Document { get; } //[Export ("pageRef")] //CGPdfPageRef PageRef { get; } [Export ("label")] string Label { get; } [Export ("boundsForBox:")] RectangleF GetBoundsForBox (PdfDisplayBox box); [Export ("setBounds:forBox:")] void SetBoundsForBox (RectangleF bounds, PdfDisplayBox box); [Export ("rotation")] int Rotation { get; set; } //Check Docs say: "array will _most likely_ be typed to subclasses of the PdfAnnotation class" //do they mean that if it isn't a subclass it is the base class ?? //Maybe we should be safe and return NSArray ?? [Export ("annotations")] PdfAnnotation [] Annotations { get; } [Export ("displaysAnnotations")] bool DisplaysAnnotations { get; set; } [Export ("addAnnotation:")] void AddAnnotation (PdfAnnotation annotation); [Export ("removeAnnotation:")] void RemoveAnnotation (PdfAnnotation annotation); [Export ("annotationAtPoint:")] PdfAnnotation GetAnnotation (PointF point); [Export ("drawWithBox:")] void Draw (PdfDisplayBox box); [Export ("transformContextForBox:")] void TransformContext (PdfDisplayBox box); [Export ("numberOfCharacters")] int CharacterCount { get; } [Export ("string")] string Text { get; } [Export ("attributedString")] NSAttributedString AttributedString { get; } [Export ("characterBoundsAtIndex:")] RectangleF GetCharacterBounds (int index); [Export ("characterIndexAtPoint:")] int GetCharacterIndex (PointF point); [Export ("selectionForRect:")] PdfSelection GetSelection (RectangleF rect); [Export ("selectionForWordAtPoint:")] PdfSelection SelectWord (PointF point); [Export ("selectionForLineAtPoint:")] PdfSelection SelectLine (PointF point); [Export ("selectionFromPoint:toPoint:")] PdfSelection GetSelection (PointF startPoint, PointF endPoint); [Export ("selectionForRange:")] PdfSelection GetSelection (NSRange range); [Export ("dataRepresentation")] NSData DataRepresentation { get; } } [BaseType (typeof (NSObject), Name="PDFSelection")] [DisableDefaultCtor] // An uncaught exception was raised: init: not a valid initializer for PDFSelection public interface PdfSelection { [Export ("initWithDocument:")] IntPtr Constructor (PdfDocument document); //verify NSArray [Export ("pages")] PdfPage [] Pages { get; } [Export ("color")] NSColor Color { get; set; } [Export ("string")] string Text { get; } [Export ("attributedString")] NSAttributedString AttributedString { get; } [Export ("boundsForPage:")] RectangleF GetBoundsForPage (PdfPage page); //verify NSArray [Export ("selectionsByLine")] PdfSelection [] SelectionsByLine (); [Export ("addSelection:")] void AddSelection (PdfSelection selection); [Export ("addSelections:")] void AddSelections (PdfSelection [] selections); [Export ("extendSelectionAtEnd:")] void ExtendSelectionAtEnd (int succeed); [Export ("extendSelectionAtStart:")] void ExtendSelectionAtStart (int precede); [Export ("drawForPage:active:")] void Draw (PdfPage page, bool active); [Export ("drawForPage:withBox:active:")] void Draw (PdfPage page, PdfDisplayBox box, bool active); } [BaseType (typeof (NSView), Name="PDFThumbnailView")] public interface PdfThumbnailView { [Export ("PDFView")] PdfView PdfView { get; set; } [Export ("thumbnailSize")] SizeF ThumbnailSize { get; set; } [Export ("maximumNumberOfColumns")] int MaximumNumberOfColumns { get; set; } [Export ("labelFont")] NSFont LabelFont { get; set; } [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("allowsDragging")] bool AllowsDragging { get; set; } [Export ("allowsMultipleSelection")] bool AllowsMultipleSelection { get; set; } //verify NSArray [Export ("selectedPages")] PdfPage [] SelectedPages { get; } } [BaseType (typeof (NSView), Name="PDFView", Delegates=new string [] { "WeakDelegate" }, Events=new Type [] { typeof (PdfViewDelegate)})] public interface PdfView { [Export ("document")] PdfDocument Document { get; set; } [Export ("canGoToFirstPage")] bool CanGoToFirstPage { get; } //Verify [Export ("goToFirstPage:")] void GoToFirstPage (NSObject sender); [Export ("canGoToLastPage")] bool CanGoToLastPage { get; } [Export ("goToLastPage:")] void GoToLastPage (NSObject sender); [Export ("canGoToNextPage")] bool CanGoToNextPage { get; } [Export ("goToNextPage:")] void GoToNextPage (NSObject sender); [Export ("canGoToPreviousPage")] bool CanGoToPreviousPage { get; } [Export ("goToPreviousPage:")] void GoToPreviousPage (NSObject sender); [Export ("canGoBack")] bool CanGoBack { get; } [Export ("goBack:")] void GoBack (NSObject sender); [Export ("canGoForward")] bool CanGoForward { get; } [Export ("goForward:")] void GoForward (NSObject sender); [Export ("currentPage")] PdfPage CurrentPage { get; } [Export ("goToPage:")] void GoToPage (PdfPage page); [Export ("currentDestination")] PdfDestination CurrentDestination { get; } [Export ("goToDestination:")] void GoToDestination (PdfDestination destination); [Export ("goToSelection:")] void GoToSelection (PdfSelection selection); [Export ("goToRect:onPage:")] void GoToRectangle (RectangleF rect, PdfPage page); [Export ("displayMode")] PdfDisplayMode DisplayMode { get; set; } [Export ("displaysPageBreaks")] bool DisplaysPageBreaks { get; set; } [Export ("displayBox")] PdfDisplayBox DisplayBox { get; set; } [Export ("displaysAsBook")] bool DisplaysAsBook { get; set; } [Export ("shouldAntiAlias")] bool ShouldAntiAlias { get; set; } [Export ("greekingThreshold")] float GreekingThreshold { get; set; } [Export ("takeBackgroundColorFrom:")] void TakeBackgroundColor (NSObject sender); [Export ("backgroundColor")] NSColor BackgroundColor { get; set; } [Export ("delegate", ArgumentSemantic.Assign), NullAllowed] NSObject WeakDelegate { get; set; } [Wrap ("WeakDelegate")] PdfViewDelegate Delegate { get; set; } [Export ("scaleFactor")] float ScaleFactor { get; set; } [Export ("zoomIn:")] void ZoomIn (NSObject sender); [Export ("canZoomIn")] bool CanZoomIn { get; } [Export ("zoomOut:")] void ZoomOut (NSObject sender); [Export ("canZoomOut")] bool CanZoomOut { get; } [Export ("autoScales")] bool AutoScales { get; set; } [Export ("areaOfInterestForMouse:")] PdfAreaOfInterest GetAreaOfInterest (NSEvent mouseEvent); [Export ("setCursorForAreaOfInterest:")] void SetCursor (PdfAreaOfInterest area); [Export ("performAction:")] void PerformAction (PdfAction action); [Export ("currentSelection")] PdfSelection CurrentSelection { get; set; } [Export ("setCurrentSelection:animate:")] void SetCurrentSelection (PdfSelection selection, bool animate); [Export ("clearSelection")] void ClearSelection (); [Export ("selectAll:")] void SelectAll (NSObject sender); [Export ("scrollSelectionToVisible:")] void ScrollSelectionToVisible (NSObject sender); // Verify NSArray [Export ("highlightedSelections")] PdfSelection [] HighlightedSelections { get; set; } [Export ("takePasswordFrom:")] void TakePasswordFrom (NSObject sender); [Export ("drawPage:")] void DrawPage (PdfPage page); [Export ("drawPagePost:")] void DrawPagePost (PdfPage page); [Export ("copy:")] void Copy (NSObject sender); [Export ("printWithInfo:autoRotate:")] void Print (NSPrintInfo printInfo, bool doRotate); [Export ("printWithInfo:autoRotate:pageScaling:")] void Print (NSPrintInfo printInfo, bool doRotate, PdfPrintScalingMode scaleMode); [Export ("pageForPoint:nearest:")] PdfPage GetPage (PointF point, bool nearest); [Export ("convertPoint:toPage:")] PointF ConvertPointToPage (PointF point, PdfPage page); [Export ("convertRect:toPage:")] RectangleF ConvertRectangleToPage (RectangleF rect, PdfPage page); [Export ("convertPoint:fromPage:")] PointF ConvertPointFromPage (PointF point, PdfPage page); [Export ("convertRect:fromPage:")] RectangleF ConvertRectangleFromPage (RectangleF rect, PdfPage page); [Export ("documentView")] NSView DocumentView { get; } [Export ("layoutDocumentView")] void LayoutDocumentView (); [Export ("annotationsChangedOnPage:")] void AnnotationsChanged (PdfPage page); [Export ("rowSizeForPage:")] SizeF RowSize (PdfPage page); [Export ("allowsDragging")] bool AllowsDragging { get; set; } //Verify NSArray [Export ("visiblePages")] PdfPage [] VisiblePages { get; } [Export ("enableDataDetectors")] bool EnableDataDetectors { get; set; } [Field("PDFViewChangedHistoryNotification")] [Notification] NSString ChangedHistoryNotification { get; } [Field("PDFViewDocumentChangedNotification")] [Notification] NSString DocumentChangedNotification { get; } [Field ("PDFViewPageChangedNotification")] [Notification] NSString PageChangedNotification { get; } [Field ("PDFViewScaleChangedNotification")] [Notification] NSString ScaleChangedNotification { get; } [Field ("PDFViewAnnotationHitNotification")] [Notification (typeof (PdfViewAnnotationHitEventArgs))] NSString AnnotationHitNotification { get; } [Field ("PDFViewCopyPermissionNotification")] [Notification] NSString CopyPermissionNotification { get; } [Field ("PDFViewAnnotationWillHitNotification")] [Notification] NSString AnnotationWillHitNotification { get; } [Field ("PDFViewSelectionChangedNotification")] [Notification] NSString SelectionChangedNotification { get; } [Field ("PDFViewDisplayModeChangedNotification")] [Notification] NSString DisplayModeChangedNotification { get; } [Field ("PDFViewDisplayBoxChangedNotification")] [Notification] NSString DisplayBoxChangedNotification { get; } } public interface PdfViewAnnotationHitEventArgs { [Export ("PDFAnnotationHit")] PdfAnnotation AnnotationHit { get; } } //Verify delegate methods. There are default actions (not just return null ) that should occur //if the delegate does not implement the method. [BaseType (typeof (NSObject))] [Model] public interface PdfViewDelegate { //from docs: 'By default, the scale factor is restricted to a range between 0.1 and 10.0 inclusive.' [Export ("PDFViewWillChangeScaleFactor:toScale:"), DelegateName ("PdfViewScale"), DefaultValueFromArgument ("scale")] float WillChangeScaleFactor (PdfView sender, float scale); [Export ("PDFViewWillClickOnLink:withURL:"), EventArgs ("PdfViewUrl")] void WillClickOnLink (PdfView sender, NSUrl url); // from the docs: 'By default, this method uses the string, if any, associated with the // 'Title' key in the view's PDFDocument attribute dictionary. If there is no such string, // this method uses the last path component if the document is URL-based. [Export ("PDFViewPrintJobTitle:"), DelegateName ("PdfViewTitle"), DefaultValue ("String.Empty")] string TitleOfPrintJob (PdfView sender); [Export ("PDFViewPerformFind:"), EventArgs ("PdfView")] void PerformFind (PdfView sender); [Export ("PDFViewPerformGoToPage:"), EventArgs ("PdfView")] void PerformGoToPage (PdfView sender); [Export ("PDFViewPerformPrint:"), EventArgs ("PdfView")] void PerformPrint (PdfView sender); [Export ("PDFViewOpenPDF:forRemoteGoToAction:"), EventArgs ("PdfViewAction")] void OpenPdf (PdfView sender, PdfActionRemoteGoTo action); } }
// Copyright 2017, Google 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. // NOTE: This file based on // http://github.com/googleapis/google-cloud-dotnet/blob/c4439e0099d9e4c414afbe666f0d2bb28f95b297/apis/Google.Cloud.Firestore/Google.Cloud.Firestore.Tests/SerializationTestData.cs // This file has been modified from its original version. It has been adapted to use raw C# types // instead of protos and to work in .Net 3.5. using System; using System.Collections.Generic; using System.Linq; using Firebase.Firestore; namespace Tests { internal static class SerializationTestData { private static DateTime dateTime = new DateTime(1990, 1, 2, 3, 4, 5, DateTimeKind.Utc); private static DateTimeOffset dateTimeOffset = new DateTimeOffset(1990, 1, 2, 3, 4, 5, TimeSpan.FromHours(1)); internal class TestCase { /// <summary> /// The object to serialize into Firestore document. /// </summary> internal object Input { get; private set; } /// <summary> /// The expected output from the Firestore document deserialized to raw /// Firestore type (<code>Dictionary&lt;string, object&gt;</code>, or primitive types). /// </summary> internal object ExpectedRawOutput { get; private set; } public TestCase(object input, object expectedRawOutput) { Input = input; ExpectedRawOutput = expectedRawOutput; } } public static IEnumerable<TestCase> TestData(FirebaseFirestore database) { return new List<TestCase> { // Simple types { new TestCase(null, null) }, { new TestCase(true, true) }, { new TestCase(false, false) }, { new TestCase("test", "test") }, { new TestCase((byte)1, 1L) }, { new TestCase((sbyte)1, 1L) }, { new TestCase((short)1, 1L) }, { new TestCase((ushort)1, 1L) }, { new TestCase(1, 1L) }, { new TestCase(1U, 1L) }, { new TestCase(1L, 1L) }, { new TestCase(1UL, 1L) }, { new TestCase(1.5F, 1.5D) }, { new TestCase(float.PositiveInfinity, double.PositiveInfinity) }, { new TestCase(float.NegativeInfinity, double.NegativeInfinity) }, { new TestCase(float.NaN, double.NaN) }, { new TestCase(1.5D, 1.5D) }, { new TestCase(double.PositiveInfinity, double.PositiveInfinity) }, { new TestCase(double.NegativeInfinity, double.NegativeInfinity) }, { new TestCase(double.NaN, double.NaN) }, // Min/max values of each integer type { new TestCase(byte.MinValue, (long)byte.MinValue) }, { new TestCase(byte.MaxValue, (long)byte.MaxValue) }, { new TestCase(sbyte.MinValue, (long)sbyte.MinValue) }, { new TestCase(sbyte.MaxValue, (long)sbyte.MaxValue) }, { new TestCase(short.MinValue, (long)short.MinValue) }, { new TestCase(short.MaxValue, (long)short.MaxValue) }, { new TestCase(ushort.MinValue, (long)ushort.MinValue) }, { new TestCase(ushort.MaxValue, (long)ushort.MaxValue) }, { new TestCase(int.MinValue, (long)int.MinValue) }, { new TestCase(int.MaxValue, (long)int.MaxValue) }, { new TestCase(uint.MinValue, (long)uint.MinValue) }, { new TestCase(uint.MaxValue, (long)uint.MaxValue) }, { new TestCase(long.MinValue, long.MinValue) }, { new TestCase(long.MaxValue, long.MaxValue) }, // We don't cover the whole range of ulong { new TestCase((ulong)0, 0L) }, { new TestCase((ulong) long.MaxValue, long.MaxValue) }, // Enum types { new TestCase(ByteEnum.MinValue, (long)byte.MinValue) }, { new TestCase(ByteEnum.MaxValue, (long)byte.MaxValue) }, { new TestCase(SByteEnum.MinValue, (long)sbyte.MinValue) }, { new TestCase(SByteEnum.MaxValue, (long)sbyte.MaxValue) }, { new TestCase(Int16Enum.MinValue, (long)short.MinValue) }, { new TestCase(Int16Enum.MaxValue, (long)short.MaxValue) }, { new TestCase(UInt16Enum.MinValue, (long)ushort.MinValue) }, { new TestCase(UInt16Enum.MaxValue, (long)ushort.MaxValue) }, { new TestCase(Int32Enum.MinValue, (long)int.MinValue) }, { new TestCase(Int32Enum.MaxValue, (long)int.MaxValue) }, { new TestCase(UInt32Enum.MinValue, (long)uint.MinValue) }, { new TestCase(UInt32Enum.MaxValue, (long)uint.MaxValue) }, { new TestCase(Int64Enum.MinValue, (long)long.MinValue) }, { new TestCase(Int64Enum.MaxValue, (long)long.MaxValue) }, // We don't cover the whole range of ulong { new TestCase(UInt64Enum.MinValue, (long)0) }, { new TestCase(UInt64Enum.MaxRepresentableValue, (long)long.MaxValue) }, { new TestCase(CustomConversionEnum.Foo, "Foo") }, { new TestCase(CustomConversionEnum.Bar, "Bar") }, // Timestamps { new TestCase(Timestamp.FromDateTime(dateTime), Timestamp.FromDateTime(dateTime)) }, { new TestCase(dateTime, Timestamp.FromDateTime(dateTime)) }, { new TestCase(dateTimeOffset, Timestamp.FromDateTimeOffset(dateTimeOffset)) }, // Blobs { new TestCase(new byte[] { 1, 2, 3, 4 }, Blob.CopyFrom(new byte[] { 1, 2, 3, 4 })) }, { new TestCase(Blob.CopyFrom(new byte[] { 1, 2, 3, 4 }), Blob.CopyFrom(new byte[] { 1, 2, 3, 4 })) }, // GeoPoints { new TestCase(new GeoPoint(1.5, 2.5), new GeoPoint(1.5, 2.5)) }, // Array values { new TestCase(new string[] { "x", "y" }, new List<object> { "x", "y" }) }, { new TestCase(new List<string> { "x", "y" }, new List<object> { "x", "y" }) }, { new TestCase(new int[] { 3, 4 }, new List<object> { 3L, 4L }) }, // Deliberately DateTime rather than Timestamp here - we need to be able to detect the // element type to perform the per-element deserialization correctly { new TestCase(new List<DateTime> { dateTime, dateTime }, new List<object> { Timestamp.FromDateTime(dateTime), Timestamp.FromDateTime(dateTime) }) }, // Map values (that can be deserialized again): dictionaries, attributed types, expandos // (which are just dictionaries), custom serialized map-like values // Dictionaries { new TestCase(new Dictionary<string, byte> { { "A", 10 }, { "B", 20 } }, new Dictionary<string, object> { { "A", 10L }, { "B", 20L } }) }, { new TestCase(new Dictionary<string, int> { { "A", 10 }, { "B", 20 } }, new Dictionary<string, object> { { "A", 10L }, { "B", 20L } }) }, { new TestCase(new Dictionary<string, object> { { "name", "Jon" }, { "score", 10L } }, new Dictionary<string, object> { { "name", "Jon" }, { "score", 10L } }) }, // Attributed type (each property has an attribute) { new TestCase(new GameResult { Name = "Jon", Score = 10 }, new Dictionary<string, object> { { "name", "Jon" }, { "Score", 10L } }) }, // Attributed type contained in a dictionary { new TestCase( new Dictionary<string, GameResult> { { "result", new GameResult { Name = "Jon", Score = 10 } } }, new Dictionary<string, object> { { "result", new Dictionary<string, object> { { "name", "Jon" }, { "Score", 10L } } } }) }, // Attributed type containing a dictionary { new TestCase( new DictionaryInterfaceContainer { Integers = new Dictionary<string, int> { { "A", 10 }, { "B", 20 } } }, new Dictionary<string, object> { { "Integers", new Dictionary<string, object> { { "A", 10L }, { "B", 20L } } } }) }, // Attributed type serialized and deserialized by CustomPlayerConverter { new TestCase(new CustomPlayer { Name = "Amanda", Score = 15 }, new Dictionary<string, object> { { "PlayerName", "Amanda" }, { "PlayerScore", 15L } }) }, // Attributed value type serialized and deserialized by CustomValueTypeConverter { new TestCase(new CustomValueType("xyz", 10), new Dictionary<string, object> { { "Name", "xyz" }, { "Value", 10L } }) }, // Attributed type with enums (name and number) { new TestCase(new ModelWithEnums { EnumDefaultByName = CustomConversionEnum.Foo, EnumAttributedByName = Int32Enum.MinValue, EnumByNumber = Int32Enum.MaxValue }, new Dictionary<string, object> { { "EnumDefaultByName", "Foo" }, { "EnumAttributedByName", "MinValue" }, { "EnumByNumber", (long)int.MaxValue } }) }, // Attributed type with List field { new TestCase(new CustomUser { Name = "Jon", HighScore = 10, Emails = new List<string> { "jon@example.com" } }, new Dictionary<string, object> { { "Name", "Jon" }, { "HighScore", 10L }, { "Emails", new List<object> { "jon@example.com" } } }) }, // Attributed type with IEnumerable field { new TestCase( new CustomUserEnumerableEmails() { Name = "Jon", HighScore = 10, Emails = new List<string> { "jon@example.com" } }, new Dictionary<string, object> { { "Name", "Jon" }, { "HighScore", 10L }, { "Emails", new List<object> { "jon@example.com" } } }) }, // Attributed type with Set field and custom converter. { new TestCase( new CustomUserSetEmailsWithConverter() { Name = "Jon", HighScore = 10, Emails = new HashSet<string> { "jon@example.com" } }, new Dictionary<string, object> { { "Name", "Jon" }, { "HighScore", 10L }, { "Emails", new List<object> { "jon@example.com" } } }) }, // Attributed struct { new TestCase(new StructModel { Name = "xyz", Value = 10 }, new Dictionary<string, object> { { "Name", "xyz" }, { "Value", 10L } }) }, // Document references { new TestCase(database.Document("a/b"), database.Document("a/b")) }, }; } public static IEnumerable<TestCase> UnsupportedTestData() { return new List<TestCase> { // Nullable type handling { new TestCase(new NullableContainer { NullableValue = 10 }, new Dictionary<string, object> { { "NullableValue", 10L } }) }, { new TestCase(new NullableEnumContainer { NullableValue = (Int32Enum)10 }, new Dictionary<string, object> { { "NullableValue", 10L } }) }, // This one fails because the `NullableContainer` it gets back has a random value // while it should be null. { new TestCase(new NullableContainer { NullableValue = null }, new Dictionary<string, object> { { "NullableValue", null } }) }, { new TestCase(new NullableEnumContainer { NullableValue = null }, new Dictionary<string, object> { { "NullableValue", null } }) }, }; } // Test data that is serializable, but cannot be deserialized into the original types. public static IEnumerable<TestCase> UnsupportedReadToInputTypesTestData() { return new List<TestCase> { // IEnumerable values cannot be assigned from a List. // TODO(b/173894435): there should be a way to specify if it is serialization or // deserialization failure. { new TestCase(Enumerable.Range(3, 2).Select(i => (long)i), Enumerable.Range(3, 2).Select(i => (long)i)) }, { new TestCase( new CustomUserSetEmails { Name = "Jon", HighScore = 10, Emails = new HashSet<string> { "jon@example.com" } }, new Dictionary<string, object> { { "Name", "Jon" }, { "HighScore", 10L }, { "Emails", new List<object> { "jon@example.com" } } }) } }; } // Only equatable for the sake of testing; that's not a requirement of the serialization code. [FirestoreData] internal class GameResult : IEquatable<GameResult> { [FirestoreProperty("name")] public string Name { get; set; } [FirestoreProperty] // No property name specified, so field will be Score public int Score { get; set; } public override int GetHashCode() { return Name.GetHashCode() ^ Score; } public override bool Equals(object obj) { return Equals(obj as GameResult); } public bool Equals(GameResult other) { return other != null && other.Name == Name && other.Score == Score; } } [FirestoreData] internal class NullableContainer : IEquatable<NullableContainer> { [FirestoreProperty] public long? NullableValue { get; set; } public override int GetHashCode() { return (int)NullableValue.GetValueOrDefault().GetHashCode(); } public override bool Equals(object obj) { return Equals(obj as NullableContainer); } public bool Equals(NullableContainer other) { return other != null && other.NullableValue == NullableValue; } public override string ToString() { return String.Format("NullableContainer: {0}", NullableValue.GetValueOrDefault()); } } [FirestoreData] internal class NullableEnumContainer : IEquatable<NullableEnumContainer> { [FirestoreProperty] public Int32Enum? NullableValue { get; set; } public override int GetHashCode() { return (int)NullableValue.GetValueOrDefault().GetHashCode(); } public override bool Equals(object obj) { return Equals(obj as NullableEnumContainer); } public bool Equals(NullableEnumContainer other) { return other != null && other.NullableValue == NullableValue; } } [FirestoreData] internal class DictionaryInterfaceContainer : IEquatable<DictionaryInterfaceContainer> { [FirestoreProperty] public IDictionary<string, int> Integers { get; set; } public override int GetHashCode() { return Integers.Sum(pair => pair.Key.GetHashCode() + pair.Value); } public override bool Equals(object obj) { return Equals(obj as DictionaryInterfaceContainer); } public bool Equals(DictionaryInterfaceContainer other) { if (other == null) { return false; } if (Integers == other.Integers) { return true; } if (Integers == null || other.Integers == null) { return false; } if (Integers.Count != other.Integers.Count) { return false; } int otherValue; return Integers.All(pair => other.Integers.TryGetValue(pair.Key, out otherValue) && pair.Value == otherValue); } } internal enum SByteEnum : sbyte { MinValue = sbyte.MinValue, MaxValue = sbyte.MaxValue } internal enum Int16Enum : short { MinValue = short.MinValue, MaxValue = short.MaxValue } internal enum Int32Enum : int { MinValue = int.MinValue, MaxValue = int.MaxValue } internal enum Int64Enum : long { MinValue = long.MinValue, MaxValue = long.MaxValue } internal enum ByteEnum : byte { MinValue = byte.MinValue, MaxValue = byte.MaxValue } internal enum UInt16Enum : ushort { MinValue = ushort.MinValue, MaxValue = ushort.MaxValue } internal enum UInt32Enum : uint { MinValue = uint.MinValue, MaxValue = uint.MaxValue } internal enum UInt64Enum : ulong { MinValue = ulong.MinValue, MaxRepresentableValue = long.MaxValue } [FirestoreData(ConverterType = typeof(FirestoreEnumNameConverter<CustomConversionEnum>))] internal enum CustomConversionEnum { Foo = 1, Bar = 2 } [FirestoreData] public sealed class ModelWithEnums { [FirestoreProperty] public CustomConversionEnum EnumDefaultByName { get; set; } [FirestoreProperty(ConverterType = typeof(FirestoreEnumNameConverter<Int32Enum>))] public Int32Enum EnumAttributedByName { get; set; } [FirestoreProperty] public Int32Enum EnumByNumber { get; set; } public override bool Equals(object obj) { if (!(obj is ModelWithEnums)) { return false; } ModelWithEnums other = obj as ModelWithEnums; return EnumDefaultByName == other.EnumDefaultByName && EnumAttributedByName == other.EnumAttributedByName && EnumByNumber == other.EnumByNumber; } public override int GetHashCode() { return 0; } } [FirestoreData] public sealed class CustomUser { [FirestoreProperty] public int HighScore { get; set; } [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public List<string> Emails { get; set; } public override bool Equals(object obj) { if (!(obj is CustomUser)) { return false; } CustomUser other = (CustomUser)obj; return HighScore == other.HighScore && Name == other.Name && Emails.SequenceEqual(other.Emails); } public override int GetHashCode() { return 0; } } [FirestoreData] public sealed class CustomUserEnumerableEmails { [FirestoreProperty] public int HighScore { get; set; } [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public IEnumerable<string> Emails { get; set; } public override bool Equals(object obj) { if (!(obj is CustomUserEnumerableEmails)) { return false; } CustomUserEnumerableEmails other = (CustomUserEnumerableEmails)obj; return HighScore == other.HighScore && Name == other.Name && Emails.SequenceEqual(other.Emails); } public override int GetHashCode() { return 0; } } [FirestoreData] public sealed class CustomUserSetEmails { [FirestoreProperty] public int HighScore { get; set; } [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public HashSet<string> Emails { get; set; } public override bool Equals(object obj) { if (!(obj is CustomUserSetEmails)) { return false; } CustomUserSetEmails other = (CustomUserSetEmails)obj; return HighScore == other.HighScore && Name == other.Name && Emails.SequenceEqual(other.Emails); } public override int GetHashCode() { return 0; } } [FirestoreData(ConverterType = typeof(CustomUserSetEmailsConverter))] public sealed class CustomUserSetEmailsWithConverter { [FirestoreProperty] public int HighScore { get; set; } [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public HashSet<string> Emails { get; set; } public override bool Equals(object obj) { if (!(obj is CustomUserSetEmailsWithConverter)) { return false; } var other = (CustomUserSetEmailsWithConverter)obj; return HighScore == other.HighScore && Name == other.Name && Emails.SequenceEqual(other.Emails); } public override int GetHashCode() { return 0; } } public class CustomUserSetEmailsConverter : FirestoreConverter<CustomUserSetEmailsWithConverter> { public override CustomUserSetEmailsWithConverter FromFirestore(object value) { if (value == null) { throw new ArgumentNullException("value"); // Shouldn't happen } var map = (Dictionary<string, object>)value; var emails = (List<object>)map["Emails"]; var emailSet = new HashSet<string>(emails.Select(o => o.ToString())); return new CustomUserSetEmailsWithConverter { Name = (string)map["Name"], HighScore = Convert.ToInt32(map["HighScore"]), Emails = emailSet }; } public override object ToFirestore(CustomUserSetEmailsWithConverter value) { return new Dictionary<string, object> { { "Name", value.Name }, { "HighScore", value.HighScore }, { "Emails", value.Emails }, }; } } [FirestoreData(ConverterType = typeof(EmailConverter))] public sealed class Email { public readonly string Address; public Email(string address) { Address = address; } } public class EmailConverter : FirestoreConverter<Email> { public override Email FromFirestore(object value) { if (value == null) { throw new ArgumentNullException("value"); // Shouldn't happen } else if (value is string) { return new Email(value as string); } else { throw new ArgumentException(String.Format("Unexpected data: {}", value.GetType())); } } public override object ToFirestore(Email value) { return value == null ? null : value.Address; } } [FirestoreData] public class GuidPair { [FirestoreProperty] public string Name { get; set; } [FirestoreProperty(ConverterType = typeof(GuidConverter))] public Guid Guid { get; set; } [FirestoreProperty(ConverterType = typeof(GuidConverter))] public Guid ? GuidOrNull { get; set; } } // Like GuidPair, but without the converter specified - it has to come // from a converter registry instead. [FirestoreData] public class GuidPair2 { [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public Guid Guid { get; set; } [FirestoreProperty] public Guid? GuidOrNull { get; set; } } public class GuidConverter : FirestoreConverter<Guid> { public override Guid FromFirestore(object value) { if (value == null) { throw new ArgumentNullException("value"); // Shouldn't happen } else if (value is string) { return new Guid(value as string); } else { throw new ArgumentException(String.Format("Unexpected data: {0}", value.GetType())); } } public override object ToFirestore(Guid value) { return value.ToString("N"); } } // Only equatable for the sake of testing; that's not a requirement of the serialization code. [FirestoreData(ConverterType = typeof(CustomPlayerConverter))] public class CustomPlayer : IEquatable<CustomPlayer> { public string Name { get; set; } public int Score { get; set; } public override int GetHashCode() { return Name.GetHashCode() ^ Score; } public override bool Equals(object obj) { return Equals(obj as CustomPlayer); } public bool Equals(CustomPlayer other) { return other != null && other.Name == Name && other.Score == Score; } } public class CustomPlayerConverter : FirestoreConverter<CustomPlayer> { public override CustomPlayer FromFirestore(object value) { var map = (IDictionary<string, object>)value; return new CustomPlayer { Name = (string)map["PlayerName"], // Unbox to long, then convert to int. Score = (int)(long)map["PlayerScore"] }; } public override object ToFirestore(CustomPlayer value) { return new Dictionary<string, object> { { "PlayerName", value.Name }, { "PlayerScore", value.Score } }; } } [FirestoreData(ConverterType = typeof(CustomValueTypeConverter))] internal struct CustomValueType : IEquatable<CustomValueType> { public readonly string Name; public readonly int Value; public CustomValueType(string name, int value) { Name = name; Value = value; } public override int GetHashCode() { return Name.GetHashCode() + Value; } public override bool Equals(object obj) { return obj is CustomValueType && Equals((CustomValueType)obj); } public bool Equals(CustomValueType other) { return Name == other.Name && Value == other.Value; } public override string ToString() { return String.Format("CustomValueType: {0}", new { Name, Value }); } } internal class CustomValueTypeConverter : FirestoreConverter<CustomValueType> { public override CustomValueType FromFirestore(object value) { var dictionary = (IDictionary<string, object>)value; return new CustomValueType((string)dictionary["Name"], (int)(long)dictionary["Value"]); } public override object ToFirestore(CustomValueType value) { return new Dictionary<string, object> { { "Name", value.Name }, { "Value", value.Value } }; } } [FirestoreData] internal struct StructModel : IEquatable<StructModel> { [FirestoreProperty] public string Name { get; set; } [FirestoreProperty] public int Value { get; set; } public override int GetHashCode() { return Name.GetHashCode() + Value; } public override bool Equals(object obj) { return obj is StructModel && Equals((StructModel)obj); } public bool Equals(StructModel other) { return Name == other.Name && Value == other.Value; } public override string ToString() { return String.Format("StructModel: {0}", new { Name, Value }); } } } }
// // Created by Shopify. // Copyright (c) 2016 Shopify Inc. All rights reserved. // Copyright (c) 2016 Xamarin Inc. All rights reserved. // // 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 CoreGraphics; using Foundation; using PassKit; using SafariServices; using UIKit; using Shopify.Buy; namespace ShopifyiOSSample { public class PreCheckoutViewController : UITableViewController { private readonly BuyClient client; private Checkout _checkout; private PKPaymentSummaryItem[] summaryItems; private enum UITableViewSections { SummaryItems, DiscountGiftCard, Continue, Count } private enum UITableViewDiscountGiftCardSection { Discount, GiftCard, Count } public PreCheckoutViewController (BuyClient client, Checkout checkout) : base (UITableViewStyle.Grouped) { this.client = client; this.checkout = checkout; } public NSNumberFormatter CurrencyFormatter { get; set; } private Checkout checkout { get { return _checkout; } set { _checkout = value; // We can take advantage of the PKPaymentSummaryItems used for // Apple Pay to display summary items natively in our own // checkout summaryItems = _checkout.ApplePaySummaryItems (); } } public override void ViewDidLoad () { base.ViewDidLoad (); Title = "Add Discount or Gift Card(s)"; TableView.RegisterClassForCellReuse (typeof(UITableViewCell), "Cell"); } public override nint NumberOfSections (UITableView tableView) { return (int)UITableViewSections.Count; } public override nint RowsInSection (UITableView tableView, nint section) { switch ((UITableViewSections)(int)section) { case UITableViewSections.SummaryItems: return summaryItems == null ? 0 : summaryItems.Length; case UITableViewSections.DiscountGiftCard: return (int)UITableViewDiscountGiftCardSection.Count; default: return 1; } } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = null; switch ((UITableViewSections)indexPath.Section) { case UITableViewSections.SummaryItems: cell = tableView.DequeueReusableCell ("SummaryCell") ?? new SummaryItemsTableViewCell ("SummaryCell"); var summaryItem = summaryItems [indexPath.Row]; cell.TextLabel.Text = summaryItem.Label; cell.DetailTextLabel.Text = CurrencyFormatter.StringFromNumber (summaryItem.Amount); cell.SelectionStyle = UITableViewCellSelectionStyle.None; // Only show a line above the last cell if (indexPath.Row != summaryItems.Length - 2) { cell.SeparatorInset = new UIEdgeInsets (0.0f, 0.0f, 0.0f, cell.Bounds.Size.Width); } break; case UITableViewSections.DiscountGiftCard: cell = tableView.DequeueReusableCell ("Cell", indexPath); cell.SeparatorInset = UIEdgeInsets.Zero; switch ((UITableViewDiscountGiftCardSection)indexPath.Row) { case UITableViewDiscountGiftCardSection.Discount: cell.TextLabel.Text = "Add Discount"; break; case UITableViewDiscountGiftCardSection.GiftCard: cell.TextLabel.Text = "Apply Gift Card"; break; } cell.TextLabel.TextAlignment = UITextAlignment.Center; break; case UITableViewSections.Continue: cell = tableView.DequeueReusableCell ("Cell", indexPath); cell.TextLabel.Text = "Continue"; cell.TextLabel.TextAlignment = UITextAlignment.Center; break; } cell.PreservesSuperviewLayoutMargins = false; cell.LayoutMargins = UIEdgeInsets.Zero; return cell; } public override void RowSelected (UITableView tableView, NSIndexPath indexPath) { switch ((UITableViewSections)indexPath.Section) { case UITableViewSections.DiscountGiftCard: switch ((UITableViewDiscountGiftCardSection)indexPath.Row) { case UITableViewDiscountGiftCardSection.Discount: AddDiscount (); break; case UITableViewDiscountGiftCardSection.GiftCard: ApplyGiftCard (); break; } break; case UITableViewSections.Continue: ProceedToCheckout (); break; } tableView.DeselectRow (indexPath, true); } private void AddDiscount () { var alertController = UIAlertController.Create ("Enter Discount Code", null, UIAlertControllerStyle.Alert); alertController.AddTextField (textField => { textField.Placeholder = "Discount Code"; }); alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, action => { Console.WriteLine ("Cancel action"); })); alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, action => { var discount = new Discount (alertController.TextFields [0].Text); checkout.Discount = discount; UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; client.UpdateCheckout (checkout, (checkout, error) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; if (error == null && checkout != null) { Console.WriteLine ("Successfully added discount"); this.checkout = checkout; TableView.ReloadData (); } else { Console.WriteLine ("Error applying discount: {0}", error); } }); })); PresentViewController (alertController, true, null); } private void ApplyGiftCard () { var alertController = UIAlertController.Create ("Enter Gift Card Code", null, UIAlertControllerStyle.Alert); alertController.AddTextField (textField => { textField.Placeholder = "Gift Card Code"; }); alertController.AddAction (UIAlertAction.Create ("Cancel", UIAlertActionStyle.Cancel, action => { Console.WriteLine ("Cancel action"); })); alertController.AddAction (UIAlertAction.Create ("OK", UIAlertActionStyle.Default, action => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = true; client.ApplyGiftCard (alertController.TextFields [0].Text, checkout, (checkout, error) => { UIApplication.SharedApplication.NetworkActivityIndicatorVisible = false; if (error == null && checkout != null) { Console.WriteLine ("Successfully added gift card"); this.checkout = checkout; TableView.ReloadData (); } else { Console.WriteLine ("Error applying gift card: {0}", error); } }); })); PresentViewController (alertController, true, null); } private void ProceedToCheckout () { var checkoutController = new CheckoutViewController (client, checkout); checkoutController.CurrencyFormatter = CurrencyFormatter; NavigationController.PushViewController (checkoutController, true); } } }
// ******************************************************************************************************** // Product Name: DotSpatial.Symbology.Forms.dll // Description: The Windows Forms user interface layer for the DotSpatial.Symbology library. // ******************************************************************************************************** // // The Original Code is from MapWindow.dll version 6.0 // // The Initial Developer of this Original Code is Ted Dunsford. Created 5/22/2009 11:21:12 AM // // Contributor(s): (Open source contributors should list themselves and their modifications here). // // ******************************************************************************************************** using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace DotSpatial.Symbology.Forms { /// <summary> /// GradientControl /// </summary> [DefaultEvent("PositionChanging"), ToolboxItem(false)] public class GradientSlider : Control { /// <summary> /// Occurs as the user is adjusting the positions on either of the sliders /// </summary> public event EventHandler PositionChanging; /// <summary> /// Occurs after the user has finished adjusting the positions of either of the sliders and has released control /// </summary> public event EventHandler PositionChanged; #region Private Variables private RoundedHandle _leftHandle; private float _max; private Color _maxColor; private float _min; private Color _minColor; private RoundedHandle _rightHandle; #endregion #region Constructors /// <summary> /// Creates a new instance of GradientControl /// </summary> public GradientSlider() { _min = 0F; _max = 1F; _leftHandle = new RoundedHandle(this); _leftHandle.Position = .2F; _rightHandle = new RoundedHandle(this); _rightHandle.Position = .8F; _minColor = Color.Transparent; _maxColor = Color.Blue; } #endregion #region Methods #endregion #region Properties /// <summary> /// Gets or sets the floating point position of the left slider. This must range /// between 0 and 1, and to the left of the right slider, (therefore with a value lower than the right slider.) /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter))] public RoundedHandle LeftHandle { get { return _leftHandle; } set { _leftHandle = value; } } /// <summary> /// Gets or sets the floating point position of the right slider. This must range /// between 0 and 1, and to the right of the left slider. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Content), TypeConverter(typeof(ExpandableObjectConverter))] public RoundedHandle RightHandle { get { return _rightHandle; } set { _rightHandle = value; } } /// <summary> /// Gets or sets the minimum allowed value for the slider. /// </summary> [Description("Gets or sets the minimum allowed value for the slider.")] public float Minimum { get { return _min; } set { _min = value; if (_leftHandle.Position < _min) _leftHandle.Position = _min; if (_rightHandle.Position < _min) _rightHandle.Position = _min; } } /// <summary> /// Gets or sets the color associated with the minimum color /// </summary> [Description("Gets or sets the color associated with the minimum value")] public Color MinimumColor { get { return _minColor; } set { _minColor = value; Invalidate(); } } /// <summary> /// Gets or sets the maximum allowed value for the slider. /// </summary> [Description("Gets or sets the maximum allowed value for the slider.")] public float Maximum { get { return _max; } set { _max = value; if (_max < _rightHandle.Position) _rightHandle.Position = _max; if (_max < _leftHandle.Position) _leftHandle.Position = _max; } } /// <summary> /// Gets or sets the color associated with the maximum value. /// </summary> [Description("Gets or sets the color associated with the maximum value.")] public Color MaximumColor { get { return _maxColor; } set { _maxColor = value; Invalidate(); } } #endregion #region Protected Methods /// <summary> /// Prevent flicker /// </summary> /// <param name="pevent"></param> protected override void OnPaintBackground(PaintEventArgs pevent) { //base.OnPaintBackground(pevent); } /// <summary> /// Draw the clipped portion /// </summary> /// <param name="e"></param> protected override void OnPaint(PaintEventArgs e) { Rectangle clip = e.ClipRectangle; if (clip.IsEmpty) clip = ClientRectangle; Bitmap bmp = new Bitmap(clip.Width, clip.Height); Graphics g = Graphics.FromImage(bmp); g.TranslateTransform(-clip.X, -clip.Y); g.Clip = new Region(clip); g.Clear(BackColor); g.SmoothingMode = SmoothingMode.AntiAlias; OnDraw(g, clip); g.Dispose(); e.Graphics.DrawImage(bmp, clip, new Rectangle(0, 0, clip.Width, clip.Height), GraphicsUnit.Pixel); } /// <summary> /// Controls the actual drawing for this gradient slider control. /// </summary> /// <param name="g"></param> /// <param name="clipRectangle"></param> protected virtual void OnDraw(Graphics g, Rectangle clipRectangle) { if (Width == 0 || Height == 0) return; LinearGradientBrush lgb = new LinearGradientBrush(ClientRectangle, BackColor.Lighter(.2F), BackColor.Darker(.2F), LinearGradientMode.Vertical); g.FillRectangle(lgb, ClientRectangle); lgb.Dispose(); int l = Convert.ToInt32((Width * (_leftHandle.Position - _min)) / (_max - _min)); int r = Convert.ToInt32((Width * (_rightHandle.Position - _min)) / (_max - _min)); Rectangle a = new Rectangle(0, 5, l, Height - 10); Rectangle b = new Rectangle(l, 5, r - l, Height - 10); Rectangle c = new Rectangle(r, 5, Right - r, Height - 10); if (a.Width > 0) { SolidBrush sb = new SolidBrush(_minColor); g.FillRectangle(sb, a); sb.Dispose(); } if (b.Width > 0) { LinearGradientBrush center = new LinearGradientBrush(new Point(b.X, 0), new Point(b.Right, 0), _minColor, _maxColor); g.FillRectangle(center, b); center.Dispose(); } if (c.Width > 0) { SolidBrush sb = new SolidBrush(_maxColor); g.FillRectangle(sb, c); sb.Dispose(); } if (Enabled) { _leftHandle.Draw(g); _rightHandle.Draw(g); } } /// <summary> /// Initiates slider dragging /// </summary> /// <param name="e"></param> protected override void OnMouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Left && Enabled) { Rectangle l = _leftHandle.GetBounds(); if (l.Contains(e.Location) && _leftHandle.Visible) { _leftHandle.IsDragging = true; } Rectangle r = _rightHandle.GetBounds(); if (r.Contains(e.Location) && _rightHandle.Visible) { _rightHandle.IsDragging = true; } } base.OnMouseDown(e); } /// <summary> /// Handles slider dragging /// </summary> /// <param name="e"></param> protected override void OnMouseMove(MouseEventArgs e) { if (_rightHandle.IsDragging) { float x = e.X; int min = 0; if (_leftHandle.Visible) min = _leftHandle.Width; if (x > Width) x = Width; if (x < min) x = min; _rightHandle.Position = _min + (x / Width) * (_max - _min); if (_leftHandle.Visible) { float lw = _leftHandle.Width / (float)Width * (_max - _min); if (_leftHandle.Position > _rightHandle.Position - lw) { _leftHandle.Position = _rightHandle.Position - lw; } } OnPositionChanging(); } if (_leftHandle.IsDragging) { float x = e.X; int max = Width; if (_rightHandle.Visible) max = Width - _rightHandle.Width; if (x > max) x = max; if (x < 0) x = 0; _leftHandle.Position = _min + (x / Width) * (_max - _min); if (_rightHandle.Visible) { float rw = _rightHandle.Width / (float)Width * (_max - _min); if (_rightHandle.Position < _leftHandle.Position + rw) { _rightHandle.Position = _leftHandle.Position + rw; } } OnPositionChanging(); } Invalidate(); base.OnMouseMove(e); } /// <summary> /// Handles the mouse up situation /// </summary> /// <param name="e"></param> protected override void OnMouseUp(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { if (_rightHandle.IsDragging) _rightHandle.IsDragging = false; if (_leftHandle.IsDragging) _leftHandle.IsDragging = false; OnPositionChanged(); } base.OnMouseUp(e); } /// <summary> /// Fires the Position Changing event while either slider is being dragged /// </summary> protected virtual void OnPositionChanging() { if (PositionChanging != null) PositionChanging(this, EventArgs.Empty); } /// <summary> /// Fires the Position Changed event after sliders are released /// </summary> protected virtual void OnPositionChanged() { if (PositionChanged != null) PositionChanged(this, EventArgs.Empty); } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V8.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using gr = Google.Rpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V8.Services; namespace Google.Ads.GoogleAds.Tests.V8.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedAdGroupCriterionLabelServiceClientTest { [Category("Autogenerated")][Test] public void GetAdGroupCriterionLabelRequestObject() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionLabelRequest request = new GetAdGroupCriterionLabelRequest { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), }; gagvr::AdGroupCriterionLabel expectedResponse = new gagvr::AdGroupCriterionLabel { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionLabel response = client.GetAdGroupCriterionLabel(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupCriterionLabelRequestObjectAsync() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionLabelRequest request = new GetAdGroupCriterionLabelRequest { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), }; gagvr::AdGroupCriterionLabel expectedResponse = new gagvr::AdGroupCriterionLabel { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupCriterionLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionLabel responseCallSettings = await client.GetAdGroupCriterionLabelAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupCriterionLabel responseCancellationToken = await client.GetAdGroupCriterionLabelAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupCriterionLabel() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionLabelRequest request = new GetAdGroupCriterionLabelRequest { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), }; gagvr::AdGroupCriterionLabel expectedResponse = new gagvr::AdGroupCriterionLabel { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionLabel response = client.GetAdGroupCriterionLabel(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupCriterionLabelAsync() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionLabelRequest request = new GetAdGroupCriterionLabelRequest { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), }; gagvr::AdGroupCriterionLabel expectedResponse = new gagvr::AdGroupCriterionLabel { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupCriterionLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionLabel responseCallSettings = await client.GetAdGroupCriterionLabelAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupCriterionLabel responseCancellationToken = await client.GetAdGroupCriterionLabelAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void GetAdGroupCriterionLabelResourceNames() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionLabelRequest request = new GetAdGroupCriterionLabelRequest { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), }; gagvr::AdGroupCriterionLabel expectedResponse = new gagvr::AdGroupCriterionLabel { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionLabel(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionLabel response = client.GetAdGroupCriterionLabel(request.ResourceNameAsAdGroupCriterionLabelName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task GetAdGroupCriterionLabelResourceNamesAsync() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); GetAdGroupCriterionLabelRequest request = new GetAdGroupCriterionLabelRequest { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), }; gagvr::AdGroupCriterionLabel expectedResponse = new gagvr::AdGroupCriterionLabel { ResourceNameAsAdGroupCriterionLabelName = gagvr::AdGroupCriterionLabelName.FromCustomerAdGroupCriterionLabel("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]", "[LABEL_ID]"), AdGroupCriterionAsAdGroupCriterionName = gagvr::AdGroupCriterionName.FromCustomerAdGroupCriterion("[CUSTOMER_ID]", "[AD_GROUP_ID]", "[CRITERION_ID]"), LabelAsLabelName = gagvr::LabelName.FromCustomerLabel("[CUSTOMER_ID]", "[LABEL_ID]"), }; mockGrpcClient.Setup(x => x.GetAdGroupCriterionLabelAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::AdGroupCriterionLabel>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); gagvr::AdGroupCriterionLabel responseCallSettings = await client.GetAdGroupCriterionLabelAsync(request.ResourceNameAsAdGroupCriterionLabelName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::AdGroupCriterionLabel responseCancellationToken = await client.GetAdGroupCriterionLabelAsync(request.ResourceNameAsAdGroupCriterionLabelName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupCriterionLabelsRequestObject() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupCriterionLabelsRequest request = new MutateAdGroupCriterionLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupCriterionLabelOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateAdGroupCriterionLabelsResponse expectedResponse = new MutateAdGroupCriterionLabelsResponse { Results = { new MutateAdGroupCriterionLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupCriterionLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupCriterionLabelsResponse response = client.MutateAdGroupCriterionLabels(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupCriterionLabelsRequestObjectAsync() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupCriterionLabelsRequest request = new MutateAdGroupCriterionLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupCriterionLabelOperation(), }, PartialFailure = false, ValidateOnly = true, }; MutateAdGroupCriterionLabelsResponse expectedResponse = new MutateAdGroupCriterionLabelsResponse { Results = { new MutateAdGroupCriterionLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupCriterionLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupCriterionLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupCriterionLabelsResponse responseCallSettings = await client.MutateAdGroupCriterionLabelsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupCriterionLabelsResponse responseCancellationToken = await client.MutateAdGroupCriterionLabelsAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public void MutateAdGroupCriterionLabels() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupCriterionLabelsRequest request = new MutateAdGroupCriterionLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupCriterionLabelOperation(), }, }; MutateAdGroupCriterionLabelsResponse expectedResponse = new MutateAdGroupCriterionLabelsResponse { Results = { new MutateAdGroupCriterionLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupCriterionLabels(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupCriterionLabelsResponse response = client.MutateAdGroupCriterionLabels(request.CustomerId, request.Operations); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Autogenerated")][Test] public async stt::Task MutateAdGroupCriterionLabelsAsync() { moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient> mockGrpcClient = new moq::Mock<AdGroupCriterionLabelService.AdGroupCriterionLabelServiceClient>(moq::MockBehavior.Strict); MutateAdGroupCriterionLabelsRequest request = new MutateAdGroupCriterionLabelsRequest { CustomerId = "customer_id3b3724cb", Operations = { new AdGroupCriterionLabelOperation(), }, }; MutateAdGroupCriterionLabelsResponse expectedResponse = new MutateAdGroupCriterionLabelsResponse { Results = { new MutateAdGroupCriterionLabelResult(), }, PartialFailureError = new gr::Status(), }; mockGrpcClient.Setup(x => x.MutateAdGroupCriterionLabelsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<MutateAdGroupCriterionLabelsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); AdGroupCriterionLabelServiceClient client = new AdGroupCriterionLabelServiceClientImpl(mockGrpcClient.Object, null); MutateAdGroupCriterionLabelsResponse responseCallSettings = await client.MutateAdGroupCriterionLabelsAsync(request.CustomerId, request.Operations, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); MutateAdGroupCriterionLabelsResponse responseCancellationToken = await client.MutateAdGroupCriterionLabelsAsync(request.CustomerId, request.Operations, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Threading; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.ClientStack.LindenUDP; using OpenSim.Region.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Hypergrid; using OpenMetaverse; using OpenMetaverse.Packets; using log4net; using Nini.Config; using Mono.Addins; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; namespace OpenSim.Region.CoreModules.Framework.UserManagement { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "UserManagementModule")] public class UserManagementModule : ISharedRegionModule, IUserManagement, IPeople { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); protected bool m_Enabled; protected List<Scene> m_Scenes = new List<Scene>(); protected IServiceThrottleModule m_ServiceThrottle; // The cache protected Dictionary<UUID, UserData> m_UserCache = new Dictionary<UUID, UserData>(); protected bool m_DisplayChangingHomeURI = false; #region ISharedRegionModule public void Initialise(IConfigSource config) { string umanmod = config.Configs["Modules"].GetString("UserManagementModule", Name); if (umanmod == Name) { m_Enabled = true; Init(); m_log.DebugFormat("[USER MANAGEMENT MODULE]: {0} is enabled", Name); } if(!m_Enabled) { return; } IConfig userManagementConfig = config.Configs["UserManagement"]; if (userManagementConfig == null) return; m_DisplayChangingHomeURI = userManagementConfig.GetBoolean("DisplayChangingHomeURI", false); } public bool IsSharedModule { get { return true; } } public virtual string Name { get { return "BasicUserManagementModule"; } } public Type ReplaceableInterface { get { return null; } } public void AddRegion(Scene scene) { if (m_Enabled) { lock (m_Scenes) { m_Scenes.Add(scene); } scene.RegisterModuleInterface<IUserManagement>(this); scene.RegisterModuleInterface<IPeople>(this); scene.EventManager.OnNewClient += new EventManager.OnNewClientDelegate(EventManager_OnNewClient); scene.EventManager.OnPrimsLoaded += new EventManager.PrimsLoaded(EventManager_OnPrimsLoaded); } } public void RemoveRegion(Scene scene) { if (m_Enabled) { scene.UnregisterModuleInterface<IUserManagement>(this); lock (m_Scenes) { m_Scenes.Remove(scene); } } } public void RegionLoaded(Scene s) { if (m_Enabled && m_ServiceThrottle == null) m_ServiceThrottle = s.RequestModuleInterface<IServiceThrottleModule>(); } public void PostInitialise() { } public void Close() { lock (m_Scenes) { m_Scenes.Clear(); } lock (m_UserCache) m_UserCache.Clear(); } #endregion ISharedRegionModule #region Event Handlers void EventManager_OnPrimsLoaded(Scene s) { // let's sniff all the user names referenced by objects in the scene m_log.DebugFormat("[USER MANAGEMENT MODULE]: Caching creators' data from {0} ({1} objects)...", s.RegionInfo.RegionName, s.GetEntities().Length); s.ForEachSOG(delegate(SceneObjectGroup sog) { CacheCreators(sog); }); } void EventManager_OnNewClient(IClientAPI client) { client.OnConnectionClosed += new Action<IClientAPI>(HandleConnectionClosed); client.OnNameFromUUIDRequest += new UUIDNameRequest(HandleUUIDNameRequest); client.OnAvatarPickerRequest += new AvatarPickerRequest(HandleAvatarPickerRequest); } void HandleConnectionClosed(IClientAPI client) { client.OnNameFromUUIDRequest -= new UUIDNameRequest(HandleUUIDNameRequest); client.OnAvatarPickerRequest -= new AvatarPickerRequest(HandleAvatarPickerRequest); } void HandleUUIDNameRequest(UUID uuid, IClientAPI client) { // m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: Handling request for name binding of UUID {0} from {1}", // uuid, remote_client.Name); if (m_Scenes[0].LibraryService != null && (m_Scenes[0].LibraryService.LibraryRootFolder.Owner == uuid)) { client.SendNameReply(uuid, "Mr", "OpenSim"); } else { UserData user; /* bypass that continuation here when entry is already available */ lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out user)) { if (!user.IsUnknownUser && user.HasGridUserTried) { client.SendNameReply(uuid, user.FirstName, user.LastName); return; } } } // Not found in cache, queue continuation m_ServiceThrottle.Enqueue("name", uuid.ToString(), delegate { //m_log.DebugFormat("[YYY]: Name request {0}", uuid); // As least upto September 2013, clients permanently cache UUID -> Name bindings. Some clients // appear to clear this when the user asks it to clear the cache, but others may not. // // So to avoid clients // (particularly Hypergrid clients) permanently binding "Unknown User" to a given UUID, we will // instead drop the request entirely. if (GetUser(uuid, out user)) { client.SendNameReply(uuid, user.FirstName, user.LastName); } // else // m_log.DebugFormat( // "[USER MANAGEMENT MODULE]: No bound name for {0} found, ignoring request from {1}", // uuid, client.Name); }); } } public void HandleAvatarPickerRequest(IClientAPI client, UUID avatarID, UUID RequestID, string query) { //EventManager.TriggerAvatarPickerRequest(); m_log.DebugFormat("[USER MANAGEMENT MODULE]: HandleAvatarPickerRequest for {0}", query); List<UserData> users = GetUserData(query, 500, 1); AvatarPickerReplyPacket replyPacket = (AvatarPickerReplyPacket)PacketPool.Instance.GetPacket(PacketType.AvatarPickerReply); // TODO: don't create new blocks if recycling an old packet AvatarPickerReplyPacket.DataBlock[] searchData = new AvatarPickerReplyPacket.DataBlock[users.Count]; AvatarPickerReplyPacket.AgentDataBlock agentData = new AvatarPickerReplyPacket.AgentDataBlock(); agentData.AgentID = avatarID; agentData.QueryID = RequestID; replyPacket.AgentData = agentData; //byte[] bytes = new byte[AvatarResponses.Count*32]; int i = 0; foreach (UserData item in users) { UUID translatedIDtem = item.Id; searchData[i] = new AvatarPickerReplyPacket.DataBlock(); searchData[i].AvatarID = translatedIDtem; searchData[i].FirstName = Utils.StringToBytes((string)item.FirstName); searchData[i].LastName = Utils.StringToBytes((string)item.LastName); i++; } if (users.Count == 0) { searchData = new AvatarPickerReplyPacket.DataBlock[0]; } replyPacket.Data = searchData; AvatarPickerReplyAgentDataArgs agent_data = new AvatarPickerReplyAgentDataArgs(); agent_data.AgentID = replyPacket.AgentData.AgentID; agent_data.QueryID = replyPacket.AgentData.QueryID; List<AvatarPickerReplyDataArgs> data_args = new List<AvatarPickerReplyDataArgs>(); for (i = 0; i < replyPacket.Data.Length; i++) { AvatarPickerReplyDataArgs data_arg = new AvatarPickerReplyDataArgs(); data_arg.AvatarID = replyPacket.Data[i].AvatarID; data_arg.FirstName = replyPacket.Data[i].FirstName; data_arg.LastName = replyPacket.Data[i].LastName; data_args.Add(data_arg); } client.SendAvatarPickerReply(agent_data, data_args); } protected virtual void AddAdditionalUsers(string query, List<UserData> users) { } #endregion Event Handlers #region IPeople public List<UserData> GetUserData(string query, int page_size, int page_number) { // search the user accounts service List<UserAccount> accs = m_Scenes[0].UserAccountService.GetUserAccounts(m_Scenes[0].RegionInfo.ScopeID, query); List<UserData> users = new List<UserData>(); if (accs != null) { foreach (UserAccount acc in accs) { UserData ud = new UserData(); ud.FirstName = acc.FirstName; ud.LastName = acc.LastName; ud.Id = acc.PrincipalID; ud.HasGridUserTried = true; ud.IsUnknownUser = false; users.Add(ud); } } // search the local cache foreach (UserData data in m_UserCache.Values) { if (data.Id != UUID.Zero && !data.IsUnknownUser && users.Find(delegate(UserData d) { return d.Id == data.Id; }) == null && (data.FirstName.ToLower().StartsWith(query.ToLower()) || data.LastName.ToLower().StartsWith(query.ToLower()))) users.Add(data); } AddAdditionalUsers(query, users); return users; } #endregion IPeople private void CacheCreators(SceneObjectGroup sog) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: processing {0} {1}; {2}", sog.RootPart.Name, sog.RootPart.CreatorData, sog.RootPart.CreatorIdentification); AddUser(sog.RootPart.CreatorID, sog.RootPart.CreatorData); foreach (SceneObjectPart sop in sog.Parts) { AddUser(sop.CreatorID, sop.CreatorData); foreach (TaskInventoryItem item in sop.TaskInventory.Values) AddUser(item.CreatorID, item.CreatorData); } } /// <summary> /// /// </summary> /// <param name="uuid"></param> /// <param name="names">Caller please provide a properly instantiated array for names, string[2]</param> /// <returns></returns> private bool TryGetUserNames(UUID uuid, string[] names) { if (names == null) names = new string[2]; if (TryGetUserNamesFromCache(uuid, names)) return true; if (TryGetUserNamesFromServices(uuid, names)) return true; return false; } private bool TryGetUserNamesFromCache(UUID uuid, string[] names) { lock (m_UserCache) { if (m_UserCache.ContainsKey(uuid)) { names[0] = m_UserCache[uuid].FirstName; names[1] = m_UserCache[uuid].LastName; return true; } } return false; } /// <summary> /// Try to get the names bound to the given uuid, from the services. /// </summary> /// <returns>True if the name was found, false if not.</returns> /// <param name='uuid'></param> /// <param name='names'>The array of names if found. If not found, then names[0] = "Unknown" and names[1] = "User"</param> private bool TryGetUserNamesFromServices(UUID uuid, string[] names) { UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, uuid); if (account != null) { names[0] = account.FirstName; names[1] = account.LastName; UserData user = new UserData(); user.FirstName = account.FirstName; user.LastName = account.LastName; lock (m_UserCache) m_UserCache[uuid] = user; return true; } else { // Let's try the GridUser service GridUserInfo uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString()); if (uInfo != null) { string url, first, last, tmp; UUID u; if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp)) { AddUser(uuid, first, last, url); if (m_UserCache.ContainsKey(uuid)) { names[0] = m_UserCache[uuid].FirstName; names[1] = m_UserCache[uuid].LastName; return true; } } else m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID); } // else // { // m_log.DebugFormat("[USER MANAGEMENT MODULE]: No grid user found for {0}", uuid); // } names[0] = "Unknown"; names[1] = "UserUMMTGUN9"; return false; } } #region IUserManagement public UUID GetUserIdByName(string name) { string[] parts = name.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 2) throw new Exception("Name must have 2 components"); return GetUserIdByName(parts[0], parts[1]); } public UUID GetUserIdByName(string firstName, string lastName) { // TODO: Optimize for reverse lookup if this gets used by non-console commands. lock (m_UserCache) { foreach (UserData user in m_UserCache.Values) { if (user.FirstName == firstName && user.LastName == lastName) return user.Id; } } UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(UUID.Zero, firstName, lastName); if (account != null) return account.PrincipalID; return UUID.Zero; } public string GetUserName(UUID uuid) { UserData user; GetUser(uuid, out user); return user.FirstName + " " + user.LastName; } public string GetUserHomeURL(UUID userID) { UserData user; if(GetUser(userID, out user)) { return user.HomeURL; } return string.Empty; } public string GetUserServerURL(UUID userID, string serverType) { UserData userdata; if(!GetUser(userID, out userdata)) { return string.Empty; } if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null) { return userdata.ServerURLs[serverType].ToString(); } if (!string.IsNullOrEmpty(userdata.HomeURL)) { // m_log.DebugFormat("[USER MANAGEMENT MODULE]: Requested url type {0} for {1}", serverType, userID); UserAgentServiceConnector uConn = new UserAgentServiceConnector(userdata.HomeURL); try { userdata.ServerURLs = uConn.GetServerURLs(userID); } catch(System.Net.WebException e) { m_log.DebugFormat("[USER MANAGEMENT MODULE]: GetServerURLs call failed {0}", e.Message); userdata.ServerURLs = new Dictionary<string, object>(); } catch (Exception e) { m_log.Debug("[USER MANAGEMENT MODULE]: GetServerURLs call failed ", e); userdata.ServerURLs = new Dictionary<string, object>(); } if (userdata.ServerURLs != null && userdata.ServerURLs.ContainsKey(serverType) && userdata.ServerURLs[serverType] != null) return userdata.ServerURLs[serverType].ToString(); } return string.Empty; } public string GetUserUUI(UUID userID) { string uui; GetUserUUI(userID, out uui); return uui; } public bool GetUserUUI(UUID userID, out string uui) { UserData ud; bool result = GetUser(userID, out ud); if (ud != null) { string homeURL = ud.HomeURL; string first = ud.FirstName, last = ud.LastName; if (ud.LastName.StartsWith("@")) { string[] parts = ud.FirstName.Split('.'); if (parts.Length >= 2) { first = parts[0]; last = parts[1]; } uui = userID + ";" + homeURL + ";" + first + " " + last; } } uui = userID.ToString(); return result; } #region Cache Management public bool GetUser(UUID uuid, out UserData userdata) { lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out userdata)) { if (userdata.HasGridUserTried) { return true; } } else { userdata = new UserData(); userdata.HasGridUserTried = false; userdata.Id = uuid; userdata.FirstName = "Unknown"; userdata.LastName = "UserUMMAU42"; userdata.HomeURL = string.Empty; userdata.IsUnknownUser = true; userdata.HasGridUserTried = false; } } /* BEGIN: do not wrap this code in any lock here * There are HTTP calls in here. */ if (!userdata.HasGridUserTried) { /* rewrite here */ UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid); if (account != null) { userdata.FirstName = account.FirstName; userdata.LastName = account.LastName; userdata.HomeURL = string.Empty; userdata.IsUnknownUser = false; userdata.HasGridUserTried = true; } } if (!userdata.HasGridUserTried) { GridUserInfo uInfo = null; if (null != m_Scenes[0].GridUserService) { uInfo = m_Scenes[0].GridUserService.GetGridUserInfo(uuid.ToString()); } if (uInfo != null) { string url, first, last, tmp; UUID u; if(uInfo.UserID.Length <= 36) { /* not a UUI */ } else if (Util.ParseUniversalUserIdentifier(uInfo.UserID, out u, out url, out first, out last, out tmp)) { if (url != string.Empty) { userdata.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", "."); userdata.HomeURL = url; try { userdata.LastName = "@" + new Uri(url).Authority; userdata.IsUnknownUser = false; } catch { userdata.LastName = "@unknown"; } userdata.HasGridUserTried = true; } } else m_log.DebugFormat("[USER MANAGEMENT MODULE]: Unable to parse UUI {0}", uInfo.UserID); } } /* END: do not wrap this code in any lock here */ lock (m_UserCache) { m_UserCache[uuid] = userdata; } return !userdata.IsUnknownUser; } public void AddUser(UUID uuid, string first, string last) { lock(m_UserCache) { if(!m_UserCache.ContainsKey(uuid)) { UserData user = new UserData(); user.Id = uuid; user.FirstName = first; user.LastName = last; user.IsUnknownUser = false; user.HasGridUserTried = false; m_UserCache.Add(uuid, user); } } } public void AddUser(UUID uuid, string first, string last, string homeURL) { //m_log.DebugFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, first {1}, last {2}, url {3}", uuid, first, last, homeURL); UserData oldUser; lock (m_UserCache) { if (m_UserCache.TryGetValue(uuid, out oldUser)) { if (!oldUser.IsUnknownUser) { if (homeURL != oldUser.HomeURL && m_DisplayChangingHomeURI) { m_log.DebugFormat("[USER MANAGEMENT MODULE]: Different HomeURI for {0} {1} ({2}): {3} and {4}", first, last, uuid.ToString(), homeURL, oldUser.HomeURL); } /* no update needed */ return; } } else if(!m_UserCache.ContainsKey(uuid)) { oldUser = new UserData(); oldUser.HasGridUserTried = false; oldUser.IsUnknownUser = false; if (homeURL != string.Empty) { oldUser.FirstName = first.Replace(" ", ".") + "." + last.Replace(" ", "."); try { oldUser.LastName = "@" + new Uri(homeURL).Authority; oldUser.IsUnknownUser = false; } catch { oldUser.LastName = "@unknown"; } } else { oldUser.FirstName = first; oldUser.LastName = last; } oldUser.HomeURL = homeURL; oldUser.Id = uuid; m_UserCache.Add(uuid, oldUser); } } } public void AddUser(UUID id, string creatorData) { // m_log.InfoFormat("[USER MANAGEMENT MODULE]: Adding user with id {0}, creatorData {1}", id, creatorData); if(string.IsNullOrEmpty(creatorData)) { AddUser(id, string.Empty, string.Empty, string.Empty); } else { string homeURL; string firstname = string.Empty; string lastname = string.Empty; //creatorData = <endpoint>;<name> string[] parts = creatorData.Split(';'); if(parts.Length > 1) { string[] nameparts = parts[1].Split(' '); firstname = nameparts[0]; for(int xi = 1; xi < nameparts.Length; ++xi) { if(xi != 1) { lastname += " "; } lastname += nameparts[xi]; } } else { firstname = "Unknown"; lastname = "UserUMMAU5"; } if (parts.Length >= 1) { homeURL = parts[0]; if(Uri.IsWellFormedUriString(homeURL, UriKind.Absolute)) { AddUser(id, firstname, lastname, homeURL); } else { m_log.DebugFormat("[SCENE]: Unable to parse Uri {0} for CreatorID {1}", parts[0], creatorData); lock (m_UserCache) { if(!m_UserCache.ContainsKey(id)) { UserData newUser = new UserData(); newUser.Id = id; newUser.FirstName = firstname + "." + lastname.Replace(' ', '.'); newUser.LastName = "@unknown"; newUser.HomeURL = string.Empty; newUser.HasGridUserTried = false; newUser.IsUnknownUser = true; /* we mark those users as Unknown user so a re-retrieve may be activated */ m_UserCache.Add(id, newUser); } } } } else { lock(m_UserCache) { if(!m_UserCache.ContainsKey(id)) { UserData newUser = new UserData(); newUser.Id = id; newUser.FirstName = "Unknown"; newUser.LastName = "UserUMMAU4"; newUser.HomeURL = string.Empty; newUser.IsUnknownUser = true; newUser.HasGridUserTried = false; m_UserCache.Add(id, newUser); } } } } } #endregion public bool IsLocalGridUser(UUID uuid) { UserAccount account = m_Scenes[0].UserAccountService.GetUserAccount(m_Scenes[0].RegionInfo.ScopeID, uuid); if (account == null || (account != null && !account.LocalToGrid)) return false; return true; } #endregion IUserManagement protected void Init() { AddUser(UUID.Zero, "Unknown", "User"); RegisterConsoleCmds(); } protected void RegisterConsoleCmds() { MainConsole.Instance.Commands.AddCommand("Users", true, "show name", "show name <uuid>", "Show the bindings between a single user UUID and a user name", String.Empty, HandleShowUser); MainConsole.Instance.Commands.AddCommand("Users", true, "show names", "show names", "Show the bindings between user UUIDs and user names", String.Empty, HandleShowUsers); MainConsole.Instance.Commands.AddCommand("Users", true, "reset user cache", "reset user cache", "reset user cache to allow changed settings to be applied", String.Empty, HandleResetUserCache); } private void HandleResetUserCache(string module, string[] cmd) { lock(m_UserCache) { m_UserCache.Clear(); } } private void HandleShowUser(string module, string[] cmd) { if (cmd.Length < 3) { MainConsole.Instance.OutputFormat("Usage: show name <uuid>"); return; } UUID userId; if (!ConsoleUtil.TryParseConsoleUuid(MainConsole.Instance, cmd[2], out userId)) return; UserData ud; if(!GetUser(userId, out ud)) { MainConsole.Instance.OutputFormat("No name known for user with id {0}", userId); return; } ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("UUID", 36); cdt.AddColumn("Name", 30); cdt.AddColumn("HomeURL", 40); cdt.AddRow(userId, string.Format("{0} {1}", ud.FirstName, ud.LastName), ud.HomeURL); MainConsole.Instance.Output(cdt.ToString()); } private void HandleShowUsers(string module, string[] cmd) { ConsoleDisplayTable cdt = new ConsoleDisplayTable(); cdt.AddColumn("UUID", 36); cdt.AddColumn("Name", 30); cdt.AddColumn("HomeURL", 40); cdt.AddColumn("Checked", 10); Dictionary<UUID, UserData> copyDict; lock(m_UserCache) { copyDict = new Dictionary<UUID, UserData>(m_UserCache); } foreach(KeyValuePair<UUID, UserData> kvp in copyDict) { cdt.AddRow(kvp.Key, string.Format("{0} {1}", kvp.Value.FirstName, kvp.Value.LastName), kvp.Value.HomeURL, kvp.Value.HasGridUserTried ? "yes" : "no"); } MainConsole.Instance.Output(cdt.ToString()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using UnityEngine.Experimental.VFX; namespace UnityEditor.VFX { [VFXGizmo(typeof(Cone))] class VFXConeGizmo : VFXSpaceableGizmo<Cone> { IProperty<Vector3> m_CenterProperty; IProperty<float> m_Radius0Property; IProperty<float> m_Radius1Property; IProperty<float> m_HeightProperty; public override void RegisterEditableMembers(IContext context) { m_CenterProperty = context.RegisterProperty<Vector3>("center"); m_Radius0Property = context.RegisterProperty<float>("radius0"); m_Radius1Property = context.RegisterProperty<float>("radius1"); m_HeightProperty = context.RegisterProperty<float>("height"); } public static readonly Vector3[] radiusDirections = new Vector3[] { Vector3.left, Vector3.up, Vector3.right, Vector3.down }; float radius1Screen; float radius0Screen; bool m_Dragging; public struct Extremities { public void Build(Cone cone) { topCap = cone.height * Vector3.up; bottomCap = Vector3.zero; if (extremities == null) extremities = new List<Vector3>(8); extremities.Clear(); extremities.Add(topCap + Vector3.forward * cone.radius1); extremities.Add(topCap - Vector3.forward * cone.radius1); extremities.Add(topCap + Vector3.left * cone.radius1); extremities.Add(topCap - Vector3.left * cone.radius1); extremities.Add(bottomCap + Vector3.forward * cone.radius0); extremities.Add(bottomCap - Vector3.forward * cone.radius0); extremities.Add(bottomCap + Vector3.left * cone.radius0); extremities.Add(bottomCap - Vector3.left * cone.radius0); visibleCount = 4; } public void Build(Cone cone, float degArc) { topCap = cone.height * Vector3.up; bottomCap = Vector3.zero; int count = 4; visibleCount = Mathf.CeilToInt(degArc / 90); if (visibleCount <= 0) { visibleCount = 1; } if (extremities == null) extremities = new List<Vector3>(8); extremities.Clear(); extremities.Add(topCap + Vector3.forward * cone.radius1); if (count > 1) { extremities.Add(topCap - Vector3.left * cone.radius1); if (count > 2) { extremities.Add(topCap - Vector3.forward * cone.radius1); if (count > 3) { extremities.Add(topCap + Vector3.left * cone.radius1); } } } extremities.Add(bottomCap + Vector3.forward * cone.radius0); if (count > 1) { extremities.Add(bottomCap - Vector3.left * cone.radius0); if (count > 2) { extremities.Add(bottomCap - Vector3.forward * cone.radius0); if (count > 3) { extremities.Add(bottomCap + Vector3.left * cone.radius0); } } } } public Vector3 topCap; public Vector3 bottomCap; public List<Vector3> extremities; public int visibleCount; } public static void DrawCone(Cone cone, VFXGizmo gizmo, ref Extremities extremities, IProperty<Vector3> centerProperty, IProperty<float> radius0Property, IProperty<float> radius1Property, IProperty<float> heightProperty, float radius0Screen, float radius1Screen) { gizmo.PositionGizmo(cone.center, centerProperty, true); using (new Handles.DrawingScope(Handles.matrix * Matrix4x4.Translate(cone.center))) { if (radius0Screen > 2 && radius0Property.isEditable) { for (int i = extremities.extremities.Count / 2; i < extremities.extremities.Count; ++i) { EditorGUI.BeginChangeCheck(); Vector3 pos = extremities.extremities[i]; Vector3 result = Handles.Slider(pos, pos - extremities.bottomCap, (i - extremities.extremities.Count / 2) < extremities.visibleCount ? handleSize * HandleUtility.GetHandleSize(pos) : 0, Handles.CubeHandleCap, 0); if (EditorGUI.EndChangeCheck()) { radius0Property.SetValue(result.magnitude); } } } if (radius1Screen > 2 && radius1Property.isEditable) { for (int i = 0; i < extremities.extremities.Count / 2; ++i) { EditorGUI.BeginChangeCheck(); Vector3 pos = extremities.extremities[i]; Vector3 dir = pos - extremities.topCap; Vector3 result = Handles.Slider(pos, dir, i < extremities.visibleCount ? handleSize * HandleUtility.GetHandleSize(pos) : 0, Handles.CubeHandleCap, 0); if (EditorGUI.EndChangeCheck()) { radius1Property.SetValue((result - extremities.topCap).magnitude); } } } if (heightProperty.isEditable) { EditorGUI.BeginChangeCheck(); Vector3 result = Handles.Slider(extremities.topCap, Vector3.up, handleSize * HandleUtility.GetHandleSize(extremities.topCap), Handles.CubeHandleCap, 0); if (EditorGUI.EndChangeCheck()) { heightProperty.SetValue(result.magnitude); } } } } Extremities extremities; public override void OnDrawSpacedGizmo(Cone cone) { extremities.Build(cone); if (Event.current != null && Event.current.type == EventType.MouseDown) { m_Dragging = true; } if (Event.current != null && Event.current.type == EventType.MouseUp) { m_Dragging = false; } if (!m_Dragging) { radius1Screen = (HandleUtility.WorldToGUIPoint(extremities.topCap) - HandleUtility.WorldToGUIPoint(extremities.topCap + Vector3.forward * cone.radius1)).magnitude; radius0Screen = (HandleUtility.WorldToGUIPoint(extremities.bottomCap) - HandleUtility.WorldToGUIPoint(extremities.bottomCap + Vector3.forward * cone.radius0)).magnitude; } using (new Handles.DrawingScope(Handles.matrix * Matrix4x4.Translate(cone.center))) { Handles.DrawWireDisc(extremities.topCap, Vector3.up, cone.radius1); Handles.DrawWireDisc(extremities.bottomCap, Vector3.up, cone.radius0); for (int i = 0; i < extremities.extremities.Count / 2; ++i) { Handles.DrawLine(extremities.extremities[i], extremities.extremities[i + extremities.extremities.Count / 2]); } } DrawCone(cone, this, ref extremities, m_CenterProperty, m_Radius0Property, m_Radius1Property, m_HeightProperty, radius0Screen, radius1Screen); } public override Bounds OnGetSpacedGizmoBounds(Cone value) { return new Bounds(value.center, new Vector3(Mathf.Max(value.radius0, value.radius1), Mathf.Max(value.radius0, value.radius1), value.height)); //TODO take orientation in account } } [VFXGizmo(typeof(ArcCone))] class VFXArcConeGizmo : VFXSpaceableGizmo<ArcCone> { IProperty<Vector3> m_CenterProperty; IProperty<float> m_Radius0Property; IProperty<float> m_Radius1Property; IProperty<float> m_HeightProperty; IProperty<float> m_ArcProperty; public override void RegisterEditableMembers(IContext context) { m_CenterProperty = context.RegisterProperty<Vector3>("center"); m_Radius0Property = context.RegisterProperty<float>("radius0"); m_Radius1Property = context.RegisterProperty<float>("radius1"); m_HeightProperty = context.RegisterProperty<float>("height"); m_ArcProperty = context.RegisterProperty<float>("arc"); } public static readonly Vector3[] radiusDirections = new Vector3[] { Vector3.left, Vector3.up, Vector3.right, Vector3.down }; VFXConeGizmo.Extremities extremities; bool m_Dragging; float radius1Screen; float radius0Screen; public override void OnDrawSpacedGizmo(ArcCone arcCone) { float arc = arcCone.arc * Mathf.Rad2Deg; Cone cone = new Cone { center = arcCone.center, radius0 = arcCone.radius0, radius1 = arcCone.radius1, height = arcCone.height }; extremities.Build(cone, arc); Vector3 arcDirection = Quaternion.AngleAxis(arc, Vector3.up) * Vector3.forward; if (Event.current != null && Event.current.type == EventType.MouseDown) { m_Dragging = true; } if (Event.current != null && Event.current.type == EventType.MouseUp) { m_Dragging = false; } if (!m_Dragging) { radius1Screen = (HandleUtility.WorldToGUIPoint(extremities.topCap) - HandleUtility.WorldToGUIPoint(extremities.topCap + Vector3.forward * cone.radius1)).magnitude; radius0Screen = (HandleUtility.WorldToGUIPoint(extremities.bottomCap) - HandleUtility.WorldToGUIPoint(extremities.bottomCap + Vector3.forward * cone.radius0)).magnitude; } using (new Handles.DrawingScope(Handles.matrix * Matrix4x4.Translate(arcCone.center))) { if (radius1Screen > 2) Handles.DrawWireArc(extremities.topCap, Vector3.up, Vector3.forward, arc, arcCone.radius1); if (radius0Screen > 2) Handles.DrawWireArc(extremities.bottomCap, Vector3.up, Vector3.forward, arc, arcCone.radius0); for (int i = 0; i < extremities.extremities.Count / 2 && i < extremities.visibleCount; ++i) { Handles.DrawLine(extremities.extremities[i], extremities.extremities[i + extremities.extremities.Count / 2]); } Handles.DrawLine(extremities.topCap, extremities.extremities[0]); Handles.DrawLine(extremities.bottomCap, extremities.extremities[extremities.extremities.Count / 2]); Handles.DrawLine(extremities.topCap, extremities.topCap + arcDirection * arcCone.radius1); Handles.DrawLine(extremities.bottomCap, arcDirection * arcCone.radius0); Handles.DrawLine(arcDirection * arcCone.radius0, extremities.topCap + arcDirection * arcCone.radius1); float radius = arcCone.radius0 > arcCone.radius1 ? arcCone.radius0 : arcCone.radius1; Vector3 center = arcCone.radius0 > arcCone.radius1 ? Vector3.zero : extremities.topCap; if (radius != 0) ArcGizmo(center, radius, arc, m_ArcProperty, Quaternion.identity, true); } VFXConeGizmo.DrawCone(cone, this, ref extremities, m_CenterProperty, m_Radius0Property, m_Radius1Property, m_HeightProperty, radius0Screen, radius1Screen); } public override Bounds OnGetSpacedGizmoBounds(ArcCone value) { return new Bounds(value.center, new Vector3(Mathf.Max(value.radius0, value.radius1), Mathf.Max(value.radius0, value.radius1), value.height)); //TODO take orientation in account } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.ServiceModel.Syndication; using System.Xml; using System.IO; using Xunit; using System.Linq; namespace System.ServiceModel.Syndication.Tests { public static partial class BasicScenarioTests { [Fact] public static void SyndicationFeed_CreateNewFeed() { string filePath = Path.GetTempFileName(); try { // *** SETUP *** \\ var sf = new SyndicationFeed("First feed on .net core ever!!", "This is the first feed on .net core ever!", new Uri("https://github.com/dotnet/wcf")); Assert.True(sf != null); using (XmlWriter xmlw = XmlWriter.Create(filePath)) { var rssf = new Rss20FeedFormatter(sf); // *** EXECUTE *** \\ rssf.WriteTo(xmlw); } // *** VALIDATE *** \\ Assert.True(File.Exists(filePath)); } finally { // *** CLEANUP *** \\ File.Delete(filePath); } } [Fact] public static void SyndicationFeed_Load_Write_RSS_Feed() { string path = Path.GetTempFileName(); try { // *** SETUP *** \\\ SyndicationFeed sf; using (XmlReader xmlr = XmlReader.Create("TestFeeds/SimpleRssFeed.xml")) { sf = SyndicationFeed.Load(xmlr); Assert.True(sf != null); } // *** EXECUTE *** \\ //Write the same feed that was read. using (XmlWriter xmlw = XmlWriter.Create(path)) { var rss20FeedFormatter = new Rss20FeedFormatter(sf); rss20FeedFormatter.WriteTo(xmlw); } // *** VALIDATE *** \\ Assert.True(File.Exists(path)); } finally { // *** CLEANUP *** \\ File.Delete(path); } } [Fact] public static void SyndicationFeed_Load_Write_RSS_Feed_() { string path = Path.GetTempFileName(); try { // *** SETUP *** \\\ SyndicationFeed sf; using (XmlReader xmlr = XmlReader.Create("TestFeeds/rssSpecExample.xml")) { sf = SyndicationFeed.Load(xmlr); Assert.True(sf != null); } // *** EXECUTE *** \\ //Write the same feed that was read. XmlWriterSettings settingsWriter = new XmlWriterSettings(); using (XmlWriter xmlw = XmlWriter.Create(path, settingsWriter)) { var rss20FeedFormatter = new Rss20FeedFormatter(sf); rss20FeedFormatter.WriteTo(xmlw); } // *** VALIDATE *** \\ Assert.True(File.Exists(path)); } finally { // *** CLEANUP *** \\ File.Delete(path); } } [Fact] public static void SyndicationFeed_Load_Write_Atom_Feed() { string path = Path.GetTempFileName(); try { // *** SETUP *** \\\ SyndicationFeed sf; using (XmlReader xmlr = XmlReader.Create("TestFeeds/SimpleAtomFeed.xml")) { sf = SyndicationFeed.Load(xmlr); Assert.True(sf != null); } // *** EXECUTE *** \\ //Write the same feed that was read. using (XmlWriter xmlw = XmlWriter.Create(path)) { var atom10FeedFormatter = new Atom10FeedFormatter(sf); atom10FeedFormatter.WriteTo(xmlw); } // *** VALIDATE *** \\ Assert.True(File.Exists(path)); } finally { // *** CLEANUP *** \\ File.Delete(path); } } [Fact] public static void SyndicationFeed_Load_Write_Atom_Feed_() { string path = Path.GetTempFileName(); try { // *** SETUP *** \\\ SyndicationFeed sf; using (XmlReader xmlr = XmlReader.Create("TestFeeds/atom_spec_example.xml")) { sf = SyndicationFeed.Load(xmlr); Assert.True(sf != null); } // *** EXECUTE *** \\ //Write the same feed that was read. using (XmlWriter xmlw = XmlWriter.Create(path)) { var atom10FeedFormatter = new Atom10FeedFormatter(sf); atom10FeedFormatter.WriteTo(xmlw); } // *** VALIDATE *** \\ Assert.True(File.Exists(path)); } finally { // *** CLEANUP *** \\ File.Delete(path); } } [Fact] public static void SyndicationFeed_Write_RSS_Atom() { string RssPath = Path.GetTempFileName(); string AtomPath = Path.GetTempFileName(); try { // *** SETUP *** \\ SyndicationFeed feed = new SyndicationFeed("Contoso News", "<div>Most recent news from Contoso</div>", new Uri("http://www.Contoso.com/news"), "123FeedID", DateTime.Now); //Add an author SyndicationPerson author = new SyndicationPerson("jerry@Contoso.com"); feed.Authors.Add(author); //Create item SyndicationItem item1 = new SyndicationItem("SyndicationFeed released for .net Core", "A lot of text describing the release of .net core feature", new Uri("http://Contoso.com/news/path")); //Add item to feed List<SyndicationItem> feedList = new List<SyndicationItem> { item1 }; feed.Items = feedList; feed.ElementExtensions.Add("CustomElement", "", "asd"); //add an image feed.ImageUrl = new Uri("http://2.bp.blogspot.com/-NA5Jb-64eUg/URx8CSdcj_I/AAAAAAAAAUo/eCx0irI0rq0/s1600/bg_Contoso_logo3-20120824073001907469-620x349.jpg"); feed.BaseUri = new Uri("http://mypage.com"); // Write to XML > rss using (XmlWriter xmlwRss = XmlWriter.Create(RssPath)) { Rss20FeedFormatter rssff = new Rss20FeedFormatter(feed); rssff.WriteTo(xmlwRss); } // Write to XML > atom using (XmlWriter xmlwAtom = XmlWriter.Create(AtomPath)) { Atom10FeedFormatter atomf = new Atom10FeedFormatter(feed); atomf.WriteTo(xmlwAtom); } // *** ASSERT *** \\ Assert.True(File.Exists(RssPath)); Assert.True(File.Exists(AtomPath)); } finally { // *** CLEANUP *** \\ File.Delete(RssPath); File.Delete(AtomPath); } } [Fact] public static void SyndicationFeed_Load_Rss() { XmlReaderSettings setting = new XmlReaderSettings(); using (XmlReader reader = XmlReader.Create("TestFeeds/rssSpecExample.xml", setting)) { SyndicationFeed rss = SyndicationFeed.Load(reader); Assert.True(rss.Items != null); } } [Fact] public static void SyndicationFeed_Load_Atom() { XmlReaderSettings setting = new XmlReaderSettings(); using (XmlReader reader = XmlReader.Create("TestFeeds/atom_spec_example.xml", setting)) { SyndicationFeed atom = SyndicationFeed.Load(reader); Assert.True(atom.Items != null); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Disjoint items not supported on NetFX")] public static void SyndicationFeed_Rss_TestDisjointItems() { using (XmlReader reader = XmlReader.Create("TestFeeds/RssDisjointItems.xml")) { // *** EXECUTE *** \\ SyndicationFeed sf = SyndicationFeed.Load(reader); // *** ASSERT *** \\ int count = 0; foreach (SyndicationItem item in sf.Items) { count++; } Assert.True(count == 2); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Disjoint items not supported on NetFX")] public static void SyndicationFeed_Atom_TestDisjointItems() { using (XmlReader reader = XmlReader.Create("TestFeeds/AtomDisjointItems.xml")) { // *** EXECUTE *** \\ SyndicationFeed sf = SyndicationFeed.Load(reader); // *** ASSERT *** \\ int count = 0; foreach (SyndicationItem item in sf.Items) { count++; } Assert.True(count == 2); } } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Deferred date exception throwing not implemented on NetFX")] public static void SyndicationFeed_Rss_WrongDateFormat() { // *** SETUP *** \\ XmlReader reader = XmlReader.Create("TestFeeds/rssSpecExampleWrongDateFormat.xml"); // *** EXECUTE *** \\ SyndicationFeed res = SyndicationFeed.Load(reader); // *** ASSERT *** \\ Assert.True(res != null, "res was null."); Assert.Equal(new DateTimeOffset(2016, 8, 23, 16, 8, 0, new TimeSpan(-4, 0, 0)), res.LastUpdatedTime); Assert.True(res.Items != null, "res.Items was null."); Assert.True(res.Items.Count() == 4, $"res.Items.Count() was not as expected. Expected: 4; Actual: {res.Items.Count()}"); SyndicationItem[] items = res.Items.ToArray(); DateTimeOffset dateTimeOffset; Assert.Throws<XmlException>(() => dateTimeOffset = items[2].PublishDate); } [Fact] public static void AtomEntryPositiveTest() { string file = "TestFeeds/brief-entry-noerror.xml"; ReadWriteSyndicationItem(file, (itemObject) => new Atom10ItemFormatter(itemObject)); } [Fact] public static void AtomEntryPositiveTest_write() { string file = "TestFeeds/AtomEntryTest.xml"; string serializeFilePath = Path.GetTempFileName(); bool toDeletedFile = true; SyndicationItem item = new SyndicationItem("SyndicationFeed released for .net Core", "A lot of text describing the release of .net core feature", new Uri("http://contoso.com/news/path")); item.Id = "uuid:43481a10-d881-40d1-adf2-99b438c57e21;id=1"; item.LastUpdatedTime = new DateTimeOffset(Convert.ToDateTime("2017-10-11T11:25:55Z")).UtcDateTime; try { using (FileStream fileStream = new FileStream(serializeFilePath, FileMode.OpenOrCreate)) { using (XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(fileStream)) { Atom10ItemFormatter f = new Atom10ItemFormatter(item); f.WriteTo(writer); } } CompareHelper ch = new CompareHelper { Diff = new XmlDiff() { Option = XmlDiffOption.IgnoreComments | XmlDiffOption.IgnorePrefix | XmlDiffOption.IgnoreWhitespace | XmlDiffOption.IgnoreChildOrder | XmlDiffOption.IgnoreAttributeOrder } }; string diffNode = string.Empty; if (!ch.Compare(file, serializeFilePath, out diffNode)) { toDeletedFile = false; string errorMessage = $"The generated file was different from the baseline file:{Environment.NewLine}Baseline: {file}{Environment.NewLine}Actual: {serializeFilePath}{Environment.NewLine}Different Nodes:{Environment.NewLine}{diffNode}"; Assert.True(false, errorMessage); } } finally { if (toDeletedFile) { File.Delete(serializeFilePath); } } } [Fact] public static void AtomFeedPositiveTest() { string dataFile = "TestFeeds/atom_feeds.dat"; List<string> fileList = GetTestFilesForFeedTest(dataFile); List<AllowableDifference> allowableDifferences = GetAtomFeedPositiveTestAllowableDifferences(); foreach (string file in fileList) { ReadWriteSyndicationFeed(file, (feedObject) => new Atom10FeedFormatter(feedObject), allowableDifferences); } } [Fact] public static void RssEntryPositiveTest() { string file = "TestFeeds/RssEntry.xml"; ReadWriteSyndicationItem(file, (itemObject) => new Rss20ItemFormatter(itemObject)); } [Fact] public static void RssFeedPositiveTest() { string dataFile = "TestFeeds/rss_feeds.dat"; List<string> fileList = GetTestFilesForFeedTest(dataFile); List<AllowableDifference> allowableDifferences = GetRssFeedPositiveTestAllowableDifferences(); foreach (string file in fileList) { ReadWriteSyndicationFeed(file, (feedObject) => new Rss20FeedFormatter(feedObject), allowableDifferences); } } [Fact] public static void DiffAtomNsTest() { string file = "TestFeeds/FailureFeeds/diff_atom_ns.xml"; using (XmlReader reader = XmlReader.Create(file)) { Assert.Throws<XmlException>(() => { SyndicationItem.Load(reader); }); } } [Fact] public static void DiffRssNsTest() { string file = "TestFeeds/FailureFeeds/diff_rss_ns.xml"; using (XmlReader reader = XmlReader.Create(file)) { Assert.Throws<XmlException>(() => { SyndicationItem.Load(reader); }); } } [Fact] public static void DiffRssVersionTest() { string file = "TestFeeds/FailureFeeds/diff_rss_version.xml"; using (XmlReader reader = XmlReader.Create(file)) { Assert.Throws<XmlException>(() => { SyndicationItem.Load(reader); }); } } [Fact] public static void NoRssVersionTest() { string file = "TestFeeds/FailureFeeds/no_rss_version.xml"; using (XmlReader reader = XmlReader.Create(file)) { Assert.Throws<XmlException>(() => { SyndicationItem.Load(reader); }); } } private static void ReadWriteSyndicationItem(string file, Func<SyndicationItem, SyndicationItemFormatter> itemFormatter) { string serializeFilePath = Path.GetTempFileName(); bool toDeletedFile = true; try { SyndicationItem itemObjct = null; using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { using (XmlReader reader = XmlDictionaryReader.CreateTextReader(fileStream, XmlDictionaryReaderQuotas.Max)) { itemObjct = SyndicationItem.Load(reader); } } using (FileStream fileStream = new FileStream(serializeFilePath, FileMode.OpenOrCreate)) { using (XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(fileStream)) { SyndicationItemFormatter formatter = itemFormatter(itemObjct); formatter.WriteTo(writer); } } // compare file filePath and serializeFilePath CompareHelper ch = new CompareHelper { Diff = new XmlDiff() { Option = XmlDiffOption.IgnoreComments | XmlDiffOption.IgnorePrefix | XmlDiffOption.IgnoreWhitespace | XmlDiffOption.IgnoreChildOrder | XmlDiffOption.IgnoreAttributeOrder } }; string diffNode = string.Empty; if (!ch.Compare(file, serializeFilePath, out diffNode)) { toDeletedFile = false; string errorMessage = $"The generated file was different from the baseline file:{Environment.NewLine}Baseline: {file}{Environment.NewLine}Actual: {serializeFilePath}{Environment.NewLine}Different Nodes:{Environment.NewLine}{diffNode}"; Assert.True(false, errorMessage); } } catch (Exception e) { Exception newEx = new Exception($"Failed File Name: {file}", e); throw newEx; } finally { if (toDeletedFile) { File.Delete(serializeFilePath); } } } private static void ReadWriteSyndicationFeed(string file, Func<SyndicationFeed, SyndicationFeedFormatter> feedFormatter, List<AllowableDifference> allowableDifferences = null, Action<SyndicationFeed> verifySyndicationFeedRead = null) { string serializeFilePath = Path.GetTempFileName(); bool toDeletedFile = true; try { SyndicationFeed feedObjct; using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { using (XmlReader reader = XmlDictionaryReader.CreateTextReader(fileStream, XmlDictionaryReaderQuotas.Max)) { feedObjct = SyndicationFeed.Load(reader); verifySyndicationFeedRead?.Invoke(feedObjct); } } using (FileStream fileStream = new FileStream(serializeFilePath, FileMode.OpenOrCreate)) { using (XmlWriter writer = XmlDictionaryWriter.CreateTextWriter(fileStream)) { SyndicationFeedFormatter formatter = feedFormatter(feedObjct); formatter.WriteTo(writer); } } CompareHelper ch = new CompareHelper { Diff = new XmlDiff() { Option = XmlDiffOption.IgnoreComments | XmlDiffOption.IgnorePrefix | XmlDiffOption.IgnoreWhitespace | XmlDiffOption.IgnoreChildOrder | XmlDiffOption.IgnoreAttributeOrder }, AllowableDifferences = allowableDifferences }; string diffNode = string.Empty; if (!ch.Compare(file, serializeFilePath, out diffNode)) { toDeletedFile = false; string errorMessage = $"The generated file was different from the baseline file:{Environment.NewLine}Baseline: {file}{Environment.NewLine}Actual: {serializeFilePath}{Environment.NewLine}Different Nodes:{Environment.NewLine}{diffNode}"; Assert.True(false, errorMessage); } } catch (Exception e) { Exception newEx = new Exception($"Failed File Name: {file}", e); throw newEx; } finally { if (toDeletedFile) { File.Delete(serializeFilePath); } } } private static List<AllowableDifference> GetAtomFeedPositiveTestAllowableDifferences() { return new List<AllowableDifference>(new AllowableDifference[] { new AllowableDifference("<content xmlns=\"http://www.w3.org/2005/Atom\" />","<content type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<content>","<content type=\"text\">"), new AllowableDifference("<content src=\"http://contoso.com/2003/12/13/atom03\" xmlns=\"http://www.w3.org/2005/Atom\" />","<content src=\"http://contoso.com/2003/12/13/atom03\" type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<content src=\" http://www.contoso.com/doc.pdf\" type=\"application/pdf\" xmlns=\"http://www.w3.org/2005/Atom\" />","<content src=\"http://www.contoso.com/doc.pdf\" type=\"application/pdf\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<title>","<title type=\"text\">"), new AllowableDifference("<subtitle>","<subtitle type=\"text\">"), new AllowableDifference("<subtitle xmlns=\"http://www.w3.org/2005/Atom\" />","<subtitle type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<title xmlns=\"http://www.w3.org/2005/Atom\" />","<title type=\"text\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<atom:title>","<title type=\"text\">"), new AllowableDifference("<summary>","<summary type=\"text\">"), new AllowableDifference("<atom:summary>","<summary type=\"text\">"), new AllowableDifference("<generator uri=\"http://www.contoso.com/\" version=\"1.0\">", "<generator>"), new AllowableDifference("<generator uri=\"/generator\" xmlns=\"http://www.w3.org/2005/Atom\" />", "<generator xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<generator uri=\"/generator\">", "<generator>"), new AllowableDifference("<generator uri=\"misc/Colophon\">", "<generator>"), new AllowableDifference("<generator uri=\"http://www.contoso.com/ \" version=\"1.0\">", "<generator>"), new AllowableDifference("<rights>","<rights type=\"text\">"), new AllowableDifference("<link href=\"http://contoso.com\" xmlns=\"http://www.w3.org/2005/Atom\" />","<link href=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<link href=\" http://contoso.com/ \" xmlns=\"http://www.w3.org/2005/Atom\" />","<link href=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<feed xml:lang=\"\" xmlns=\"http://www.w3.org/2005/Atom\">","<feed xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<entry xmlns:xh=\"http://www.w3.org/1999/xhtml\">","<entry>"), new AllowableDifference("<xh:div>","<xh:div xmlns:xh=\"http://www.w3.org/1999/xhtml\">"), new AllowableDifference("<summary type=\"xhtml\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">","<summary type=\"xhtml\">"), new AllowableDifference("<xhtml:a href=\"http://contoso.com/\">","<xhtml:a href=\"http://contoso.com/\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">"), new AllowableDifference("<feed xmlns:trackback=\"http://contoso.com/public/xml/rss/module/trackback/\" xmlns=\"http://www.w3.org/2005/Atom\">","<feed xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<trackback:ping>", "<trackback:ping xmlns:trackback=\"http://contoso.com/public/xml/rss/module/trackback/\">"), new AllowableDifference("<feed xmlns:dc=\"http://contoso.com/dc/elements/1.1/\" xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<author rdf:parseType=\"Resource\">", "<author xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" a:parseType=\"Resource\">"), new AllowableDifference("<foaf:homepage rdf:resource=\"http://contoso.com/\">", "<foaf:homepage xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:resource=\"http://contoso.com/\">"), new AllowableDifference("<foaf:weblog rdf:resource=\"http://contoso.com/blog/\">", "<foaf:weblog xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:resource=\"http://contoso.com/blog/\">"), new AllowableDifference("<foaf:workplaceHomepage rdf:resource=\"http://DoeCorp.contoso.com/\">", "<foaf:workplaceHomepage xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rdf:resource=\"http://DoeCorp.contoso.com/\">"), new AllowableDifference("<dc:description>", "<dc:description xmlns:dc=\"http://contoso.com/dc/elements/1.1/\">"), new AllowableDifference("<entry rdf:parseType=\"Resource\">", "<entry xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" a:parseType=\"Resource\">"), new AllowableDifference("<foaf:primaryTopic rdf:parseType=\"Resource\">", "<foaf:primaryTopic xmlns:foaf=\"http://xmlns.com/foaf/0.1/\" rdf:parseType=\"Resource\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">"), new AllowableDifference("<link href=\"http://contoso.com/\" rdf:resource=\"http://contoso.com/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" xmlns=\"http://www.w3.org/2005/Atom\" />", "<link xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" href=\"http://contoso.com/\" a:resource=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\" />"), new AllowableDifference("<feed xmlns:creativeCommons=\"http://contoso.com/creativeCommonsRssModule\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<creativeCommons:license>", "<creativeCommons:license xmlns:creativeCommons=\"http://contoso.com/creativeCommonsRssModule\">"), new AllowableDifference("<feed xmlns:a=\"http://www.contoso.com/extension-a\" xmlns:dc=\"http://contoso.com/dc/elements/1.1/\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<a:simple-value>", "<a:simple-value xmlns:a=\"http://www.contoso.com/extension-a\">"), new AllowableDifference("<a:structured-xml>", "<a:structured-xml xmlns:a=\"http://www.contoso.com/extension-a\">"), new AllowableDifference("<dc:title>", "<dc:title xmlns:dc=\"http://contoso.com/dc/elements/1.1/\">"), new AllowableDifference("<simple-value>", "<simple-value xmlns=\"\">"), new AllowableDifference("<feed xmlns:xhtml=\"http://www.w3.org/1999/xhtml\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<trackback:about>", "<trackback:about xmlns:trackback=\"http://contoso.com/public/xml/rss/module/trackback/\">"), new AllowableDifference("<xhtml:img src=\"http://contoso.com/image.jpg\">", "<xhtml:img src=\"http://contoso.com/image.jpg\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">"), new AllowableDifference("<feed xml:base=\"http://contoso.com\" xmlns=\"http://www.w3.org/2005/Atom\">", "<feed xml:base=\"http://contoso.com/\" xmlns=\"http://www.w3.org/2005/Atom\">"), new AllowableDifference("<link href=\"http://contoso.com/licenses/by-nc/2.5/\" xmlns:lic=\"http://web.resource.org/cc/\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" rel=\"http://www.contoso.com/atom/extensions/proposed/license\" rdf:resource=\"http://contoso.com/licenses/by-nc/2.5/\" type=\"text/html\" rdf:type=\"http://web.resource.org/cc/license\">", "<link xmlns:a=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" href=\"http://contoso.com/licenses/by-nc/2.5/\" rel=\"http://www.contoso.com/atom/extensions/proposed/license\" a:resource=\"http://contoso.com/licenses/by-nc/2.5/\" type=\"text/html\" a:type=\"http://web.resource.org/cc/license\">"), }); } private static List<AllowableDifference> GetRssFeedPositiveTestAllowableDifferences() { return new List<AllowableDifference>(new AllowableDifference[] { new AllowableDifference("<rss version=\"2.0\">","<rss xmlns:a10=\"http://www.w3.org/2005/Atom\" version=\"2.0\">"), new AllowableDifference("<content:encoded>", "<content:encoded xmlns:content=\"http://contoso.com/rss/1.0/modules/content/\">"), new AllowableDifference("Tue, 31 Dec 2002 14:20:20 GMT", "Tue, 31 Dec 2002 14:20:20 Z"), }); } private static List<string> GetTestFilesForFeedTest(string dataFile) { List<string> fileList = new List<string>(); string file; using (StreamReader sr = new StreamReader(dataFile)) { while (!string.IsNullOrEmpty(file = sr.ReadLine())) { if (!file.StartsWith("#")) { file = Path.Combine("TestFeeds", file.Trim()); if (File.Exists(file)) { fileList.Add(Path.GetFullPath(file)); } else { throw new FileNotFoundException($"File `{file}` was not found!"); } } } } return fileList; } } }
// <copyright file="UserQRTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // Copyright (c) 2009-2010 Math.NET // 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> using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Double.Factorization; using MathNet.Numerics.LinearAlgebra.Factorization; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Double.Factorization { /// <summary> /// QR factorization tests for a user matrix. /// </summary> [TestFixture, Category("LAFactorization")] public class UserQRTests { /// <summary> /// Constructor with wide matrix throws <c>ArgumentException</c>. /// </summary> [Test] public void ConstructorWideMatrixThrowsInvalidMatrixOperationException() { Assert.That(() => UserQR.Create(new UserDefinedMatrix(3, 4)), Throws.ArgumentException); } /// <summary> /// Can factorize identity matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentity(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorQR = matrixI.QR(); var r = factorQR.R; Assert.AreEqual(matrixI.RowCount, r.RowCount); Assert.AreEqual(matrixI.ColumnCount, r.ColumnCount); for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i == j) { Assert.AreEqual(-1.0, r[i, j]); } else { Assert.AreEqual(0.0, r[i, j]); } } } } /// <summary> /// Can factorize identity matrix using thin QR. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void CanFactorizeIdentityUsingThinQR(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorQR = matrixI.QR(QRMethod.Thin); var r = factorQR.R; Assert.AreEqual(matrixI.RowCount, r.RowCount); Assert.AreEqual(matrixI.ColumnCount, r.ColumnCount); for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i == j) { Assert.AreEqual(-1.0, r[i, j]); } else { Assert.AreEqual(0.0, r[i, j]); } } } } /// <summary> /// Identity determinant is one. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(10)] [TestCase(100)] public void IdentityDeterminantIsOne(int order) { var matrixI = UserDefinedMatrix.Identity(order); var factorQR = matrixI.QR(); Assert.AreEqual(1.0, factorQR.Determinant); } /// <summary> /// Can factorize a random matrix. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrix(int row, int column) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray()); var factorQR = matrixA.QR(QRMethod.Full); var q = factorQR.Q; var r = factorQR.R; // Make sure the R has the right dimensions. Assert.AreEqual(row, r.RowCount); Assert.AreEqual(column, r.ColumnCount); // Make sure the Q has the right dimensions. Assert.AreEqual(row, q.RowCount); Assert.AreEqual(row, q.ColumnCount); // Make sure the R factor is upper triangular. for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i > j) { Assert.AreEqual(0.0, r[i, j]); } } } // Make sure the Q*R is the original matrix. var matrixQfromR = q * r; for (var i = 0; i < matrixQfromR.RowCount; i++) { for (var j = 0; j < matrixQfromR.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrixQfromR[i, j], 1.0e-11); } } } /// <summary> /// Can factorize a random matrix using thin QR. /// </summary> /// <param name="row">Matrix row number.</param> /// <param name="column">Matrix column number.</param> [TestCase(1, 1)] [TestCase(2, 2)] [TestCase(5, 5)] [TestCase(10, 6)] [TestCase(50, 48)] [TestCase(100, 98)] public void CanFactorizeRandomMatrixUsingThinQR(int row, int column) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(row, column, 1).ToArray()); var factorQR = matrixA.QR(QRMethod.Thin); var q = factorQR.Q; var r = factorQR.R; // Make sure the R has the right dimensions. Assert.AreEqual(column, r.RowCount); Assert.AreEqual(column, r.ColumnCount); // Make sure the Q has the right dimensions. Assert.AreEqual(row, q.RowCount); Assert.AreEqual(column, q.ColumnCount); // Make sure the R factor is upper triangular. for (var i = 0; i < r.RowCount; i++) { for (var j = 0; j < r.ColumnCount; j++) { if (i > j) { Assert.AreEqual(0.0, r[i, j]); } } } // Make sure the Q*R is the original matrix. var matrixQfromR = q * r; for (var i = 0; i < matrixQfromR.RowCount; i++) { for (var j = 0; j < matrixQfromR.ColumnCount; j++) { Assert.AreEqual(matrixA[i, j], matrixQfromR[i, j], 1.0e-11); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVector(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var vectorb = new UserDefinedVector(Vector<double>.Build.Random(order, 1).ToArray()); var resultx = factorQR.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrix(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixX = factorQR.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var vectorb = new UserDefinedVector(Vector<double>.Build.Random(order, 1).ToArray()); var vectorbCopy = vectorb.Clone(); var resultx = new UserDefinedVector(order); factorQR.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGiven(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(); var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(order, order); factorQR.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random vector (Ax=b). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorUsingThinQR(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var vectorb = new UserDefinedVector(Vector<double>.Build.Random(order, 1).ToArray()); var resultx = factorQR.Solve(vectorb); Assert.AreEqual(matrixA.ColumnCount, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < order; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B). /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixUsingThinQR(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixX = factorQR.Solve(matrixB); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } } /// <summary> /// Can solve for a random vector into a result vector. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomVectorWhenResultVectorGivenUsingThinQR(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var vectorb = new UserDefinedVector(Vector<double>.Build.Random(order, 1).ToArray()); var vectorbCopy = vectorb.Clone(); var resultx = new UserDefinedVector(order); factorQR.Solve(vectorb, resultx); Assert.AreEqual(vectorb.Count, resultx.Count); var matrixBReconstruct = matrixA * resultx; // Check the reconstruction. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorb[i], matrixBReconstruct[i], 1.0e-11); } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure b didn't change. for (var i = 0; i < vectorb.Count; i++) { Assert.AreEqual(vectorbCopy[i], vectorb[i]); } } /// <summary> /// Can solve a system of linear equations for a random matrix (AX=B) into a result matrix. /// </summary> /// <param name="order">Matrix order.</param> [TestCase(1)] [TestCase(2)] [TestCase(5)] [TestCase(10)] [TestCase(50)] [TestCase(100)] public void CanSolveForRandomMatrixWhenResultMatrixGivenUsingThinQR(int order) { var matrixA = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixACopy = matrixA.Clone(); var factorQR = matrixA.QR(QRMethod.Thin); var matrixB = new UserDefinedMatrix(Matrix<double>.Build.Random(order, order, 1).ToArray()); var matrixBCopy = matrixB.Clone(); var matrixX = new UserDefinedMatrix(order, order); factorQR.Solve(matrixB, matrixX); // The solution X row dimension is equal to the column dimension of A Assert.AreEqual(matrixA.ColumnCount, matrixX.RowCount); // The solution X has the same number of columns as B Assert.AreEqual(matrixB.ColumnCount, matrixX.ColumnCount); var matrixBReconstruct = matrixA * matrixX; // Check the reconstruction. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixB[i, j], matrixBReconstruct[i, j], 1.0e-11); } } // Make sure A didn't change. for (var i = 0; i < matrixA.RowCount; i++) { for (var j = 0; j < matrixA.ColumnCount; j++) { Assert.AreEqual(matrixACopy[i, j], matrixA[i, j]); } } // Make sure B didn't change. for (var i = 0; i < matrixB.RowCount; i++) { for (var j = 0; j < matrixB.ColumnCount; j++) { Assert.AreEqual(matrixBCopy[i, j], matrixB[i, j]); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void FloorScalarDouble() { var test = new SimpleBinaryOpTest__FloorScalarDouble(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__FloorScalarDouble { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Double); private const int Op2ElementCount = VectorSize / sizeof(Double); private const int RetElementCount = VectorSize / sizeof(Double); private static Double[] _data1 = new Double[Op1ElementCount]; private static Double[] _data2 = new Double[Op2ElementCount]; private static Vector128<Double> _clsVar1; private static Vector128<Double> _clsVar2; private Vector128<Double> _fld1; private Vector128<Double> _fld2; private SimpleBinaryOpTest__DataTable<Double, Double, Double> _dataTable; static SimpleBinaryOpTest__FloorScalarDouble() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _clsVar2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__FloorScalarDouble() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld1), ref Unsafe.As<Double, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Double>, byte>(ref _fld2), ref Unsafe.As<Double, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (double)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (double)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Double, Double, Double>(_data1, _data2, new Double[RetElementCount], VectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.FloorScalar( Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.FloorScalar( Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.FloorScalar( Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.FloorScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.FloorScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.FloorScalar), new Type[] { typeof(Vector128<Double>), typeof(Vector128<Double>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Double>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.FloorScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Double>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Double>>(_dataTable.inArray2Ptr); var result = Sse41.FloorScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse41.FloorScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Double*)(_dataTable.inArray2Ptr)); var result = Sse41.FloorScalar(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__FloorScalarDouble(); var result = Sse41.FloorScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.FloorScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Double> left, Vector128<Double> right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Double[] inArray1 = new Double[Op1ElementCount]; Double[] inArray2 = new Double[Op2ElementCount]; Double[] outArray = new Double[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Double, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Double[] left, Double[] right, Double[] result, [CallerMemberName] string method = "") { if (BitConverter.DoubleToInt64Bits(result[0]) != BitConverter.DoubleToInt64Bits(Math.Floor(right[0]))) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.DoubleToInt64Bits(result[i]) != BitConverter.DoubleToInt64Bits(left[i])) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.FloorScalar)}<Double>(Vector128<Double>, Vector128<Double>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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 gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gagr = Google.Api.Gax.ResourceNames; using gciv = Google.Cloud.Iam.V1; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.DataCatalog.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedPolicyTagManagerClientTest { [xunit::FactAttribute] public void CreateTaxonomyRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreateTaxonomyRequest request = new CreateTaxonomyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.CreateTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.CreateTaxonomy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTaxonomyRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreateTaxonomyRequest request = new CreateTaxonomyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.CreateTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.CreateTaxonomyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.CreateTaxonomyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTaxonomy() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreateTaxonomyRequest request = new CreateTaxonomyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.CreateTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.CreateTaxonomy(request.Parent, request.Taxonomy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTaxonomyAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreateTaxonomyRequest request = new CreateTaxonomyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.CreateTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.CreateTaxonomyAsync(request.Parent, request.Taxonomy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.CreateTaxonomyAsync(request.Parent, request.Taxonomy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreateTaxonomyResourceNames() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreateTaxonomyRequest request = new CreateTaxonomyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.CreateTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.CreateTaxonomy(request.ParentAsLocationName, request.Taxonomy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreateTaxonomyResourceNamesAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreateTaxonomyRequest request = new CreateTaxonomyRequest { ParentAsLocationName = gagr::LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.CreateTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.CreateTaxonomyAsync(request.ParentAsLocationName, request.Taxonomy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.CreateTaxonomyAsync(request.ParentAsLocationName, request.Taxonomy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTaxonomyRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeleteTaxonomyRequest request = new DeleteTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); client.DeleteTaxonomy(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTaxonomyRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeleteTaxonomyRequest request = new DeleteTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); await client.DeleteTaxonomyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTaxonomyAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTaxonomy() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeleteTaxonomyRequest request = new DeleteTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); client.DeleteTaxonomy(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTaxonomyAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeleteTaxonomyRequest request = new DeleteTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); await client.DeleteTaxonomyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTaxonomyAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeleteTaxonomyResourceNames() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeleteTaxonomyRequest request = new DeleteTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); client.DeleteTaxonomy(request.TaxonomyName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeleteTaxonomyResourceNamesAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeleteTaxonomyRequest request = new DeleteTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeleteTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); await client.DeleteTaxonomyAsync(request.TaxonomyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeleteTaxonomyAsync(request.TaxonomyName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTaxonomyRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdateTaxonomyRequest request = new UpdateTaxonomyRequest { Taxonomy = new Taxonomy(), UpdateMask = new wkt::FieldMask(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.UpdateTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.UpdateTaxonomy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTaxonomyRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdateTaxonomyRequest request = new UpdateTaxonomyRequest { Taxonomy = new Taxonomy(), UpdateMask = new wkt::FieldMask(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.UpdateTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.UpdateTaxonomyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.UpdateTaxonomyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdateTaxonomy() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdateTaxonomyRequest request = new UpdateTaxonomyRequest { Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.UpdateTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.UpdateTaxonomy(request.Taxonomy); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdateTaxonomyAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdateTaxonomyRequest request = new UpdateTaxonomyRequest { Taxonomy = new Taxonomy(), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.UpdateTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.UpdateTaxonomyAsync(request.Taxonomy, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.UpdateTaxonomyAsync(request.Taxonomy, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTaxonomyRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetTaxonomyRequest request = new GetTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.GetTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.GetTaxonomy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTaxonomyRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetTaxonomyRequest request = new GetTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.GetTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.GetTaxonomyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.GetTaxonomyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTaxonomy() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetTaxonomyRequest request = new GetTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.GetTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.GetTaxonomy(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTaxonomyAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetTaxonomyRequest request = new GetTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.GetTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.GetTaxonomyAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.GetTaxonomyAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetTaxonomyResourceNames() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetTaxonomyRequest request = new GetTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.GetTaxonomy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy response = client.GetTaxonomy(request.TaxonomyName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetTaxonomyResourceNamesAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetTaxonomyRequest request = new GetTaxonomyRequest { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), }; Taxonomy expectedResponse = new Taxonomy { TaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", PolicyTagCount = -1730676159, TaxonomyTimestamps = new SystemTimestamps(), ActivatedPolicyTypes = { Taxonomy.Types.PolicyType.Unspecified, }, }; mockGrpcClient.Setup(x => x.GetTaxonomyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Taxonomy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); Taxonomy responseCallSettings = await client.GetTaxonomyAsync(request.TaxonomyName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Taxonomy responseCancellationToken = await client.GetTaxonomyAsync(request.TaxonomyName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePolicyTagRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreatePolicyTagRequest request = new CreatePolicyTagRequest { ParentAsTaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.CreatePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.CreatePolicyTag(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePolicyTagRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreatePolicyTagRequest request = new CreatePolicyTagRequest { ParentAsTaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.CreatePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.CreatePolicyTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.CreatePolicyTagAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePolicyTag() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreatePolicyTagRequest request = new CreatePolicyTagRequest { ParentAsTaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.CreatePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.CreatePolicyTag(request.Parent, request.PolicyTag); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePolicyTagAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreatePolicyTagRequest request = new CreatePolicyTagRequest { ParentAsTaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.CreatePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.CreatePolicyTagAsync(request.Parent, request.PolicyTag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.CreatePolicyTagAsync(request.Parent, request.PolicyTag, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CreatePolicyTagResourceNames() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreatePolicyTagRequest request = new CreatePolicyTagRequest { ParentAsTaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.CreatePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.CreatePolicyTag(request.ParentAsTaxonomyName, request.PolicyTag); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CreatePolicyTagResourceNamesAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); CreatePolicyTagRequest request = new CreatePolicyTagRequest { ParentAsTaxonomyName = TaxonomyName.FromProjectLocationTaxonomy("[PROJECT]", "[LOCATION]", "[TAXONOMY]"), PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.CreatePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.CreatePolicyTagAsync(request.ParentAsTaxonomyName, request.PolicyTag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.CreatePolicyTagAsync(request.ParentAsTaxonomyName, request.PolicyTag, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePolicyTagRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeletePolicyTagRequest request = new DeletePolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); client.DeletePolicyTag(request); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePolicyTagRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeletePolicyTagRequest request = new DeletePolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); await client.DeletePolicyTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePolicyTagAsync(request, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePolicyTag() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeletePolicyTagRequest request = new DeletePolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); client.DeletePolicyTag(request.Name); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePolicyTagAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeletePolicyTagRequest request = new DeletePolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); await client.DeletePolicyTagAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePolicyTagAsync(request.Name, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void DeletePolicyTagResourceNames() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeletePolicyTagRequest request = new DeletePolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); client.DeletePolicyTag(request.PolicyTagName); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task DeletePolicyTagResourceNamesAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); DeletePolicyTagRequest request = new DeletePolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; wkt::Empty expectedResponse = new wkt::Empty { }; mockGrpcClient.Setup(x => x.DeletePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<wkt::Empty>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); await client.DeletePolicyTagAsync(request.PolicyTagName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); await client.DeletePolicyTagAsync(request.PolicyTagName, st::CancellationToken.None); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdatePolicyTagRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdatePolicyTagRequest request = new UpdatePolicyTagRequest { PolicyTag = new PolicyTag(), UpdateMask = new wkt::FieldMask(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.UpdatePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.UpdatePolicyTag(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdatePolicyTagRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdatePolicyTagRequest request = new UpdatePolicyTagRequest { PolicyTag = new PolicyTag(), UpdateMask = new wkt::FieldMask(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.UpdatePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.UpdatePolicyTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.UpdatePolicyTagAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void UpdatePolicyTag() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdatePolicyTagRequest request = new UpdatePolicyTagRequest { PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.UpdatePolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.UpdatePolicyTag(request.PolicyTag); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task UpdatePolicyTagAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); UpdatePolicyTagRequest request = new UpdatePolicyTagRequest { PolicyTag = new PolicyTag(), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.UpdatePolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.UpdatePolicyTagAsync(request.PolicyTag, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.UpdatePolicyTagAsync(request.PolicyTag, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPolicyTagRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetPolicyTagRequest request = new GetPolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.GetPolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.GetPolicyTag(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPolicyTagRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetPolicyTagRequest request = new GetPolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.GetPolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.GetPolicyTagAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.GetPolicyTagAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPolicyTag() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetPolicyTagRequest request = new GetPolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.GetPolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.GetPolicyTag(request.Name); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPolicyTagAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetPolicyTagRequest request = new GetPolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.GetPolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.GetPolicyTagAsync(request.Name, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.GetPolicyTagAsync(request.Name, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetPolicyTagResourceNames() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetPolicyTagRequest request = new GetPolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.GetPolicyTag(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag response = client.GetPolicyTag(request.PolicyTagName); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetPolicyTagResourceNamesAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); GetPolicyTagRequest request = new GetPolicyTagRequest { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), }; PolicyTag expectedResponse = new PolicyTag { PolicyTagName = PolicyTagName.FromProjectLocationTaxonomyPolicyTag("[PROJECT]", "[LOCATION]", "[TAXONOMY]", "[POLICY_TAG]"), DisplayName = "display_name137f65c2", Description = "description2cf9da67", ParentPolicyTag = "parent_policy_tagbc591931", ChildPolicyTags = { "child_policy_tags11be0699", }, }; mockGrpcClient.Setup(x => x.GetPolicyTagAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<PolicyTag>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); PolicyTag responseCallSettings = await client.GetPolicyTagAsync(request.PolicyTagName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); PolicyTag responseCancellationToken = await client.GetPolicyTagAsync(request.PolicyTagName, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); gciv::GetIamPolicyRequest request = new gciv::GetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Options = new gciv::GetPolicyOptions(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); gciv::Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); gciv::SetIamPolicyRequest request = new gciv::SetIamPolicyRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Policy = new gciv::Policy(), }; gciv::Policy expectedResponse = new gciv::Policy { Version = 271578922, Etag = proto::ByteString.CopyFromUtf8("etage8ad7218"), Bindings = { new gciv::Binding(), }, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); gciv::Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<PolicyTagManager.PolicyTagManagerClient> mockGrpcClient = new moq::Mock<PolicyTagManager.PolicyTagManagerClient>(moq::MockBehavior.Strict); gciv::TestIamPermissionsRequest request = new gciv::TestIamPermissionsRequest { ResourceAsResourceName = new gax::UnparsedResourceName("a/wildcard/resource"), Permissions = { "permissions535a2741", }, }; gciv::TestIamPermissionsResponse expectedResponse = new gciv::TestIamPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gciv::TestIamPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); PolicyTagManagerClient client = new PolicyTagManagerClientImpl(mockGrpcClient.Object, null); gciv::TestIamPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); gciv::TestIamPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#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.Runtime.Serialization.Formatters; using Newtonsoft.Json.Utilities; using System.Runtime.Serialization; namespace Newtonsoft.Json.Serialization { internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerInternalReader _serializerReader; private readonly JsonSerializerInternalWriter _serializerWriter; private readonly JsonSerializer _serializer; public override event EventHandler<ErrorEventArgs> Error { add { _serializer.Error += value; } remove { _serializer.Error -= value; } } public override IReferenceResolver ReferenceResolver { get { return _serializer.ReferenceResolver; } set { _serializer.ReferenceResolver = value; } } public override ITraceWriter TraceWriter { get { return _serializer.TraceWriter; } set { _serializer.TraceWriter = value; } } public override IEqualityComparer EqualityComparer { get { return _serializer.EqualityComparer; } set { _serializer.EqualityComparer = value; } } public override JsonConverterCollection Converters { get { return _serializer.Converters; } } public override DefaultValueHandling DefaultValueHandling { get { return _serializer.DefaultValueHandling; } set { _serializer.DefaultValueHandling = value; } } public override IContractResolver ContractResolver { get { return _serializer.ContractResolver; } set { _serializer.ContractResolver = value; } } public override MissingMemberHandling MissingMemberHandling { get { return _serializer.MissingMemberHandling; } set { _serializer.MissingMemberHandling = value; } } public override NullValueHandling NullValueHandling { get { return _serializer.NullValueHandling; } set { _serializer.NullValueHandling = value; } } public override ObjectCreationHandling ObjectCreationHandling { get { return _serializer.ObjectCreationHandling; } set { _serializer.ObjectCreationHandling = value; } } public override ReferenceLoopHandling ReferenceLoopHandling { get { return _serializer.ReferenceLoopHandling; } set { _serializer.ReferenceLoopHandling = value; } } public override PreserveReferencesHandling PreserveReferencesHandling { get { return _serializer.PreserveReferencesHandling; } set { _serializer.PreserveReferencesHandling = value; } } public override TypeNameHandling TypeNameHandling { get { return _serializer.TypeNameHandling; } set { _serializer.TypeNameHandling = value; } } public override MetadataPropertyHandling MetadataPropertyHandling { get { return _serializer.MetadataPropertyHandling; } set { _serializer.MetadataPropertyHandling = value; } } public override FormatterAssemblyStyle TypeNameAssemblyFormat { get { return _serializer.TypeNameAssemblyFormat; } set { _serializer.TypeNameAssemblyFormat = value; } } public override ConstructorHandling ConstructorHandling { get { return _serializer.ConstructorHandling; } set { _serializer.ConstructorHandling = value; } } public override SerializationBinder Binder { get { return _serializer.Binder; } set { _serializer.Binder = value; } } public override StreamingContext Context { get { return _serializer.Context; } set { _serializer.Context = value; } } public override Formatting Formatting { get { return _serializer.Formatting; } set { _serializer.Formatting = value; } } public override DateFormatHandling DateFormatHandling { get { return _serializer.DateFormatHandling; } set { _serializer.DateFormatHandling = value; } } public override DateTimeZoneHandling DateTimeZoneHandling { get { return _serializer.DateTimeZoneHandling; } set { _serializer.DateTimeZoneHandling = value; } } public override DateParseHandling DateParseHandling { get { return _serializer.DateParseHandling; } set { _serializer.DateParseHandling = value; } } public override FloatFormatHandling FloatFormatHandling { get { return _serializer.FloatFormatHandling; } set { _serializer.FloatFormatHandling = value; } } public override FloatParseHandling FloatParseHandling { get { return _serializer.FloatParseHandling; } set { _serializer.FloatParseHandling = value; } } public override StringEscapeHandling StringEscapeHandling { get { return _serializer.StringEscapeHandling; } set { _serializer.StringEscapeHandling = value; } } public override string DateFormatString { get { return _serializer.DateFormatString; } set { _serializer.DateFormatString = value; } } public override CultureInfo Culture { get { return _serializer.Culture; } set { _serializer.Culture = value; } } public override int? MaxDepth { get { return _serializer.MaxDepth; } set { _serializer.MaxDepth = value; } } public override bool CheckAdditionalContent { get { return _serializer.CheckAdditionalContent; } set { _serializer.CheckAdditionalContent = value; } } internal JsonSerializerInternalBase GetInternalSerializer() { if (_serializerReader != null) { return _serializerReader; } else { return _serializerWriter; } } public JsonSerializerProxy(JsonSerializerInternalReader serializerReader) { ValidationUtils.ArgumentNotNull(serializerReader, "serializerReader"); _serializerReader = serializerReader; _serializer = serializerReader.Serializer; } public JsonSerializerProxy(JsonSerializerInternalWriter serializerWriter) { ValidationUtils.ArgumentNotNull(serializerWriter, "serializerWriter"); _serializerWriter = serializerWriter; _serializer = serializerWriter.Serializer; } internal override object DeserializeInternal(JsonReader reader, Type objectType) { if (_serializerReader != null) { return _serializerReader.Deserialize(reader, objectType, false); } else { return _serializer.Deserialize(reader, objectType); } } internal override void PopulateInternal(JsonReader reader, object target) { if (_serializerReader != null) { _serializerReader.Populate(reader, target); } else { _serializer.Populate(reader, target); } } internal override void SerializeInternal(JsonWriter jsonWriter, object value, Type rootType) { if (_serializerWriter != null) { _serializerWriter.Serialize(jsonWriter, value, rootType); } else { _serializer.Serialize(jsonWriter, value); } } } }
/* Generated SBE (Simple Binary Encoding) message codec */ using System; using System.Text; using System.Collections.Generic; using Adaptive.Agrona; namespace Adaptive.Archiver.Codecs { public class TruncateRecordingRequestDecoder { public const ushort BLOCK_LENGTH = 32; public const ushort TEMPLATE_ID = 13; public const ushort SCHEMA_ID = 101; public const ushort SCHEMA_VERSION = 6; private TruncateRecordingRequestDecoder _parentMessage; private IDirectBuffer _buffer; protected int _offset; protected int _limit; protected int _actingBlockLength; protected int _actingVersion; public TruncateRecordingRequestDecoder() { _parentMessage = this; } public ushort SbeBlockLength() { return BLOCK_LENGTH; } public ushort SbeTemplateId() { return TEMPLATE_ID; } public ushort SbeSchemaId() { return SCHEMA_ID; } public ushort SbeSchemaVersion() { return SCHEMA_VERSION; } public string SbeSemanticType() { return ""; } public IDirectBuffer Buffer() { return _buffer; } public int Offset() { return _offset; } public TruncateRecordingRequestDecoder Wrap( IDirectBuffer buffer, int offset, int actingBlockLength, int actingVersion) { this._buffer = buffer; this._offset = offset; this._actingBlockLength = actingBlockLength; this._actingVersion = actingVersion; Limit(offset + actingBlockLength); return this; } public int EncodedLength() { return _limit - _offset; } public int Limit() { return _limit; } public void Limit(int limit) { this._limit = limit; } public static int ControlSessionIdId() { return 1; } public static int ControlSessionIdSinceVersion() { return 0; } public static int ControlSessionIdEncodingOffset() { return 0; } public static int ControlSessionIdEncodingLength() { return 8; } public static string ControlSessionIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long ControlSessionIdNullValue() { return -9223372036854775808L; } public static long ControlSessionIdMinValue() { return -9223372036854775807L; } public static long ControlSessionIdMaxValue() { return 9223372036854775807L; } public long ControlSessionId() { return _buffer.GetLong(_offset + 0, ByteOrder.LittleEndian); } public static int CorrelationIdId() { return 2; } public static int CorrelationIdSinceVersion() { return 0; } public static int CorrelationIdEncodingOffset() { return 8; } public static int CorrelationIdEncodingLength() { return 8; } public static string CorrelationIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long CorrelationIdNullValue() { return -9223372036854775808L; } public static long CorrelationIdMinValue() { return -9223372036854775807L; } public static long CorrelationIdMaxValue() { return 9223372036854775807L; } public long CorrelationId() { return _buffer.GetLong(_offset + 8, ByteOrder.LittleEndian); } public static int RecordingIdId() { return 3; } public static int RecordingIdSinceVersion() { return 0; } public static int RecordingIdEncodingOffset() { return 16; } public static int RecordingIdEncodingLength() { return 8; } public static string RecordingIdMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long RecordingIdNullValue() { return -9223372036854775808L; } public static long RecordingIdMinValue() { return -9223372036854775807L; } public static long RecordingIdMaxValue() { return 9223372036854775807L; } public long RecordingId() { return _buffer.GetLong(_offset + 16, ByteOrder.LittleEndian); } public static int PositionId() { return 4; } public static int PositionSinceVersion() { return 0; } public static int PositionEncodingOffset() { return 24; } public static int PositionEncodingLength() { return 8; } public static string PositionMetaAttribute(MetaAttribute metaAttribute) { switch (metaAttribute) { case MetaAttribute.EPOCH: return "unix"; case MetaAttribute.TIME_UNIT: return "nanosecond"; case MetaAttribute.SEMANTIC_TYPE: return ""; case MetaAttribute.PRESENCE: return "required"; } return ""; } public static long PositionNullValue() { return -9223372036854775808L; } public static long PositionMinValue() { return -9223372036854775807L; } public static long PositionMaxValue() { return 9223372036854775807L; } public long Position() { return _buffer.GetLong(_offset + 24, ByteOrder.LittleEndian); } public override string ToString() { return AppendTo(new StringBuilder(100)).ToString(); } public StringBuilder AppendTo(StringBuilder builder) { int originalLimit = Limit(); Limit(_offset + _actingBlockLength); builder.Append("[TruncateRecordingRequest](sbeTemplateId="); builder.Append(TEMPLATE_ID); builder.Append("|sbeSchemaId="); builder.Append(SCHEMA_ID); builder.Append("|sbeSchemaVersion="); if (_parentMessage._actingVersion != SCHEMA_VERSION) { builder.Append(_parentMessage._actingVersion); builder.Append('/'); } builder.Append(SCHEMA_VERSION); builder.Append("|sbeBlockLength="); if (_actingBlockLength != BLOCK_LENGTH) { builder.Append(_actingBlockLength); builder.Append('/'); } builder.Append(BLOCK_LENGTH); builder.Append("):"); //Token{signal=BEGIN_FIELD, name='controlSessionId', referencedName='null', description='null', id=1, version=0, deprecated=0, encodedLength=0, offset=0, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=0, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("ControlSessionId="); builder.Append(ControlSessionId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='correlationId', referencedName='null', description='null', id=2, version=0, deprecated=0, encodedLength=0, offset=8, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=8, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("CorrelationId="); builder.Append(CorrelationId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='recordingId', referencedName='null', description='null', id=3, version=0, deprecated=0, encodedLength=0, offset=16, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=16, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("RecordingId="); builder.Append(RecordingId()); builder.Append('|'); //Token{signal=BEGIN_FIELD, name='position', referencedName='null', description='null', id=4, version=0, deprecated=0, encodedLength=0, offset=24, componentTokenCount=3, encoding=Encoding{presence=REQUIRED, primitiveType=null, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} //Token{signal=ENCODING, name='int64', referencedName='null', description='null', id=-1, version=0, deprecated=0, encodedLength=8, offset=24, componentTokenCount=1, encoding=Encoding{presence=REQUIRED, primitiveType=INT64, byteOrder=LITTLE_ENDIAN, minValue=null, maxValue=null, nullValue=null, constValue=null, characterEncoding='null', epoch='unix', timeUnit=nanosecond, semanticType='null'}} builder.Append("Position="); builder.Append(Position()); Limit(originalLimit); return builder; } } }
// // OssiferWebView.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright 2010 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Runtime.InteropServices; namespace Banshee.WebBrowser { public class OssiferWebView : Gtk.Widget { private delegate OssiferNavigationResponse MimeTypePolicyDecisionRequestedCallback (IntPtr ossifer, IntPtr mimetype); private delegate OssiferNavigationResponse NavigationPolicyDecisionRequestedCallback (IntPtr ossifer, IntPtr uri); private delegate IntPtr DownloadRequestedCallback (IntPtr ossifer, IntPtr mimetype, IntPtr uri, IntPtr suggested_filename); private delegate IntPtr ResourceRequestStartingCallback (IntPtr ossifer, IntPtr uri); private delegate void LoadStatusChangedCallback (IntPtr ossifer, OssiferLoadStatus status); private delegate void DownloadStatusChangedCallback (IntPtr ossifer, OssiferDownloadStatus status, IntPtr mimetype, IntPtr destnation_uri); [StructLayout (LayoutKind.Sequential)] private struct Callbacks { public MimeTypePolicyDecisionRequestedCallback MimeTypePolicyDecisionRequested; public NavigationPolicyDecisionRequestedCallback NavigationPolicyDecisionRequested; public DownloadRequestedCallback DownloadRequested; public ResourceRequestStartingCallback ResourceRequestStarting; public LoadStatusChangedCallback LoadStatusChanged; public DownloadStatusChangedCallback DownloadStatusChanged; } private const string LIBOSSIFER = "ossifer"; private Callbacks callbacks; public event EventHandler LoadStatusChanged; public event Action<float> ZoomChanged; [DllImport (LIBOSSIFER)] private static extern IntPtr ossifer_web_view_get_type (); public static new GLib.GType GType { get { return new GLib.GType (ossifer_web_view_get_type ()); } } protected OssiferWebView (IntPtr raw) : base (raw) { } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_set_callbacks (IntPtr ossifer, Callbacks callbacks); public OssiferWebView () { OssiferSession.Initialize (); CreateNativeObject (new string[0], new GLib.Value[0]); callbacks = new Callbacks () { MimeTypePolicyDecisionRequested = new MimeTypePolicyDecisionRequestedCallback (HandleMimeTypePolicyDecisionRequested), NavigationPolicyDecisionRequested = new NavigationPolicyDecisionRequestedCallback (HandleNavigationPolicyDecisionRequested), DownloadRequested = new DownloadRequestedCallback (HandleDownloadRequested), ResourceRequestStarting = new ResourceRequestStartingCallback (HandleResourceRequestStarting), LoadStatusChanged = new LoadStatusChangedCallback (HandleLoadStatusChanged), DownloadStatusChanged = new DownloadStatusChangedCallback (HandleDownloadStatusChanged) }; ossifer_web_view_set_callbacks (Handle, callbacks); } #region Callback Implementations private OssiferNavigationResponse HandleMimeTypePolicyDecisionRequested (IntPtr ossifer, IntPtr mimetype) { return OnMimeTypePolicyDecisionRequested (GLib.Marshaller.Utf8PtrToString (mimetype)); } protected virtual OssiferNavigationResponse OnMimeTypePolicyDecisionRequested (string mimetype) { return OssiferNavigationResponse.Unhandled; } private OssiferNavigationResponse HandleNavigationPolicyDecisionRequested (IntPtr ossifer, IntPtr uri) { return OnNavigationPolicyDecisionRequested (GLib.Marshaller.Utf8PtrToString (uri)); } protected virtual OssiferNavigationResponse OnNavigationPolicyDecisionRequested (string uri) { return OssiferNavigationResponse.Unhandled; } private IntPtr HandleDownloadRequested (IntPtr ossifer, IntPtr mimetype, IntPtr uri, IntPtr suggested_filename) { var destination_uri = OnDownloadRequested ( GLib.Marshaller.Utf8PtrToString (mimetype), GLib.Marshaller.Utf8PtrToString (uri), GLib.Marshaller.Utf8PtrToString (suggested_filename)); return destination_uri == null ? IntPtr.Zero : GLib.Marshaller.StringToPtrGStrdup (destination_uri); } protected virtual string OnDownloadRequested (string mimetype, string uri, string suggestedFilename) { return null; } private IntPtr HandleResourceRequestStarting (IntPtr ossifer, IntPtr old_uri) { string new_uri = OnResourceRequestStarting (GLib.Marshaller.Utf8PtrToString (old_uri)); return new_uri == null ? IntPtr.Zero : GLib.Marshaller.StringToPtrGStrdup (new_uri); } protected virtual string OnResourceRequestStarting (string old_uri) { return null; } private void HandleLoadStatusChanged (IntPtr ossifer, OssiferLoadStatus status) { OnLoadStatusChanged (status); } protected virtual void OnLoadStatusChanged (OssiferLoadStatus status) { var handler = LoadStatusChanged; if (handler != null) { handler (this, EventArgs.Empty); } } private void HandleDownloadStatusChanged (IntPtr ossifer, OssiferDownloadStatus status, IntPtr mimetype, IntPtr destinationUri) { OnDownloadStatusChanged (status, GLib.Marshaller.Utf8PtrToString (mimetype), GLib.Marshaller.Utf8PtrToString (destinationUri)); } protected virtual void OnDownloadStatusChanged (OssiferDownloadStatus status, string mimetype, string destinationUri) { } #endregion #region Public Instance API [DllImport (LIBOSSIFER)] private static extern IntPtr ossifer_web_view_load_uri (IntPtr ossifer, IntPtr uri); public void LoadUri (string uri) { var uri_raw = IntPtr.Zero; try { uri_raw = GLib.Marshaller.StringToPtrGStrdup (uri); ossifer_web_view_load_uri (Handle, uri_raw); } finally { GLib.Marshaller.Free (uri_raw); } } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_load_string (IntPtr ossifer, IntPtr content, IntPtr mimetype, IntPtr encoding, IntPtr base_uri); public void LoadString (string content, string mimetype, string encoding, string baseUri) { var content_raw = IntPtr.Zero; var mimetype_raw = IntPtr.Zero; var encoding_raw = IntPtr.Zero; var base_uri_raw = IntPtr.Zero; try { ossifer_web_view_load_string (Handle, content_raw = GLib.Marshaller.StringToPtrGStrdup (content), mimetype_raw = GLib.Marshaller.StringToPtrGStrdup (mimetype), encoding_raw = GLib.Marshaller.StringToPtrGStrdup (encoding), base_uri_raw = GLib.Marshaller.StringToPtrGStrdup (baseUri)); } finally { GLib.Marshaller.Free (content_raw); GLib.Marshaller.Free (mimetype_raw); GLib.Marshaller.Free (encoding_raw); GLib.Marshaller.Free (base_uri_raw); } } [DllImport (LIBOSSIFER)] private static extern bool ossifer_web_view_can_go_forward (IntPtr ossifer); public virtual bool CanGoForward { get { return ossifer_web_view_can_go_forward (Handle); } } [DllImport (LIBOSSIFER)] private static extern bool ossifer_web_view_can_go_back (IntPtr ossifer); public virtual bool CanGoBack { get { return ossifer_web_view_can_go_back (Handle); } } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_go_forward (IntPtr ossifer); public virtual void GoForward () { ossifer_web_view_go_forward (Handle); } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_go_back (IntPtr ossifer); public virtual void GoBack () { ossifer_web_view_go_back (Handle); } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_set_zoom (IntPtr ossifer, float zoomLevel); [DllImport (LIBOSSIFER)] private static extern float ossifer_web_view_get_zoom (IntPtr ossifer); public float Zoom { get { return ossifer_web_view_get_zoom (Handle); } set { ossifer_web_view_set_zoom (Handle, value); var handler = ZoomChanged; if (handler != null) { handler (value); } } } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_reload (IntPtr ossifer); [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_reload_bypass_cache (IntPtr ossifer); public virtual void Reload (bool bypassCache) { if (bypassCache) { ossifer_web_view_reload_bypass_cache (Handle); } else { ossifer_web_view_reload (Handle); } } public void Reload () { Reload (false); } [DllImport (LIBOSSIFER)] private static extern void ossifer_web_view_execute_script (IntPtr ossifer, IntPtr script); public void ExecuteScript (string script) { var script_raw = IntPtr.Zero; try { ossifer_web_view_execute_script (Handle, script_raw = GLib.Marshaller.StringToPtrGStrdup (script)); } finally { GLib.Marshaller.Free (script_raw); } } [DllImport (LIBOSSIFER)] private static extern IntPtr ossifer_web_view_get_uri (IntPtr ossifer); public virtual string Uri { get { return GLib.Marshaller.Utf8PtrToString (ossifer_web_view_get_uri (Handle)); } } [DllImport (LIBOSSIFER)] private static extern IntPtr ossifer_web_view_get_title (IntPtr ossifer); public virtual string Title { get { return GLib.Marshaller.Utf8PtrToString (ossifer_web_view_get_title (Handle)); } } [DllImport (LIBOSSIFER)] private static extern OssiferLoadStatus ossifer_web_view_get_load_status (IntPtr ossifer); public virtual OssiferLoadStatus LoadStatus { get { return ossifer_web_view_get_load_status (Handle); } } [DllImport (LIBOSSIFER)] private static extern OssiferSecurityLevel ossifer_web_view_get_security_level (IntPtr ossifer); public virtual OssiferSecurityLevel SecurityLevel { get { return ossifer_web_view_get_security_level (Handle); } } #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; /// <summary> /// Convert.ToBoolean(Double) /// Converts the value of the specified double float value to an equivalent Boolean value. /// </summary> public class ConvertToBoolean { public static int Main() { ConvertToBoolean testObj = new ConvertToBoolean(); TestLibrary.TestFramework.BeginTestCase("for method: Convert.ToBoolean(Double)"); if(testObj.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; return retVal; } #region Positive tests public bool PosTest1() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = TestLibrary.Generator.GetDouble(-55); TestLibrary.TestFramework.BeginScenario("PosTest1: Random double value between 0.0 and 1.0."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("001", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("002", errorDesc); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = double.MaxValue; TestLibrary.TestFramework.BeginScenario("PosTest2: value is double.MaxValue."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("003", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("004", errorDesc); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = double.MinValue; TestLibrary.TestFramework.BeginScenario("PosTest3: value is double.MinValue."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("005", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("006", errorDesc); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = double.Epsilon; TestLibrary.TestFramework.BeginScenario("PosTest4: value is double.Epsilon."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("007", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("008", errorDesc); retVal = false; } return retVal; } public bool PosTest5() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = -1 * TestLibrary.Generator.GetDouble(-55); TestLibrary.TestFramework.BeginScenario("PosTest5: Random double value between -0.0 and -1.0."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("009", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("010", errorDesc); retVal = false; } return retVal; } public bool PosTest6() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = double.NaN; TestLibrary.TestFramework.BeginScenario("PosTest6: value is double.NaN."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("011", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("012", errorDesc); retVal = false; } return retVal; } public bool PosTest7() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = double.NegativeInfinity; TestLibrary.TestFramework.BeginScenario("PosTest7: value is double.NegativeInfinity."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("013", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("014", errorDesc); retVal = false; } return retVal; } public bool PosTest8() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = double.PositiveInfinity; TestLibrary.TestFramework.BeginScenario("PosTest8: value is double.PositiveInfinity."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("015", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("016", errorDesc); retVal = false; } return retVal; } public bool PosTest9() { bool retVal = true; string errorDesc; double d; bool expectedValue; bool actualValue; d = -1 * double.Epsilon; TestLibrary.TestFramework.BeginScenario("PosTest9: value is negative double.Epsilon."); try { actualValue = Convert.ToBoolean(d); expectedValue = 0 != d; if (actualValue != expectedValue) { errorDesc = "The boolean value of double value " + d + " is not the value " + expectedValue + " as expected: actual(" + actualValue + ")"; TestLibrary.TestFramework.LogError("017", errorDesc); retVal = false; } } catch (Exception e) { errorDesc = "Unexpect exception:" + e; errorDesc += "\nThe double value is " + d; TestLibrary.TestFramework.LogError("018", errorDesc); retVal = false; } return retVal; } #endregion }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NPOI.SS; using NPOI.SS.UserModel; using NUnit.Framework; /** * Common superclass for testing implementatiosn of * {@link Comment} */ public class BaseTestCellComment { private ITestDataProvider _testDataProvider; public BaseTestCellComment() : this(TestCases.HSSF.HSSFITestDataProvider.Instance) {} protected BaseTestCellComment(ITestDataProvider testDataProvider) { _testDataProvider = testDataProvider; } [Test] public void TestFind() { IWorkbook book = _testDataProvider.CreateWorkbook(); ISheet sheet = book.CreateSheet(); Assert.IsNull(sheet.GetCellComment(0, 0)); IRow row = sheet.CreateRow(0); ICell cell = row.CreateCell(0); Assert.IsNull(sheet.GetCellComment(0, 0)); Assert.IsNull(cell.CellComment); } [Test] public void TestCreate() { String cellText = "Hello, World"; String commentText = "We can set comments in POI"; String commentAuthor = "Apache Software Foundation"; int cellRow = 3; int cellColumn = 1; IWorkbook wb = _testDataProvider.CreateWorkbook(); ICreationHelper factory = wb.GetCreationHelper(); ISheet sheet = wb.CreateSheet(); Assert.IsNull(sheet.GetCellComment(cellRow, cellColumn)); ICell cell = sheet.CreateRow(cellRow).CreateCell(cellColumn); cell.SetCellValue(factory.CreateRichTextString(cellText)); Assert.IsNull(cell.CellComment); Assert.IsNull(sheet.GetCellComment(cellRow, cellColumn)); IDrawing patr = sheet.CreateDrawingPatriarch(); IClientAnchor anchor = factory.CreateClientAnchor(); anchor.Col1=(2); anchor.Col2=(5); anchor.Row1=(1); anchor.Row2=(2); IComment comment = patr.CreateCellComment(anchor); Assert.IsFalse(comment.Visible); comment.Visible = (true); Assert.IsTrue(comment.Visible); IRichTextString string1 = factory.CreateRichTextString(commentText); comment.String=(string1); comment.Author=(commentAuthor); cell.CellComment=(comment); Assert.IsNotNull(cell.CellComment); Assert.IsNotNull(sheet.GetCellComment(cellRow, cellColumn)); //verify our Settings Assert.AreEqual(commentAuthor, comment.Author); Assert.AreEqual(commentText, comment.String.String); Assert.AreEqual(cellRow, comment.Row); Assert.AreEqual(cellColumn, comment.Column); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); cell = sheet.GetRow(cellRow).GetCell(cellColumn); comment = cell.CellComment; Assert.IsNotNull(comment); Assert.AreEqual(commentAuthor, comment.Author); Assert.AreEqual(commentText, comment.String.String); Assert.AreEqual(cellRow, comment.Row); Assert.AreEqual(cellColumn, comment.Column); Assert.IsTrue(comment.Visible); // Change slightly, and re-test comment.String = (factory.CreateRichTextString("New Comment Text")); comment.Visible = (false); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); cell = sheet.GetRow(cellRow).GetCell(cellColumn); comment = cell.CellComment; Assert.IsNotNull(comment); Assert.AreEqual(commentAuthor, comment.Author); Assert.AreEqual("New Comment Text", comment.String.String); Assert.AreEqual(cellRow, comment.Row); Assert.AreEqual(cellColumn, comment.Column); Assert.IsFalse(comment.Visible); } /** * test that we can read cell comments from an existing workbook. */ [Test] public void TestReadComments() { IWorkbook wb = _testDataProvider.OpenSampleWorkbook("SimpleWithComments." + _testDataProvider.StandardFileNameExtension); ISheet sheet = wb.GetSheetAt(0); ICell cell; IRow row; IComment comment; for (int rownum = 0; rownum < 3; rownum++) { row = sheet.GetRow(rownum); cell = row.GetCell(0); comment = cell.CellComment; Assert.IsNull(comment, "Cells in the first column are not commented"); Assert.IsNull(sheet.GetCellComment(rownum, 0)); } for (int rownum = 0; rownum < 3; rownum++) { row = sheet.GetRow(rownum); cell = row.GetCell(1); comment = cell.CellComment; Assert.IsNotNull(comment, "Cells in the second column have comments"); Assert.IsNotNull(sheet.GetCellComment(rownum, 1), "Cells in the second column have comments"); Assert.AreEqual("Yegor Kozlov", comment.Author); Assert.IsFalse(comment.String.String == string.Empty, "cells in the second column have not empyy notes"); Assert.AreEqual(rownum, comment.Row); Assert.AreEqual(cell.ColumnIndex, comment.Column); } } /** * test that we can modify existing cell comments */ [Test] public void TestModifyComments() { IWorkbook wb = _testDataProvider.OpenSampleWorkbook("SimpleWithComments." + _testDataProvider.StandardFileNameExtension); ICreationHelper factory = wb.GetCreationHelper(); ISheet sheet = wb.GetSheetAt(0); ICell cell; IRow row; IComment comment; for (int rownum = 0; rownum < 3; rownum++) { row = sheet.GetRow(rownum); cell = row.GetCell(1); comment = cell.CellComment; comment.Author = ("Mofified[" + rownum + "] by Yegor"); comment.String = (factory.CreateRichTextString("Modified comment at row " + rownum)); } wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); for (int rownum = 0; rownum < 3; rownum++) { row = sheet.GetRow(rownum); cell = row.GetCell(1); comment = cell.CellComment; Assert.AreEqual("Mofified[" + rownum + "] by Yegor", comment.Author); Assert.AreEqual("Modified comment at row " + rownum, comment.String.String); } } [Test] public void TestDeleteComments() { IWorkbook wb = _testDataProvider.OpenSampleWorkbook("SimpleWithComments." + _testDataProvider.StandardFileNameExtension); ISheet sheet = wb.GetSheetAt(0); // Zap from rows 1 and 3 Assert.IsNotNull(sheet.GetRow(0).GetCell(1).CellComment); Assert.IsNotNull(sheet.GetRow(1).GetCell(1).CellComment); Assert.IsNotNull(sheet.GetRow(2).GetCell(1).CellComment); sheet.GetRow(0).GetCell(1).RemoveCellComment(); sheet.GetRow(2).GetCell(1).CellComment = (null); // Check gone so far Assert.IsNull(sheet.GetRow(0).GetCell(1).CellComment); Assert.IsNotNull(sheet.GetRow(1).GetCell(1).CellComment); Assert.IsNull(sheet.GetRow(2).GetCell(1).CellComment); // Save and re-load wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); // Check Assert.IsNull(sheet.GetRow(0).GetCell(1).CellComment); Assert.IsNotNull(sheet.GetRow(1).GetCell(1).CellComment); Assert.IsNull(sheet.GetRow(2).GetCell(1).CellComment); } /** * code from the quick guide */ [Test] public void TestQuickGuide() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ICreationHelper factory = wb.GetCreationHelper(); ISheet sheet = wb.CreateSheet(); ICell cell = sheet.CreateRow(3).CreateCell(5); cell.SetCellValue("F4"); IDrawing drawing = sheet.CreateDrawingPatriarch(); IClientAnchor anchor = factory.CreateClientAnchor(); IComment comment = drawing.CreateCellComment(anchor); IRichTextString str = factory.CreateRichTextString("Hello, World!"); comment.String = (str); comment.Author = ("Apache POI"); //assign the comment to the cell cell.CellComment = (comment); wb = _testDataProvider.WriteOutAndReadBack(wb); sheet = wb.GetSheetAt(0); cell = sheet.GetRow(3).GetCell(5); comment = cell.CellComment; Assert.IsNotNull(comment); Assert.AreEqual("Hello, World!", comment.String.String); Assert.AreEqual("Apache POI", comment.Author); Assert.AreEqual(3, comment.Row); Assert.AreEqual(5, comment.Column); } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Net; using System.Reflection; using OpenMetaverse; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using System.Text; using System.IO; namespace OpenSim.Region.Framework.Scenes { public delegate void RestartSim(RegionInfo thisregion); public class SceneOwnerCounts { public string OwnerName; public int TotalObjects; public int TotalPrims; } /// <summary> /// Manager for adding, closing and restarting scenes. /// </summary> public class SceneManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public event RestartSim OnRestartSim; private readonly List<Scene> m_localScenes; private Scene m_currentScene = null; public List<Scene> Scenes { get { return m_localScenes; } } public Scene CurrentScene { get { return m_currentScene; } } public Scene CurrentOrFirstScene { get { if (m_currentScene == null) { if (m_localScenes.Count > 0) { return m_localScenes[0]; } else { return null; } } else { return m_currentScene; } } } public SceneManager() { m_localScenes = new List<Scene>(); } public void Close() { // collect known shared modules in sharedModules Dictionary<string, IRegionModule> sharedModules = new Dictionary<string, IRegionModule>(); for (int i = 0; i < m_localScenes.Count; i++) { // extract known shared modules from scene foreach (string k in m_localScenes[i].Modules.Keys) { if (m_localScenes[i].Modules[k].IsSharedModule && !sharedModules.ContainsKey(k)) sharedModules[k] = m_localScenes[i].Modules[k]; } // close scene/region m_localScenes[i].Close(); } // all regions/scenes are now closed, we can now safely // close all shared modules foreach (IRegionModule mod in sharedModules.Values) { mod.Close(); } } public void Close(Scene cscene) { if (m_localScenes.Contains(cscene)) { for (int i = 0; i < m_localScenes.Count; i++) { if (m_localScenes[i].Equals(cscene)) { m_localScenes[i].Close(); } } } } public void Add(Scene scene) { scene.OnRestart += HandleRestart; m_localScenes.Add(scene); } public void HandleRestart(RegionInfo rdata) { m_log.Error("[SCENEMANAGER]: Got Restart message for region:" + rdata.RegionName + " Sending up to main"); int RegionSceneElement = -1; for (int i = 0; i < m_localScenes.Count; i++) { if (rdata.RegionName == m_localScenes[i].RegionInfo.RegionName) { RegionSceneElement = i; } } // Now we make sure the region is no longer known about by the SceneManager // Prevents duplicates. if (RegionSceneElement >= 0) { m_localScenes.RemoveAt(RegionSceneElement); } // Send signal to main that we're restarting this sim. OnRestartSim(rdata); } public void SendSimOnlineNotification(ulong regionHandle) { RegionInfo Result = null; for (int i = 0; i < m_localScenes.Count; i++) { if (m_localScenes[i].RegionInfo.RegionHandle == regionHandle) { // Inform other regions to tell their avatar about me Result = m_localScenes[i].RegionInfo; } } if (Result != null) { for (int i = 0; i < m_localScenes.Count; i++) { if (m_localScenes[i].RegionInfo.RegionHandle != regionHandle) { // Inform other regions to tell their avatar about me //m_localScenes[i].OtherRegionUp(Result); } } } else { m_log.Error("[REGION]: Unable to notify Other regions of this Region coming up"); } } /// <summary> /// Save the prims in the current scene to an xml file in OpenSimulator's original 'xml' format /// </summary> /// <param name="filename"></param> public void SaveCurrentSceneToXml(string filename) { IRegionSerializerModule serializer = CurrentOrFirstScene.RequestModuleInterface<IRegionSerializerModule>(); if (serializer != null) serializer.SavePrimsToXml(CurrentOrFirstScene, filename); } /// <summary> /// Load an xml file of prims in OpenSimulator's original 'xml' file format to the current scene /// </summary> /// <param name="filename"></param> /// <param name="generateNewIDs"></param> /// <param name="loadOffset"></param> public void LoadCurrentSceneFromXml(string filename, bool generateNewIDs, Vector3 loadOffset) { IRegionSerializerModule serializer = CurrentOrFirstScene.RequestModuleInterface<IRegionSerializerModule>(); if (serializer != null) serializer.LoadPrimsFromXml(CurrentOrFirstScene, filename, generateNewIDs, loadOffset); } /// <summary> /// Save the prims in the current scene to an xml file in OpenSimulator's current 'xml2' format /// </summary> /// <param name="filename"></param> public void SaveCurrentSceneToXml2(string filename) { IRegionSerializerModule serializer = CurrentOrFirstScene.RequestModuleInterface<IRegionSerializerModule>(); if (serializer != null) serializer.SavePrimsToXml2(CurrentOrFirstScene, filename); } public void SaveNamedPrimsToXml2(string primName, string filename) { IRegionSerializerModule serializer = CurrentOrFirstScene.RequestModuleInterface<IRegionSerializerModule>(); if (serializer != null) serializer.SaveNamedPrimsToXml2(CurrentOrFirstScene, primName, filename); } /// <summary> /// Load an xml file of prims in OpenSimulator's current 'xml2' file format to the current scene /// </summary> public void LoadCurrentSceneFromXml2(string filename) { IRegionSerializerModule serializer = CurrentOrFirstScene.RequestModuleInterface<IRegionSerializerModule>(); if (serializer != null) serializer.LoadPrimsFromXml2(CurrentOrFirstScene, filename); } /// <summary> /// Load an xml file of prims in OpenSimulator's current 'xml2' file format to the current scene /// </summary> /// <summary> /// Scans objects in an OAR file for creator IDs to save for assets. /// </summary> /// <param name="fileName"></param> /// <param name="saveCreators">true to save in database</param> public void ScanSceneForCreators(string filename) { IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.ScanArchiveForAssetCreatorIDs(filename); } /// <summary> /// Save the current scene to an OpenSimulator archive. This archive will eventually include the prim's assets /// as well as the details of the prims themselves. /// </summary> /// <param name="filename"></param> public void SaveCurrentSceneToArchive(string filename, bool storeAssets) { IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.ArchiveRegion(filename, storeAssets); } /// <summary> /// Sets the debug level on loading or scanning an OpenSim archive. /// </summary> /// <param name="level"></param> public void SetOARDebug(int level) { IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.SetDebug(level); } /// <summary> /// Load an OpenSim archive into the current scene. This will load both the shapes of the prims and upload /// their assets to the asset service. /// </summary> /// <param name="filename"></param> public void LoadArchiveToCurrentScene(string filename, bool allowUserReassignment, bool ignoreErrors, HashSet<UUID> allowedUUIDs) { IRegionArchiverModule archiver = CurrentOrFirstScene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) archiver.DearchiveRegion(filename, allowUserReassignment, ignoreErrors, allowedUUIDs); } public string SaveCurrentSceneMapToXmlString() { return CurrentOrFirstScene.Heightmap.SaveToXmlString(); } public void LoadCurrenSceneMapFromXmlString(string mapData) { CurrentOrFirstScene.Heightmap.LoadFromXmlString(mapData); } public void SendCommandToPluginModules(string[] cmdparams) { ForEachCurrentScene(delegate(Scene scene) { scene.SendCommandToPlugins(cmdparams); }); } public void SetBypassPermissionsOnCurrentScene(bool bypassPermissions) { ForEachCurrentScene(delegate(Scene scene) { scene.Permissions.SetBypassPermissions(bypassPermissions); }); } private void ForEachCurrentScene(Action<Scene> func) { if (m_currentScene == null) { m_localScenes.ForEach(func); } else { func(m_currentScene); } } public void RestartCurrentScene() { ForEachCurrentScene(delegate(Scene scene) { scene.RestartNow(); }); } public void BackupCurrentScene() { ForEachCurrentScene(delegate(Scene scene) { scene.Backup(true); }); } public bool TrySetCurrentScene(string regionName) { if ((String.Compare(regionName, "root") == 0) || (String.Compare(regionName, "..") == 0) || (String.Compare(regionName, "/") == 0)) { m_currentScene = null; return true; } else { foreach (Scene scene in m_localScenes) { if (String.Compare(scene.RegionInfo.RegionName, regionName, true) == 0) { m_currentScene = scene; return true; } } return false; } } public bool TrySetCurrentScene(UUID regionID) { m_log.Debug("Searching for Region: '" + regionID + "'"); foreach (Scene scene in m_localScenes) { if (scene.RegionInfo.RegionID == regionID) { m_currentScene = scene; return true; } } return false; } public bool TryGetScene(string regionName, out Scene scene) { foreach (Scene mscene in m_localScenes) { if (String.Compare(mscene.RegionInfo.RegionName, regionName, true) == 0) { scene = mscene; return true; } } scene = null; return false; } public bool TryGetScene(UUID regionID, out Scene scene) { foreach (Scene mscene in m_localScenes) { if (mscene.RegionInfo.RegionID == regionID) { scene = mscene; return true; } } scene = null; return false; } public bool TryGetScene(uint locX, uint locY, out Scene scene) { foreach (Scene mscene in m_localScenes) { if (mscene.RegionInfo.RegionLocX == locX && mscene.RegionInfo.RegionLocY == locY) { scene = mscene; return true; } } scene = null; return false; } public bool TryGetScene(IPEndPoint ipEndPoint, out Scene scene) { foreach (Scene mscene in m_localScenes) { if ((mscene.RegionInfo.InternalEndPoint.Equals(ipEndPoint.Address)) && (mscene.RegionInfo.InternalEndPoint.Port == ipEndPoint.Port)) { scene = mscene; return true; } } scene = null; return false; } /// <summary> /// Set the debug packet level on the current scene. This level governs which packets are printed out to the /// console. /// </summary> /// <param name="newDebug"></param> public void SetDebugPacketLevelOnCurrentScene(int newDebug) { ForEachCurrentScene(delegate(Scene scene) { List<ScenePresence> scenePresences = scene.GetScenePresences(); foreach (ScenePresence scenePresence in scenePresences) { //if (!scenePresence.IsChildAgent) //{ m_log.ErrorFormat("Packet debug for {0} {1} set to {2}", scenePresence.Firstname, scenePresence.Lastname, newDebug); scenePresence.ControllingClient.SetDebugPacketLevel(newDebug); //} } }); } /// <summary> /// Set the debug crossings level on the current scene(s). This level governs the level of debug info printed out to the /// console during a crossing. /// </summary> /// <param name="newDebug"></param> public void SetDebugCrossingsLevelOnCurrentScene(int newDebug) { ForEachCurrentScene(delegate(Scene scene) { m_log.ErrorFormat("Crossings debug for {0} set to {1}", scene.RegionInfo.RegionName, newDebug.ToString()); scene.DebugCrossingsLevel = newDebug; }); } public List<ScenePresence> GetCurrentSceneAvatars() { List<ScenePresence> avatars = new List<ScenePresence>(); ForEachCurrentScene(delegate(Scene scene) { List<ScenePresence> scenePresences = scene.GetScenePresences(); foreach (ScenePresence scenePresence in scenePresences) { if (!scenePresence.IsChildAgent) { avatars.Add(scenePresence); } } }); return avatars; } public Dictionary<UUID,SceneOwnerCounts> GetCurrentSceneOwnerCounts() { Dictionary<UUID,SceneOwnerCounts> SOGTable = new Dictionary<UUID,SceneOwnerCounts>(); foreach (Scene scene in m_localScenes) { List<EntityBase> EntityList = scene.GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { SceneObjectGroup SOG = (SceneObjectGroup)ent; if (SOGTable.ContainsKey(SOG.OwnerID)) { SceneOwnerCounts counts = SOGTable[SOG.OwnerID]; counts.TotalObjects++; counts.TotalPrims += SOG.LandImpact; SOGTable[SOG.OwnerID] = counts; } else { SceneOwnerCounts counts = new SceneOwnerCounts(); UserProfileData profile = scene.CommsManager.UserService.GetUserProfile(SOG.OwnerID); if (profile == null) counts.OwnerName = "(Group-deeded, or unknown user)"; else counts.OwnerName = profile.Name; counts.TotalObjects = 1; counts.TotalPrims = SOG.LandImpact; SOGTable[SOG.OwnerID] = counts; } } } } return SOGTable; } private bool nukeRunning = false; public void NukeObjectsOwnedBy(UUID OwnerID) { if (nukeRunning) return; try { nukeRunning = true; foreach (Scene scene in m_localScenes) { // first disable physics to ensure CPU is available bool usePhysics = scene.PhysicsScene.Simulating; scene.PhysicsScene.Simulating = false; // anti-griefer: stop further rezzing including attaches. scene.AddBadUser(OwnerID); // lasts 1 hour try { List<EntityBase> EntityList = scene.GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { SceneObjectGroup SOG = (SceneObjectGroup)ent; // Allow UUID.Zero to represent a wildcard for all owners. if ((OwnerID == SOG.OwnerID) || ((OwnerID == UUID.Zero) && !SOG.IsAttachment)) scene.DeleteSceneObject(SOG, false, false, true); } } } finally { // don't force a region restart to reenable... and restore physics scene.PhysicsScene.Simulating = usePhysics; } } } finally { nukeRunning = false; } } private bool blacklistRunning = false; public enum BlacklistOp : int { Owner, Creator, Name, User, Remove, Clear, Show }; public void BlacklistOperation(BlacklistOp operation, string param, string param2) { if (blacklistRunning) return; // In cases where both are supported, if targetName is empty, targetID is used. string targetName = param; UUID targetID = UUID.Zero; try { blacklistRunning = true; bool nukeObjects; // BlacklistTarget.User is like BlacklistTarget.Owner except that it also prevents the user from entering the region. switch (operation) { case BlacklistOp.User: case BlacklistOp.Owner: // accepts either UUID or First Last if (String.IsNullOrEmpty(param2)) { if (!UUID.TryParse(param, out targetID)) { m_log.Warn("You must specify either a UUID or name (First Last)."); return; } } else { // name was specified UserProfileData profile = m_localScenes[0].CommsManager.UserService.GetUserProfile(param, param2); if (profile == null) { m_log.WarnFormat("Could not find a user named '{0} {1}'.", param, param2); return; } targetID = profile.ID; } nukeObjects = true; break; case BlacklistOp.Creator: if (!UUID.TryParse(param, out targetID)) { m_log.Warn("That command requires a UUID."); return; } nukeObjects = true; break; case BlacklistOp.Name: targetName = param.Trim(); nukeObjects = true; break; case BlacklistOp.Remove: if (UUID.TryParse(param, out targetID)) { targetName = String.Empty; } else { targetID = UUID.Zero; } nukeObjects = false; break; case BlacklistOp.Clear: case BlacklistOp.Show: // nothing to parse nukeObjects = false; break; default: return; } foreach (Scene scene in m_localScenes) { if (operation == BlacklistOp.Show) { scene.BlacklistShow(); return; } switch (operation) { case BlacklistOp.Creator: scene.AddBlacklistedCreator(targetID); break; case BlacklistOp.Owner: scene.AddBlacklistedOwner(targetID); // also temporarily stop further rezzing including attaches. scene.AddBadUser(targetID); break; case BlacklistOp.Name: scene.AddBlacklistedName(targetName); break; case BlacklistOp.User: scene.AddBlacklistedUser(targetID); break; case BlacklistOp.Remove: if (!String.IsNullOrEmpty(targetName)) scene.BlacklistRemove(targetName); else scene.BlacklistRemove(targetID); break; case BlacklistOp.Clear: scene.BlacklistClear(); break; } if (nukeObjects) { // first disable physics to ensure CPU is available bool usePhysics = scene.PhysicsScene.Simulating; scene.PhysicsScene.Simulating = false; try { List<EntityBase> EntityList = scene.GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { SceneObjectGroup SOG = (SceneObjectGroup)ent; bool match = false; switch (operation) { case BlacklistOp.Creator: SOG.ForEachPart(delegate(SceneObjectPart part) { match |= (part.CreatorID == targetID); }); break; case BlacklistOp.Owner: case BlacklistOp.User: match = (SOG.OwnerID == targetID); break; case BlacklistOp.Name: match = SOG.Name.Trim().StartsWith(targetName, StringComparison.InvariantCultureIgnoreCase); break; } if (match) scene.DeleteSceneObject(SOG, false, false, true); } } } finally { // don't force a region restart to reenable... and restore physics scene.PhysicsScene.Simulating = usePhysics; } } } } finally { blacklistRunning = false; } } private string SimpleLocation(Scene scene, SceneObjectPart part) { int x = (int)part.AbsolutePosition.X; int y = (int)part.AbsolutePosition.Y; int z = (int)part.AbsolutePosition.Z; return scene.RegionInfo.RegionName + "/" + x.ToString() + "/" + y.ToString() + "/" + z.ToString(); } private void DumpPart(Scene scene, SceneObjectPart part) { if (part.ParentID == 0) { m_log.InfoFormat("[Show]: Object {0} [{1}] '{2}' at {3}", part.LocalId.ToString(), part.UUID.ToString(), part.Name, SimpleLocation(scene, part)); } else { SceneObjectPart root = part.ParentGroup.RootPart; m_log.InfoFormat("[Show]: Child prim {0} [{1}] '{2}' at {3}", part.LocalId.ToString(), part.UUID.ToString(), part.Name, SimpleLocation(scene, part)); m_log.InfoFormat("[Show]: Root prim {0} [{1}] '{2}' at {3}", root.LocalId.ToString(), root.UUID.ToString(), root.Name, SimpleLocation(scene, root)); } } public void ShowObject(string[] showParams) { if (showParams.Length > 1) { string arg = showParams[1]; UUID uuid = UUID.Zero; uint localID = 0; if (UUID.TryParse(arg, out uuid)) { foreach (Scene scene in m_localScenes) { SceneObjectPart part = scene.GetSceneObjectPart(uuid); if (part != null) { DumpPart(scene, part); return; } } m_log.InfoFormat("Error: Could not find an part with UUID: {0}", uuid.ToString()); return; } if (uint.TryParse(arg, out localID)) { foreach (Scene scene in m_localScenes) { SceneObjectPart part = scene.GetSceneObjectPart(localID); if (part != null) { DumpPart(scene, part); return; } } m_log.InfoFormat("Error: Could not find an part with local ID: {0}", localID.ToString()); return; } } m_log.Info("Error: expected either a UUID or a local ID for an object."); } public List<ScenePresence> GetCurrentScenePresences() { List<ScenePresence> presences = new List<ScenePresence>(); ForEachCurrentScene(delegate(Scene scene) { List<ScenePresence> scenePresences = scene.GetScenePresences(); presences.AddRange(scenePresences); }); return presences; } public RegionInfo GetRegionInfo(ulong regionHandle) { foreach (Scene scene in m_localScenes) { if (scene.RegionInfo.RegionHandle == regionHandle) { return scene.RegionInfo; } } return null; } public void ForceCurrentSceneClientUpdate() { ForEachCurrentScene(delegate(Scene scene) { scene.ForceClientUpdate(); }); } public void HandleEditCommandOnCurrentScene(string[] cmdparams) { ForEachCurrentScene(delegate(Scene scene) { scene.HandleEditCommand(cmdparams); }); } public bool TryGetAvatar(UUID avatarId, out ScenePresence avatar) { foreach (Scene scene in m_localScenes) { if (scene.TryGetAvatar(avatarId, out avatar)) { return true; } } avatar = null; return false; } public bool TryGetAvatarsScene(UUID avatarId, out Scene scene) { ScenePresence avatar = null; foreach (Scene mScene in m_localScenes) { if (mScene.TryGetAvatar(avatarId, out avatar)) { scene = mScene; return true; } } scene = null; return false; } public void CloseScene(Scene scene) { m_localScenes.Remove(scene); scene.Close(); } public bool TryGetAvatarByName(string avatarName, out ScenePresence avatar) { foreach (Scene scene in m_localScenes) { if (scene.TryGetAvatarByName(avatarName, out avatar)) { return true; } } avatar = null; return false; } public void ForEachScene(Action<Scene> action) { m_localScenes.ForEach(action); } public void CacheJ2kDecode(int threads) { if (threads < 1) threads = 1; IJ2KDecoder m_decoder = m_localScenes[0].RequestModuleInterface<IJ2KDecoder>(); List<UUID> assetRequestList = new List<UUID>(); #region AssetGathering! foreach (Scene scene in m_localScenes) { List<EntityBase> entitles = scene.GetEntities(); foreach (EntityBase entity in entitles) { if (entity is SceneObjectGroup) { SceneObjectGroup sog = (SceneObjectGroup) entity; foreach (SceneObjectPart part in sog.GetParts()) { if (part.Shape != null) { OpenMetaverse.Primitive.TextureEntry te = part.Shape.Textures; if (te.DefaultTexture != null) // this has been null for some reason... { if (te.DefaultTexture.TextureID != UUID.Zero) assetRequestList.Add(te.DefaultTexture.TextureID); } for (int i=0; i<te.FaceTextures.Length; i++) { if (te.FaceTextures[i] != null) { if (te.FaceTextures[i].TextureID != UUID.Zero) { assetRequestList.Add(te.FaceTextures[i].TextureID); } } } if (part.Shape.SculptTexture != UUID.Zero) { assetRequestList.Add(part.Shape.SculptTexture); } } } } } } #endregion int entries_per_thread = (assetRequestList.Count / threads) + 1; UUID[] arrAssetRequestList = assetRequestList.ToArray(); List<UUID[]> arrvalus = new List<UUID[]>(); //split into separate arrays for (int j = 0; j < threads; j++) { List<UUID> val = new List<UUID>(); for (int k = j * entries_per_thread; k < ((j + 1) * entries_per_thread); k++) { if (k < arrAssetRequestList.Length) { val.Add(arrAssetRequestList[k]); } } arrvalus.Add(val.ToArray()); } for (int l = 0; l < arrvalus.Count; l++) { DecodeThreadContents threadworkItem = new DecodeThreadContents(); threadworkItem.sn = m_localScenes[0]; threadworkItem.j2kdecode = m_decoder; threadworkItem.arrassets = arrvalus[l]; System.Threading.Thread decodethread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(threadworkItem.run)); threadworkItem.SetThread(decodethread); decodethread.Priority = System.Threading.ThreadPriority.Lowest; decodethread.Name = "J2kCacheDecodeThread_" + l + 1; ThreadTracker.Add(decodethread); decodethread.Start(); } } public void ShowCollisions(string[] showParams) { foreach (Scene scene in m_localScenes) { scene.PhysicsScene.DumpCollisionInfo(); } } public void ShowUpdates(string[] showParams) { if (showParams.Length != 2) { m_log.InfoFormat("Usage: show updates [delta/total]"); return; } ForEachScene(delegate(Scene scene) { m_log.Info(scene.GetTopUpdatesOutput(showParams)); }); } private bool HasScriptEngine(Scene scene) { IScriptModule[] engines = scene.RequestModuleInterfaces<IScriptModule>(); if (engines.Length == 0) return false; if (engines[0] == null) // happens under Phlox if disabled return false; return true; } public void SaveExplicitOar(string regionName, string oarFilename, bool storeAssets) { Scene targetScene = this.FindSceneByName(regionName); if (targetScene == null) throw new Exception(String.Format("Region {0} was not found", regionName)); if (!HasScriptEngine(targetScene)) m_log.Warn("[SCENE]: Warning: Script engine disabled. No script states will be saved in OAR file."); IRegionArchiverModule archiver = targetScene.RequestModuleInterface<IRegionArchiverModule>(); if (archiver != null) { try { archiver.ArchiveRegion(oarFilename, storeAssets); //create a file for external code to know we're done writing this OAR //cheap and fragile IPC, but Im not yet taking the time to allow interaction //by anything but the console. using (FileStream completedfile = System.IO.File.Create(OarStatusNameFromRegionName(regionName))) { completedfile.WriteByte(1); completedfile.Close(); } } catch (Exception e) { using (FileStream completedfile = System.IO.File.Create(OarStatusNameFromRegionName(regionName))) { completedfile.WriteByte(0); byte[] errorMessage = System.Text.Encoding.UTF8.GetBytes(e.Message); completedfile.Write(errorMessage, 0, errorMessage.Length); completedfile.Close(); } throw; } } } private static string OarStatusNameFromRegionName(string regionName) { return regionName.Replace(" ", String.Empty).Replace("\'", String.Empty) + ".oarstatus"; } public Scene FindSceneByName(string name) { Scene targetScene = null; this.ForEachScene( delegate(Scene scene) { if (scene.RegionInfo.RegionName == name) { targetScene = scene; } } ); return targetScene; } } public class DecodeThreadContents { public Scene sn; public UUID[] arrassets; public IJ2KDecoder j2kdecode; private System.Threading.Thread thisthread; public void run( object o) { for (int i=0;i<arrassets.Length;i++) { AssetBase ab = sn.CommsManager.AssetCache.GetAsset(arrassets[i], AssetRequestInfo.InternalRequest()); if (ab != null && ab.Data != null) { j2kdecode.Decode(arrassets[i], ab.Data); } } ThreadTracker.Remove(thisthread); } public void SetThread(System.Threading.Thread thr) { thisthread = thr; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml; using Xunit; public static class XmlDictionaryWriterTest { [Fact] public static void XmlBaseWriter_WriteBase64Async() { string actual; int byteSize = 1024; byte[] bytes = GetByteArray(byteSize); string expect = GetExpectString(bytes, byteSize); using (var ms = new AsyncMemoryStream()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartDocument(); writer.WriteStartElement("data"); var task = writer.WriteBase64Async(bytes, 0, byteSize); task.Wait(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); ms.Position = 0; var sr = new StreamReader(ms); actual = sr.ReadToEnd(); } Assert.StrictEqual(expect, actual); } [Fact] public static void XmlBaseWriter_WriteBinHex() { var str = "The quick brown fox jumps over the lazy dog."; var bytes = Encoding.Unicode.GetBytes(str); string expect = @"<data>540068006500200071007500690063006B002000620072006F0077006E00200066006F00780020006A0075006D007000730020006F00760065007200200074006800650020006C0061007A007900200064006F0067002E00</data>"; string actual; using (var ms = new MemoryStream()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartElement("data"); writer.WriteBinHex(bytes, 0, bytes.Length); writer.WriteEndElement(); writer.Flush(); ms.Position = 0; var sr = new StreamReader(ms); actual = sr.ReadToEnd(); } Assert.StrictEqual(expect, actual); } [Fact] public static void XmlBaseWriter_FlushAsync() { string actual = null; int byteSize = 1024; byte[] bytes = GetByteArray(byteSize); string expect = GetExpectString(bytes, byteSize); string lastCompletedOperation = null; try { using (var ms = new AsyncMemoryStream()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); lastCompletedOperation = "XmlDictionaryWriter.CreateTextWriter()"; writer.WriteStartDocument(); lastCompletedOperation = "writer.WriteStartDocument()"; writer.WriteStartElement("data"); lastCompletedOperation = "writer.WriteStartElement()"; writer.WriteBase64(bytes, 0, byteSize); lastCompletedOperation = "writer.WriteBase64()"; writer.WriteEndElement(); lastCompletedOperation = "writer.WriteEndElement()"; writer.WriteEndDocument(); lastCompletedOperation = "writer.WriteEndDocument()"; var task = writer.FlushAsync(); lastCompletedOperation = "writer.FlushAsync()"; task.Wait(); ms.Position = 0; var sr = new StreamReader(ms); actual = sr.ReadToEnd(); } } catch(Exception e) { var sb = new StringBuilder(); sb.AppendLine($"An error occurred: {e.Message}"); sb.AppendLine(e.StackTrace); sb.AppendLine(); sb.AppendLine($"The last completed operation before the exception was: {lastCompletedOperation}"); Assert.True(false, sb.ToString()); } Assert.StrictEqual(expect, actual); } [Fact] public static void XmlBaseWriter_WriteStartEndElementAsync() { string actual; int byteSize = 1024; byte[] bytes = GetByteArray(byteSize); string expect = GetExpectString(bytes, byteSize); using (var ms = new AsyncMemoryStream()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartDocument(); // NOTE: the async method has only one overload that takes 3 params var t1 = writer.WriteStartElementAsync(null, "data", null); t1.Wait(); writer.WriteBase64(bytes, 0, byteSize); var t2 = writer.WriteEndElementAsync(); t2.Wait(); writer.WriteEndDocument(); writer.Flush(); ms.Position = 0; var sr = new StreamReader(ms); actual = sr.ReadToEnd(); } Assert.StrictEqual(expect, actual); } [Fact] public static void XmlBaseWriter_CheckAsync_ThrowInvalidOperationException() { int byteSize = 1024; byte[] bytes = GetByteArray(byteSize); using (var ms = new MemoryStreamWithBlockAsync()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartDocument(); writer.WriteStartElement("data"); ms.blockAsync(true); var t1 = writer.WriteBase64Async(bytes, 0, byteSize); var t2 = Assert.ThrowsAsync<InvalidOperationException>(() => writer.WriteBase64Async(bytes, 0, byteSize)); InvalidOperationException e = t2.Result; bool isAsyncIsRunningException = e.Message.Contains("XmlAsyncIsRunningException") || e.Message.Contains("in progress"); Assert.True(isAsyncIsRunningException, "The exception is not XmlAsyncIsRunningException."); // let the first task complete ms.blockAsync(false); t1.Wait(); } } [Fact] public static void XmlDictionaryWriter_InvalidUnicodeChar() { using (var ms = new MemoryStream()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartDocument(); writer.WriteStartElement("data"); // This is an invalid char. Writing this char shouldn't // throw exception. writer.WriteString("\uDB1B"); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); ms.Position = 0; } } [Fact] public static void CreateMtomReaderWriter_Throw_PNSE() { using (var stream = new MemoryStream()) { string startInfo = "application/soap+xml"; Assert.Throws<PlatformNotSupportedException>(() => XmlDictionaryWriter.CreateMtomWriter(stream, Encoding.UTF8, int.MaxValue, startInfo)); } } [Fact] public static void CreateTextReaderWriterTest() { string expected = "<localName>the value</localName>"; using (MemoryStream stream = new MemoryStream()) { using (XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false)) { writer.WriteElementString("localName", "the value"); writer.Flush(); byte[] bytes = stream.ToArray(); StreamReader reader = new StreamReader(stream); stream.Position = 0; string content = reader.ReadToEnd(); Assert.Equal(expected, content); reader.Close(); using (XmlDictionaryReader xreader = XmlDictionaryReader.CreateTextReader(bytes, new XmlDictionaryReaderQuotas())) { xreader.Read(); string xml = xreader.ReadOuterXml(); Assert.Equal(expected, xml); } } } } [Fact] public static void StreamProvoiderTest() { List<string> ReaderWriterType = new List<string> { "Binary", //"MTOM", //MTOM methods not supported now. //"MTOM", //"MTOM", "Text", "Text", "Text" }; List<string> Encodings = new List<string> { "utf-8", "utf-8", "utf-16", "unicodeFFFE", "utf-8", "utf-16", "unicodeFFFE" }; for (int i = 0; i < ReaderWriterType.Count; i++) { string rwTypeStr = ReaderWriterType[i]; ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType) Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true); Encoding encoding = Encoding.GetEncoding(Encodings[i]); Random rndGen = new Random(); int byteArrayLength = rndGen.Next(100, 2000); byte[] byteArray = new byte[byteArrayLength]; rndGen.NextBytes(byteArray); MyStreamProvider myStreamProvider = new MyStreamProvider(new MemoryStream(byteArray)); bool success = false; bool successBase64 = false; MemoryStream ms = new MemoryStream(); success = WriteTest(ms, rwType, encoding, myStreamProvider); Assert.True(success); success = ReadTest(ms, encoding, rwType, byteArray); Assert.True(success); if (rwType == ReaderWriterFactory.ReaderWriterType.Text) { ms = new MemoryStream(); myStreamProvider = new MyStreamProvider(new MemoryStream(byteArray)); success = AsyncWriteTest(ms, encoding, myStreamProvider); Assert.True(success); successBase64 = AsyncWriteBase64Test(ms, byteArray, encoding, myStreamProvider); Assert.True(successBase64); } } } [Fact] public static void IXmlBinaryReaderWriterInitializerTest() { DataContractSerializer serializer = new DataContractSerializer(typeof(TestData)); MemoryStream ms = new MemoryStream(); TestData td = new TestData(); XmlDictionaryWriter binaryWriter = XmlDictionaryWriter.CreateBinaryWriter(ms, null, null, false); IXmlBinaryWriterInitializer writerInitializer = (IXmlBinaryWriterInitializer)binaryWriter; writerInitializer.SetOutput(ms, null, null, false); serializer.WriteObject(ms, td); binaryWriter.Flush(); byte[] xmlDoc = ms.ToArray(); binaryWriter.Close(); XmlDictionaryReader binaryReader = XmlDictionaryReader.CreateBinaryReader(xmlDoc, 0, xmlDoc.Length, null, XmlDictionaryReaderQuotas.Max, null, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { })); IXmlBinaryReaderInitializer readerInitializer = (IXmlBinaryReaderInitializer)binaryReader; readerInitializer.SetInput(xmlDoc, 0, xmlDoc.Length, null, XmlDictionaryReaderQuotas.Max, null, new OnXmlDictionaryReaderClose((XmlDictionaryReader reader) => { })); binaryReader.ReadContentAsObject(); binaryReader.Close(); } [Fact] public static void IXmlTextReaderInitializerTest() { var writer = new SampleTextWriter(); var ms = new MemoryStream(); var encoding = Encoding.UTF8; writer.SetOutput(ms, encoding, true); } [Fact] public static void FragmentTest() { string rwTypeStr = "Text"; ReaderWriterFactory.ReaderWriterType rwType = (ReaderWriterFactory.ReaderWriterType) Enum.Parse(typeof(ReaderWriterFactory.ReaderWriterType), rwTypeStr, true); Encoding encoding = Encoding.GetEncoding("utf-8"); MemoryStream ms = new MemoryStream(); XmlDictionaryWriter writer = (XmlDictionaryWriter)ReaderWriterFactory.CreateXmlWriter(rwType, ms, encoding); Assert.False(FragmentHelper.CanFragment(writer)); } private static bool ReadTest(MemoryStream ms, Encoding encoding, ReaderWriterFactory.ReaderWriterType rwType, byte[] byteArray) { ms.Position = 0; XmlDictionaryReader reader = (XmlDictionaryReader)ReaderWriterFactory.CreateXmlReader(rwType, ms, encoding); reader.ReadToDescendant("Root"); byte[] bytesFromReader = reader.ReadElementContentAsBase64(); if (bytesFromReader.Length != byteArray.Length) { return false; } else { for (int i = 0; i < byteArray.Length; i++) { if (byteArray[i] != bytesFromReader[i]) { return false; } } } return true; } static bool WriteTest(MemoryStream ms, ReaderWriterFactory.ReaderWriterType rwType, Encoding encoding, MyStreamProvider myStreamProvider) { XmlWriter writer = ReaderWriterFactory.CreateXmlWriter(rwType, ms, encoding); XmlDictionaryWriter writeD = writer as XmlDictionaryWriter; writeD.WriteStartElement("Root"); writeD.WriteValue(myStreamProvider); if (rwType != ReaderWriterFactory.ReaderWriterType.MTOM) { // stream should be released right after WriteValue Assert.True(myStreamProvider.StreamReleased, "Error, stream not released after WriteValue"); } writer.WriteEndElement(); // stream should be released now for MTOM if (rwType == ReaderWriterFactory.ReaderWriterType.MTOM) { Assert.True(myStreamProvider.StreamReleased, "Error, stream not released after WriteEndElement"); } writer.Flush(); return true; } static bool AsyncWriteTest(MemoryStream ms, Encoding encoding, MyStreamProvider myStreamProvider) { XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartElement("Root"); Task writeValueAsynctask = writer.WriteValueAsync(myStreamProvider); writeValueAsynctask.Wait(); Assert.True(myStreamProvider.StreamReleased, "Error, stream not released."); writer.WriteEndElement(); writer.Flush(); return true; } static bool AsyncWriteBase64Test(MemoryStream ms, byte[] byteArray, Encoding encoding, MyStreamProvider myStreamProvider) { XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartElement("Root"); Task writeValueBase64Asynctask = writer.WriteBase64Async(byteArray, 0, byteArray.Length); writeValueBase64Asynctask.Wait(); Assert.True(myStreamProvider.StreamReleased, "Error, stream not released."); writer.WriteEndElement(); writer.Flush(); return true; } private static byte[] GetByteArray(int byteSize) { var bytes = new byte[byteSize]; for (int i = 0; i < byteSize; i++) { bytes[i] = 8; } return bytes; } private static string GetExpectString(byte[] bytes, int byteSize) { using (var ms = new MemoryStream()) { var writer = XmlDictionaryWriter.CreateTextWriter(ms); writer.WriteStartDocument(); writer.WriteStartElement("data"); writer.WriteBase64(bytes, 0, byteSize); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); ms.Position = 0; var sr = new StreamReader(ms); return sr.ReadToEnd(); } } private static void SimulateWriteFragment(XmlDictionaryWriter writer, bool useFragmentAPI, int nestedLevelsLeft) { if (nestedLevelsLeft <= 0) { return; } Random rndGen = new Random(nestedLevelsLeft); int signatureLen = rndGen.Next(100, 200); byte[] signature = new byte[signatureLen]; rndGen.NextBytes(signature); MemoryStream fragmentStream = new MemoryStream(); if (!useFragmentAPI) // simulating in the writer itself { writer.WriteStartElement("SignatureValue_" + nestedLevelsLeft); writer.WriteBase64(signature, 0, signatureLen); writer.WriteEndElement(); } if (useFragmentAPI) { FragmentHelper.Start(writer, fragmentStream); } writer.WriteStartElement("Fragment" + nestedLevelsLeft); for (int i = 0; i < 5; i++) { writer.WriteStartElement(string.Format("Element{0}_{1}", nestedLevelsLeft, i)); writer.WriteAttributeString("attr1", "value1"); writer.WriteAttributeString("attr2", "value2"); } writer.WriteString("This is a text with unicode characters: <>&;\u0301\u2234"); for (int i = 0; i < 5; i++) { writer.WriteEndElement(); } // write other nested fragments... SimulateWriteFragment(writer, useFragmentAPI, nestedLevelsLeft - 1); writer.WriteEndElement(); // Fragment{nestedLevelsLeft} writer.Flush(); if (useFragmentAPI) { FragmentHelper.End(writer); writer.WriteStartElement("SignatureValue_" + nestedLevelsLeft); writer.WriteBase64(signature, 0, signatureLen); writer.WriteEndElement(); FragmentHelper.Write(writer, fragmentStream.GetBuffer(), 0, (int)fragmentStream.Length); writer.Flush(); } } public class AsyncMemoryStream : MemoryStream { public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { await Task.Delay(1).ConfigureAwait(false); await base.WriteAsync(buffer, offset, count, cancellationToken); } } public class MemoryStreamWithBlockAsync : MemoryStream { private bool _blockAsync; public void blockAsync(bool blockAsync) { _blockAsync = blockAsync; } public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { while (_blockAsync) { await Task.Delay(10).ConfigureAwait(false); } await base.WriteAsync(buffer, offset, count, cancellationToken); } } }
// 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.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Collections.Tests { public static class QueueTests { [Fact] public static void TestCtor_Empty() { const int DefaultCapactiy = 32; var queue = new Queue(); Assert.Equal(0, queue.Count); for (int i = 0; i <= DefaultCapactiy; i++) { queue.Enqueue(i); } Assert.Equal(DefaultCapactiy + 1, queue.Count); } [Theory] [InlineData(1)] [InlineData(32)] [InlineData(77)] public static void TestCtor_Capacity(int capacity) { var queue = new Queue(capacity); for (int i = 0; i <= capacity; i++) { queue.Enqueue(i); } Assert.Equal(capacity + 1, queue.Count); } [Fact] public static void TestCtor_Capacity_Invalid() { Assert.Throws<ArgumentOutOfRangeException>(() => new Queue(-1)); // Capacity < 0 } [Theory] [InlineData(1, 2.0)] [InlineData(32, 1.0)] [InlineData(77, 5.0)] public static void TestCtor_Capacity_GrowFactor(int capacity, float growFactor) { var queue = new Queue(capacity, growFactor); for (int i = 0; i <= capacity; i++) { queue.Enqueue(i); } Assert.Equal(capacity + 1, queue.Count); } [Fact] public static void TestCtor_Capactiy_GrowFactor_Invalid() { Assert.Throws<ArgumentOutOfRangeException>(() => new Queue(-1, 1)); // Capacity < 0 Assert.Throws<ArgumentOutOfRangeException>(() => new Queue(1, (float)0.99)); // Grow factor < 1 Assert.Throws<ArgumentOutOfRangeException>(() => new Queue(1, (float)10.01)); // Grow factor > 10 } [Fact] public static void TestCtor_ICollection() { ArrayList arrList = Helpers.CreateIntArrayList(100); var queue = new Queue(arrList); Assert.Equal(arrList.Count, queue.Count); for (int i = 0; i < queue.Count; i++) { Assert.Equal(i, queue.Dequeue()); } } [Fact] public static void TestCtor_ICollection_Invalid() { Assert.Throws<ArgumentNullException>(() => new Queue(null)); // Collection is null } [Fact] public static void TestDebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Queue()); var testQueue = new Queue(); testQueue.Enqueue("a"); testQueue.Enqueue(1); testQueue.Enqueue("b"); testQueue.Enqueue(2); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(testQueue); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Queue), null); } catch (TargetInvocationException ex) { ArgumentNullException nullException = ex.InnerException as ArgumentNullException; threwNull = nullException != null; } Assert.True(threwNull); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(32)] public static void TestClear(int capacity) { var queue1 = new Queue(capacity); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(1); queue2.Clear(); Assert.Equal(0, queue2.Count); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(32)] public static void TestClearEmpty(int capacity) { var queue1 = new Queue(capacity); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Clear(); Assert.Equal(0, queue2.Count); queue2.Clear(); Assert.Equal(0, queue2.Count); }); } [Fact] public static void TestClone() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Queue clone = (Queue)queue2.Clone(); Assert.Equal(queue2.IsSynchronized, clone.IsSynchronized); Assert.Equal(queue2.Count, clone.Count); for (int i = 0; i < queue2.Count; i++) { Assert.True(clone.Contains(i)); } }); } [Fact] public static void TestClone_IsShallowCopy() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(new Foo(10)); Queue clone = (Queue)queue2.Clone(); var foo = (Foo)queue2.Dequeue(); foo.IntValue = 50; var fooClone = (Foo)clone.Dequeue(); Assert.Equal(50, fooClone.IntValue); }); } [Fact] public static void TestClone_Empty() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, clone.Count); // Can change the clone queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void TestClone_Clear() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Clear(); Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, clone.Count); // Can change clone queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void TestClone_DequeueUntilEmpty() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < 100; i++) { queue2.Dequeue(); } Queue clone = (Queue)queue2.Clone(); Assert.Equal(0, queue2.Count); // Can change clone the queue clone.Enqueue(500); Assert.Equal(500, clone.Dequeue()); }); } [Fact] public static void TestClone_DequeueThenEnqueue() { var queue1 = new Queue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue2.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue2.Enqueue(i + 50); queue2.Dequeue(); } Queue queClone = (Queue)queue2.Clone(); Assert.Equal(50, queClone.Count); Assert.Equal(75, queClone.Dequeue()); // Add an item to the Queue queClone.Enqueue(100); Assert.Equal(50, queClone.Count); Assert.Equal(76, queClone.Dequeue()); }); } [Fact] public static void TestContains() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < queue2.Count; i++) { Assert.True(queue2.Contains(i)); } queue2.Enqueue(null); Assert.True(queue2.Contains(null)); }); } [Fact] public static void TestContains_NonExistentObject() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.False(queue2.Contains(101)); Assert.False(queue2.Contains("hello world")); Assert.False(queue2.Contains(null)); queue2.Enqueue(null); Assert.False(queue2.Contains(-1)); // We have a null item in the list, so the algorithm may use a different branch }); } [Fact] public static void TestContains_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.False(queue2.Contains(101)); Assert.False(queue2.Contains("hello world")); Assert.False(queue2.Contains(null)); }); } [Theory] [InlineData(0, 0)] [InlineData(1, 0)] [InlineData(10, 0)] [InlineData(100, 0)] [InlineData(1000, 0)] [InlineData(1, 50)] [InlineData(10, 50)] [InlineData(100, 50)] [InlineData(1000, 50)] public static void TestCopyTo(int count, int index) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { var array = new object[count + index]; queue2.CopyTo(array, index); Assert.Equal(count + index, array.Length); for (int i = index; i < index + count; i++) { Assert.Equal(queue2.Dequeue(), array[i]); } }); } [Fact] public static void TestCopyTo_DequeueThenEnqueue() { var queue1 = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue1.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue1.Enqueue(i + 50); queue1.Dequeue(); } var array = new object[queue1.Count]; queue1.CopyTo(array, 0); Assert.Equal(queue1.Count, array.Length); for (int i = 0; i < queue1.Count; i++) { Assert.Equal(queue1.Dequeue(), array[i]); } } [Fact] public static void TestCopyTo_Invalid() { Queue queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<ArgumentNullException>(() => queue2.CopyTo(null, 0)); // Array is null Assert.Throws<ArgumentException>(() => queue2.CopyTo(new object[150, 150], 0)); // Array is multidimensional Assert.Throws<ArgumentOutOfRangeException>(() => queue2.CopyTo(new object[150], -1)); // Index < 0 Assert.Throws<ArgumentException>(() => queue2.CopyTo(new object[150], 51)); // Index + queue.Count > array.Length }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TestDequeue(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 1; i <= count; i++) { int obj = (int)queue2.Dequeue(); Assert.Equal(i - 1, obj); Assert.Equal(count - i, queue2.Count); } }); } [Fact] public static void TestDequeue_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); // Queue is empty }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TestDequeue_UntilEmpty(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 0; i < count; i++) { queue2.Dequeue(); } Assert.Throws<InvalidOperationException>(() => queue2.Dequeue()); }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(10000)] public static void TestEnqueue(int count) { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { for (int i = 1; i <= count; i++) { queue2.Enqueue(i); Assert.Equal(i, queue2.Count); } Assert.Equal(count, queue2.Count); }); } [Fact] public static void TestEnqueue_Null() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.Enqueue(null); Assert.Equal(1, queue2.Count); }); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TestGetEnumerator(int count) { var queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { IEnumerator enumerator1 = queue2.GetEnumerator(); IEnumerator enumerator2 = queue2.GetEnumerator(); IEnumerator[] enumerators = { enumerator1, enumerator2 }; foreach (IEnumerator enumerator in enumerators) { Assert.NotNull(enumerator); int i = 0; while (enumerator.MoveNext()) { Assert.Equal(i, enumerator.Current); i++; } Assert.Equal(count, i); enumerator.Reset(); } }); } [Fact] public static void TestGetEnumerator_Invalid() { var queue1 = Helpers.CreateIntQueue(100); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { IEnumerator enumerator = queue2.GetEnumerator(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // If the underlying collection is modified, MoveNext and Reset throw, but Current doesn't enumerator.MoveNext(); object dequeued = queue2.Dequeue(); Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Reset()); Assert.Equal(dequeued, enumerator.Current); // Current throws if the current index is < 0 or >= count enumerator = queue2.GetEnumerator(); while (enumerator.MoveNext()) ; Assert.False(enumerator.MoveNext()); Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Current throws after resetting enumerator = queue2.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.True(enumerator.MoveNext()); enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); }); } [Fact] public static void TestPeek() { string s1 = "hello"; string s2 = "world"; char c = '\0'; bool b = false; byte i8 = 0; short i16 = 0; int i32 = 0; long i64 = 0L; float f = (float)0.0; double d = 0.0; var queue1 = new Queue(); queue1.Enqueue(s1); queue1.Enqueue(s2); queue1.Enqueue(c); queue1.Enqueue(b); queue1.Enqueue(i8); queue1.Enqueue(i16); queue1.Enqueue(i32); queue1.Enqueue(i64); queue1.Enqueue(f); queue1.Enqueue(d); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Same(s1, queue2.Peek()); queue2.Dequeue(); Assert.Same(s2, queue2.Peek()); queue2.Dequeue(); Assert.Equal(c, queue2.Peek()); queue2.Dequeue(); Assert.Equal(b, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i8, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i16, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i32, queue2.Peek()); queue2.Dequeue(); Assert.Equal(i64, queue2.Peek()); queue2.Dequeue(); Assert.Equal(f, queue2.Peek()); queue2.Dequeue(); Assert.Equal(d, queue2.Peek()); queue2.Dequeue(); }); } [Fact] public static void TestPeek_Invalid() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { Assert.Throws<InvalidOperationException>(() => queue2.Peek()); // Queue is empty }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TestToArray(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(count, arr.Length); for (int i = 0; i < count; i++) { Assert.Equal(queue2.Dequeue(), arr[i]); } }); } [Fact] public static void TestToArray_Wrapped() { var queue1 = new Queue(1); queue1.Enqueue(1); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(1, arr.Length); Assert.Equal(1, arr[0]); }); } [Fact] public static void TestToArrayDiffentObjectTypes() { string s1 = "hello"; string s2 = "world"; char c = '\0'; bool b = false; byte i8 = 0; short i16 = 0; int i32 = 0; long i64 = 0L; float f = (float)0.0; double d = 0.0; var queue1 = new Queue(); queue1.Enqueue(s1); queue1.Enqueue(s2); queue1.Enqueue(c); queue1.Enqueue(b); queue1.Enqueue(i8); queue1.Enqueue(i16); queue1.Enqueue(i32); queue1.Enqueue(i64); queue1.Enqueue(f); queue1.Enqueue(d); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Same(s1, arr[0]); Assert.Same(s2, arr[1]); Assert.Equal(c, arr[2]); Assert.Equal(b, arr[3]); Assert.Equal(i8, arr[4]); Assert.Equal(i16, arr[5]); Assert.Equal(i32, arr[6]); Assert.Equal(i64, arr[7]); Assert.Equal(f, arr[8]); Assert.Equal(d, arr[9]); }); } [Fact] public static void TestToArray_EmptyQueue() { var queue1 = new Queue(); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { object[] arr = queue2.ToArray(); Assert.Equal(0, arr.Length); }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TestTrimToSize(int count) { Queue queue1 = Helpers.CreateIntQueue(count); Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.TrimToSize(); Assert.Equal(count, queue2.Count); // Can change the queue after trimming queue2.Enqueue(100); Assert.Equal(count + 1, queue2.Count); if (count == 0) { Assert.Equal(100, queue2.Dequeue()); } else { Assert.Equal(0, queue2.Dequeue()); } }); } [Theory] [InlineData(1)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void TestTrimToSize_DequeueAll(int count) { Queue queue1 = Helpers.CreateIntQueue(count); for (int i = 0; i < count; i++) { queue1.Dequeue(); } Helpers.PerformActionOnAllQueueWrappers(queue1, queue2 => { queue2.TrimToSize(); Assert.Equal(0, queue2.Count); // Can change the queue after trimming queue2.Enqueue(1); Assert.Equal(1, queue2.Dequeue()); }); } [Fact] public static void TestTrimToSize_Wrapped() { var queue = new Queue(100); // Insert 50 items in the Queue for (int i = 0; i < 50; i++) { queue.Enqueue(i); } // Insert and Remove 75 items in the Queue. This should wrap the queue // where there is 25 at the end of the array and 25 at the beginning for (int i = 0; i < 75; i++) { queue.Enqueue(i + 50); queue.Dequeue(); } queue.TrimToSize(); Assert.Equal(50, queue.Count); Assert.Equal(75, queue.Dequeue()); queue.Enqueue(100); Assert.Equal(50, queue.Count); Assert.Equal(76, queue.Dequeue()); } private class Foo { public Foo(int intValue) { IntValue = intValue; } private int _intValue; public int IntValue { set { _intValue = value; } get { return _intValue; } } } } public class Queue_SyncRootTests { Task[] workers; Action action1; Action action2; int iNumberOfElements = 1000; int iNumberOfWorkers = 1000; private Queue _queueDaughter; private Queue _queueGrandDaughter; [Fact] public void TestSyncRoot() { var queueMother = new Queue(); for (int i = 0; i < iNumberOfElements; i++) { queueMother.Enqueue(i); } Assert.Equal(queueMother.SyncRoot.GetType(), typeof(object)); var queueSon = Queue.Synchronized(queueMother); _queueGrandDaughter = Queue.Synchronized(queueSon); _queueDaughter = Queue.Synchronized(queueMother); Assert.Equal(queueMother.SyncRoot, queueSon.SyncRoot); Assert.Equal(queueSon.SyncRoot, queueMother.SyncRoot); Assert.Equal(queueMother.SyncRoot, _queueGrandDaughter.SyncRoot); Assert.Equal(queueMother.SyncRoot, _queueDaughter.SyncRoot); workers = new Task[iNumberOfWorkers]; action1 = SortElements; action2 = ReverseElements; for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2) { workers[iThreads] = Task.Run(action1); workers[iThreads + 1] = Task.Run(action2); } Task.WaitAll(workers); } private void SortElements() { _queueGrandDaughter.Clear(); for (int i = 0; i < iNumberOfElements; i++) { _queueGrandDaughter.Enqueue(i); } } private void ReverseElements() { _queueDaughter.Clear(); for (int i = 0; i < iNumberOfElements; i++) { _queueDaughter.Enqueue(i); } } } public class Queue_SynchronizedTests { public Queue m_Queue; public int iCountTestcases = 0; public int iCountErrors = 0; public int m_ThreadsToUse = 8; public int m_ThreadAge = 5; // 5000; public int m_ThreadCount; [Fact] public static void TestSynchronized() { Queue queue = Helpers.CreateIntQueue(100); Queue syncQueue = Queue.Synchronized(queue); Assert.True(syncQueue.IsSynchronized); Assert.Equal(queue.Count, syncQueue.Count); for (int i = 0; i < queue.Count; i++) { Assert.True(syncQueue.Contains(i)); } } [Fact] public void TestSynchronizedEnqueue() { // Enqueue m_Queue = Queue.Synchronized(new Queue()); PerformTest(StartEnqueueThread, 40); // Dequeue Queue queue = Helpers.CreateIntQueue(m_ThreadAge); m_Queue = Queue.Synchronized(queue); PerformTest(StartDequeueThread, 0); // Enqueue, dequeue m_Queue = Queue.Synchronized(new Queue()); PerformTest(StartEnqueueDequeueThread, 0); // Dequeue, enqueue queue = Helpers.CreateIntQueue(m_ThreadAge); m_Queue = Queue.Synchronized(queue); PerformTest(StartDequeueEnqueueThread, m_ThreadAge); } private void PerformTest(Action action, int expected) { var tasks = new Task[m_ThreadsToUse]; for (int i = 0; i < m_ThreadsToUse; i++) { tasks[i] = Task.Factory.StartNew(action, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default); } m_ThreadCount = m_ThreadsToUse; Task.WaitAll(tasks); Assert.Equal(expected, m_Queue.Count); } [Fact] public static void TestSynchronizedInvalid() { Assert.Throws<ArgumentNullException>(() => Queue.Synchronized(null)); // Queue is null } public void StartEnqueueThread() { int t_age = m_ThreadAge; while (t_age > 0) { m_Queue.Enqueue(t_age); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref m_ThreadCount); } private void StartDequeueThread() { int t_age = m_ThreadAge; while (t_age > 0) { try { m_Queue.Dequeue(); } catch { } Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref m_ThreadCount); } private void StartEnqueueDequeueThread() { int t_age = m_ThreadAge; while (t_age > 0) { m_Queue.Enqueue(2); m_Queue.Dequeue(); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref m_ThreadCount); } private void StartDequeueEnqueueThread() { int t_age = m_ThreadAge; while (t_age > 0) { m_Queue.Dequeue(); m_Queue.Enqueue(2); Interlocked.Decrement(ref t_age); } Interlocked.Decrement(ref m_ThreadCount); } } }
// Copyright 2010-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 // // 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 Google.OrTools.ConstraintSolver { using System; using System.Collections.Generic; public interface IConstraintWithStatus { Solver solver(); IntVar Var(); } public abstract class BaseEquality : IConstraintWithStatus { abstract public Solver solver(); abstract public IntVar Var(); public static IntExpr operator +(BaseEquality a, BaseEquality b) { return a.solver().MakeSum(a.Var(), b.Var()); } public static IntExpr operator +(BaseEquality a, long v) { return a.solver().MakeSum(a.Var(), v); } public static IntExpr operator +(long v, BaseEquality a) { return a.solver().MakeSum(a.Var(), v); } public static IntExpr operator -(BaseEquality a, BaseEquality b) { return a.solver().MakeDifference(a.Var(), b.Var()); } public static IntExpr operator -(BaseEquality a, long v) { return a.solver().MakeSum(a.Var(), -v); } public static IntExpr operator -(long v, BaseEquality a) { return a.solver().MakeDifference(v, a.Var()); } public static IntExpr operator *(BaseEquality a, BaseEquality b) { return a.solver().MakeProd(a.Var(), b.Var()); } public static IntExpr operator *(BaseEquality a, long v) { return a.solver().MakeProd(a.Var(), v); } public static IntExpr operator *(long v, BaseEquality a) { return a.solver().MakeProd(a.Var(), v); } public static IntExpr operator /(BaseEquality a, long v) { return a.solver().MakeDiv(a.Var(), v); } public static IntExpr operator -(BaseEquality a) { return a.solver().MakeOpposite(a.Var()); } public IntExpr Abs() { return this.solver().MakeAbs(this.Var()); } public IntExpr Square() { return this.solver().MakeSquare(this.Var()); } public static WrappedConstraint operator ==(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } public static WrappedConstraint operator ==(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeEquality(a.Var(), v)); } public static WrappedConstraint operator !=(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator !=(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeNonEquality(a.Var(), v)); } public static WrappedConstraint operator >=(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), v)); } public static WrappedConstraint operator >=(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), v)); } public static WrappedConstraint operator>(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator>(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), v)); } public static WrappedConstraint operator <=(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), v)); } public static WrappedConstraint operator <=(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), v)); } public static WrappedConstraint operator<(BaseEquality a, long v) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), v)); } public static WrappedConstraint operator<(long v, BaseEquality a) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), v)); } public static WrappedConstraint operator >=(BaseEquality a, BaseEquality b) { return new WrappedConstraint(a.solver().MakeGreaterOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator>(BaseEquality a, BaseEquality b) { return new WrappedConstraint(a.solver().MakeGreater(a.Var(), b.Var())); } public static WrappedConstraint operator <=(BaseEquality a, BaseEquality b) { return new WrappedConstraint(a.solver().MakeLessOrEqual(a.Var(), b.Var())); } public static WrappedConstraint operator<(BaseEquality a, BaseEquality b) { return new WrappedConstraint(a.solver().MakeLess(a.Var(), b.Var())); } public static ConstraintEquality operator ==(BaseEquality a, BaseEquality b) { return new ConstraintEquality(a, b, true); } public static ConstraintEquality operator !=(BaseEquality a, BaseEquality b) { return new ConstraintEquality(a, b, false); } } public class WrappedConstraint : BaseEquality { public bool Val { get; set; } public Constraint Cst { get; set; } public WrappedConstraint(Constraint cst) : this(true, cst) { } public WrappedConstraint(bool val) : this(val, null) { } public WrappedConstraint(bool val, Constraint cst) { this.Val = val; this.Cst = cst; } public static implicit operator bool(WrappedConstraint valCstPair) { return valCstPair.Val; } public static implicit operator Constraint(WrappedConstraint valCstPair) { return valCstPair.Cst; } public static implicit operator IntVar(WrappedConstraint eq) { return eq.Var(); } public static implicit operator IntExpr(WrappedConstraint eq) { return eq.Var(); } public override Solver solver() { return this.Cst.solver(); } public override IntVar Var() { return Cst.Var(); } } public class IntExprEquality : BaseEquality { public IntExprEquality(IntExpr a, IntExpr b, bool equality) { this.left_ = a; this.right_ = b; this.equality_ = equality; } bool IsTrue() { return (object)left_ == (object)right_ ? equality_ : !equality_; } Constraint ToConstraint() { return equality_ ? left_.solver().MakeEquality(left_.Var(), right_.Var()) : left_.solver().MakeNonEquality(left_.Var(), right_.Var()); } public static bool operator true(IntExprEquality eq) { return eq.IsTrue(); } public static bool operator false(IntExprEquality eq) { return !eq.IsTrue(); } public static implicit operator Constraint(IntExprEquality eq) { return eq.ToConstraint(); } public override IntVar Var() { return equality_ ? left_.solver().MakeIsEqualVar(left_, right_) : left_.solver().MakeIsDifferentVar(left_, right_); } public static implicit operator IntVar(IntExprEquality eq) { return eq.Var(); } public static implicit operator IntExpr(IntExprEquality eq) { return eq.Var(); } public override Solver solver() { return left_.solver(); } private IntExpr left_; private IntExpr right_; private bool equality_; } public class ConstraintEquality : BaseEquality { public ConstraintEquality(IConstraintWithStatus a, IConstraintWithStatus b, bool equality) { this.left_ = a; this.right_ = b; this.equality_ = equality; } bool IsTrue() { return (object)left_ == (object)right_ ? equality_ : !equality_; } Constraint ToConstraint() { return equality_ ? left_.solver().MakeEquality(left_.Var(), right_.Var()) : left_.solver().MakeNonEquality(left_.Var(), right_.Var()); } public static bool operator true(ConstraintEquality eq) { return eq.IsTrue(); } public static bool operator false(ConstraintEquality eq) { return !eq.IsTrue(); } public static implicit operator Constraint(ConstraintEquality eq) { return eq.ToConstraint(); } public override IntVar Var() { return equality_ ? left_.solver().MakeIsEqualVar(left_.Var(), right_.Var()) : left_.solver().MakeIsDifferentVar(left_.Var(), right_.Var()); } public static implicit operator IntVar(ConstraintEquality eq) { return eq.Var(); } public static implicit operator IntExpr(ConstraintEquality eq) { return eq.Var(); } public override Solver solver() { return left_.solver(); } private IConstraintWithStatus left_; private IConstraintWithStatus right_; private bool equality_; } } // namespace Google.OrTools.ConstraintSolver
//============================================================================= // System : Sandcastle Help File Builder Plug-Ins // File : TocExcludePlugIn.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 06/13/2010 // Note : Copyright 2008-2010, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains a plug-in that can be used to exclude API members from // the table of contents via the <tocexclude /> XML comment tag. The excluded // items are still accessible in the help file via other topic links. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.6.0.6 03/13/2008 EFW Created the code //============================================================================= using System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using System.Xml; using System.Xml.XPath; using SandcastleBuilder.Utils; using SandcastleBuilder.Utils.BuildEngine; using SandcastleBuilder.Utils.PlugIn; namespace SandcastleBuilder.PlugIns { /// <summary> /// This plug-in class can be used to exclude API members from the table /// of contents via the <c>&lt;tocexclude /&gt;</c> XML comment tag. The /// excluded items are still accessible in the help file via other topic /// links. /// </summary> public class TocExcludePlugIn : IPlugIn { #region Private data members //===================================================================== private ExecutionPointCollection executionPoints; private BuildProcess builder; private List<string> exclusionList; #endregion #region IPlugIn implementation //===================================================================== /// <summary> /// This read-only property returns a friendly name for the plug-in /// </summary> public string Name { get { return "Table of Contents Exclusion"; } } /// <summary> /// This read-only property returns the version of the plug-in /// </summary> public Version Version { get { // Use the assembly version Assembly asm = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location); return new Version(fvi.ProductVersion); } } /// <summary> /// This read-only property returns the copyright information for the /// plug-in. /// </summary> public string Copyright { get { // Use the assembly copyright Assembly asm = Assembly.GetExecutingAssembly(); AssemblyCopyrightAttribute copyright = (AssemblyCopyrightAttribute)Attribute.GetCustomAttribute( asm, typeof(AssemblyCopyrightAttribute)); return copyright.Copyright; } } /// <summary> /// This read-only property returns a brief description of the plug-in /// </summary> public string Description { get { return "This plug-in can be used to exclude API members " + "from the table of contents via the <tocexclude /> XML " + "comment tag. The excluded items are still accessible " + "in the help file via other topic links."; } } /// <summary> /// This plug-in does not run in partial builds /// </summary> public bool RunsInPartialBuild { get { return false; } } /// <summary> /// This read-only property returns a collection of execution points /// that define when the plug-in should be invoked during the build /// process. /// </summary> public ExecutionPointCollection ExecutionPoints { get { if(executionPoints == null) executionPoints = new ExecutionPointCollection { new ExecutionPoint(BuildStep.CopyStandardContent, ExecutionBehaviors.After), // This one has a slightly higher priority as it removes // stuff that the other plug-ins don't need to see. new ExecutionPoint(BuildStep.GenerateIntermediateTableOfContents, ExecutionBehaviors.After, 1500) }; return executionPoints; } } /// <summary> /// This method is used by the Sandcastle Help File Builder to let the /// plug-in perform its own configuration. /// </summary> /// <param name="project">A reference to the active project</param> /// <param name="currentConfig">The current configuration XML fragment</param> /// <returns>A string containing the new configuration XML fragment</returns> /// <remarks>The configuration data will be stored in the help file /// builder project.</remarks> public string ConfigurePlugIn(SandcastleProject project, string currentConfig) { MessageBox.Show("This plug-in has no configurable settings", "Table of Contents Exclusion Plug-In", MessageBoxButtons.OK, MessageBoxIcon.Information); return currentConfig; } /// <summary> /// This method is used to initialize the plug-in at the start of the /// build process. /// </summary> /// <param name="buildProcess">A reference to the current build /// process.</param> /// <param name="configuration">The configuration data that the plug-in /// should use to initialize itself.</param> public void Initialize(BuildProcess buildProcess, XPathNavigator configuration) { builder = buildProcess; builder.ReportProgress("{0} Version {1}\r\n{2}", this.Name, this.Version, this.Copyright); exclusionList = new List<string>(); } /// <summary> /// This method is used to execute the plug-in during the build process /// </summary> /// <param name="context">The current execution context</param> public void Execute(ExecutionContext context) { XmlDocument toc; XPathNavigator root, navToc, tocEntry, tocParent; bool hasParent; // Scan the XML comments files. The files aren't available soon // after this step and by now everything that other plug-ins may // have added to the collection should be there. if(context.BuildStep == BuildStep.CopyStandardContent) { builder.ReportProgress("Searching for comment members containing <tocexclude />..."); foreach(XmlCommentsFile f in builder.CommentsFiles) foreach(XmlNode member in f.Members.SelectNodes("member[count(.//tocexclude) > 0]/@name")) exclusionList.Add(member.Value); builder.ReportProgress("Found {0} members to exclude from the TOC", exclusionList.Count); return; } if(exclusionList.Count == 0) { builder.ReportProgress("No members found to exclude"); return; } builder.ReportProgress("Removing members from the TOC"); toc = new XmlDocument(); toc.Load(builder.WorkingFolder + "toc.xml"); navToc = toc.CreateNavigator(); // If a root namespace container node is present, we need to look // in it rather than the document root node. root = navToc.SelectSingleNode("topics/topic[starts-with(@id, 'R:')]"); if(root == null) root = navToc.SelectSingleNode("topics"); foreach(string id in exclusionList) { tocEntry = root.SelectSingleNode("//topic[@id='" + id + "']"); // Ignore if null, it was probably excluded by the API filter if(tocEntry != null) { // Remove the entry. If this results in the parent // being an empty node, remove it too. do { tocParent = tocEntry.Clone(); hasParent = tocParent.MoveToParent(); builder.ReportProgress(" Removing '{0}'", tocEntry.GetAttribute("id", String.Empty)); tocEntry.DeleteSelf(); } while(hasParent && !tocParent.HasChildren); } } toc.Save(builder.WorkingFolder + "toc.xml"); } #endregion #region IDisposable implementation //===================================================================== /// <summary> /// This handles garbage collection to ensure proper disposal of the /// plug-in if not done explicity with <see cref="Dispose()"/>. /// </summary> ~TocExcludePlugIn() { this.Dispose(false); } /// <summary> /// This implements the Dispose() interface to properly dispose of /// the plug-in object. /// </summary> /// <overloads>There are two overloads for this method.</overloads> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// This can be overridden by derived classes to add their own /// disposal code if necessary. /// </summary> /// <param name="disposing">Pass true to dispose of the managed /// and unmanaged resources or false to just dispose of the /// unmanaged resources.</param> protected virtual void Dispose(bool disposing) { // Nothing to dispose of in this one } #endregion } }
#region License // // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // 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.Data.SqlClient; using System.Linq; using FluentMigrator.Runner.Announcers; using FluentMigrator.Runner.Generators.Postgres; using FluentMigrator.Runner.Processors; using FluentMigrator.Runner.Processors.MySql; using FluentMigrator.Runner.Processors.Postgres; using FluentMigrator.Runner.Processors.SQLite; using FluentMigrator.Runner.Processors.SqlServer; using MySql.Data.MySqlClient; using Npgsql; using FluentMigrator.Runner.Generators.SQLite; using FluentMigrator.Runner.Generators.SqlServer; using FluentMigrator.Runner.Generators.MySql; using FirebirdSql.Data.FirebirdClient; using FluentMigrator.Runner.Processors.Firebird; using FluentMigrator.Runner.Generators.Firebird; namespace FluentMigrator.Tests.Integration { public class IntegrationTestBase { public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test) { ExecuteWithSupportedProcessors(test, true); } public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, Boolean tryRollback) { ExecuteWithSupportedProcessors(test, tryRollback, new Type[] { }); } public void ExecuteWithSupportedProcessors(Action<IMigrationProcessor> test, Boolean tryRollback, params Type[] exceptProcessors) { if (exceptProcessors.Count(t => typeof(SqlServerProcessor).IsAssignableFrom(t)) == 0) { ExecuteWithSqlServer2005(test, tryRollback); ExecuteWithSqlServer2008(test, tryRollback); ExecuteWithSqlServer2012(test, tryRollback); ExecuteWithSqlServer2014(test, tryRollback); } if (exceptProcessors.Count(t => typeof(SQLiteProcessor).IsAssignableFrom(t)) == 0) ExecuteWithSqlite(test, IntegrationTestOptions.SqlLite); if (exceptProcessors.Count(t => typeof(MySqlProcessor).IsAssignableFrom(t)) == 0) ExecuteWithMySql(test, IntegrationTestOptions.MySql); if (exceptProcessors.Count(t => typeof(PostgresProcessor).IsAssignableFrom(t)) == 0) ExecuteWithPostgres(test, IntegrationTestOptions.Postgres, tryRollback); if (exceptProcessors.Count(t => typeof(FirebirdProcessor).IsAssignableFrom(t)) == 0) ExecuteWithFirebird(test, IntegrationTestOptions.Firebird); } protected static void ExecuteWithSqlServer2014(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2014; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2014"); var generator = new SqlServer2014Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } protected static void ExecuteWithSqlServer2012(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2012; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2012"); var generator = new SqlServer2012Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } protected static void ExecuteWithSqlServer2008(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2008; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2008"); var generator = new SqlServer2008Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } protected static void ExecuteWithSqlServer2005(Action<IMigrationProcessor> test, bool tryRollback) { var serverOptions = IntegrationTestOptions.SqlServer2005; if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MS SQL Server 2005"); var generator = new SqlServer2005Generator(); ExecuteWithSqlServer(serverOptions, announcer, generator, test, tryRollback); } private static void ExecuteWithSqlServer(IntegrationTestOptions.DatabaseServerOptions serverOptions, TextWriterAnnouncer announcer, SqlServer2005Generator generator, Action<IMigrationProcessor> test, bool tryRollback) { using (var connection = new SqlConnection(serverOptions.ConnectionString)) { var processor = new SqlServerProcessor(connection, generator, announcer, new ProcessorOptions(), new SqlServerDbFactory()); test(processor); if (tryRollback && !processor.WasCommitted) { processor.RollbackTransaction(); } } } protected static void ExecuteWithSqlite(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against SQLite"); var factory = new SQLiteDbFactory(); using (var connection = factory.CreateConnection(serverOptions.ConnectionString)) { var processor = new SQLiteProcessor(connection, new SQLiteGenerator(), announcer, new ProcessorOptions(), factory); test(processor); } } protected static void ExecuteWithPostgres(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions, Boolean tryRollback) { if (serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against Postgres"); using (var connection = new NpgsqlConnection(serverOptions.ConnectionString)) { var processor = new PostgresProcessor(connection, new PostgresGenerator(), new TextWriterAnnouncer(System.Console.Out), new ProcessorOptions(), new PostgresDbFactory()); test(processor); if (!processor.WasCommitted) { processor.RollbackTransaction(); } } } protected static void ExecuteWithMySql(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.Heading("Testing Migration against MySQL Server"); using (var connection = new MySqlConnection(serverOptions.ConnectionString)) { var processor = new MySqlProcessor(connection, new MySqlGenerator(), announcer, new ProcessorOptions(), new MySqlDbFactory()); test(processor); } } protected static void ExecuteWithFirebird(Action<IMigrationProcessor> test, IntegrationTestOptions.DatabaseServerOptions serverOptions) { if (!serverOptions.IsEnabled) return; var announcer = new TextWriterAnnouncer(System.Console.Out); announcer.ShowSql = true; announcer.Heading("Testing Migration against Firebird Server"); if (!System.IO.File.Exists("fbtest.fdb")) { FbConnection.CreateDatabase(serverOptions.ConnectionString); } using (var connection = new FbConnection(serverOptions.ConnectionString)) { var options = FirebirdOptions.AutoCommitBehaviour(); var processor = new FirebirdProcessor(connection, new FirebirdGenerator(options), announcer, new ProcessorOptions(), new FirebirdDbFactory(), options); try { test(processor); } catch (Exception) { if (!processor.WasCommitted) processor.RollbackTransaction(); throw; } connection.Close(); } } } }
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type UserCalendarsCollectionRequest. /// </summary> public partial class UserCalendarsCollectionRequest : BaseRequest, IUserCalendarsCollectionRequest { /// <summary> /// Constructs a new UserCalendarsCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public UserCalendarsCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified Calendar to the collection via POST. /// </summary> /// <param name="calendar">The Calendar to add.</param> /// <returns>The created Calendar.</returns> public System.Threading.Tasks.Task<Calendar> AddAsync(Calendar calendar) { return this.AddAsync(calendar, CancellationToken.None); } /// <summary> /// Adds the specified Calendar to the collection via POST. /// </summary> /// <param name="calendar">The Calendar to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Calendar.</returns> public System.Threading.Tasks.Task<Calendar> AddAsync(Calendar calendar, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<Calendar>(calendar, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IUserCalendarsCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IUserCalendarsCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<UserCalendarsCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Expand(Expression<Func<Calendar, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Select(Expression<Func<Calendar, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IUserCalendarsCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
// Copyright (c) Microsoft Open Technologies, Inc. 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using Microsoft.AspNet.Razor.Parser; using Microsoft.AspNet.Razor.Parser.SyntaxTree; using Microsoft.AspNet.Razor.Text; using Microsoft.AspNet.Razor.Tokenizer.Symbols; using Microsoft.Internal.Web.Utils; namespace Microsoft.AspNet.Razor.Editor { public class ImplicitExpressionEditHandler : SpanEditHandler { [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Func<T> is the recommended delegate type and requires this level of nesting.")] public ImplicitExpressionEditHandler(Func<string, IEnumerable<ISymbol>> tokenizer, ISet<string> keywords, bool acceptTrailingDot) : base(tokenizer) { Initialize(keywords, acceptTrailingDot); } public bool AcceptTrailingDot { get; private set; } public ISet<string> Keywords { get; private set; } public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "{0};ImplicitExpression[{1}];K{2}", base.ToString(), AcceptTrailingDot ? "ATD" : "RTD", Keywords.Count); } public override bool Equals(object obj) { ImplicitExpressionEditHandler other = obj as ImplicitExpressionEditHandler; return other != null && base.Equals(other) && Keywords.SetEquals(other.Keywords) && AcceptTrailingDot == other.AcceptTrailingDot; } public override int GetHashCode() { return HashCodeCombiner.Start() .Add(base.GetHashCode()) .Add(AcceptTrailingDot) .Add(Keywords) .CombinedHash; } protected override PartialParseResult CanAcceptChange(Span target, TextChange normalizedChange) { if (AcceptedCharacters == AcceptedCharacters.Any) { return PartialParseResult.Rejected; } // In some editors intellisense insertions are handled as "dotless commits". If an intellisense selection is confirmed // via something like '.' a dotless commit will append a '.' and then insert the remaining intellisense selection prior // to the appended '.'. This 'if' statement attempts to accept the intermediate steps of a dotless commit via // intellisense. It will accept two cases: // 1. '@foo.' -> '@foobaz.'. // 2. '@foobaz..' -> '@foobaz.bar.'. Includes Sub-cases '@foobaz()..' -> '@foobaz().bar.' etc. // The key distinction being the double '.' in the second case. if (IsDotlessCommitInsertion(target, normalizedChange)) { return HandleDotlessCommitInsertion(target); } if (IsAcceptableReplace(target, normalizedChange)) { return HandleReplacement(target, normalizedChange); } int changeRelativePosition = normalizedChange.OldPosition - target.Start.AbsoluteIndex; // Get the edit context char? lastChar = null; if (changeRelativePosition > 0 && target.Content.Length > 0) { lastChar = target.Content[changeRelativePosition - 1]; } // Don't support 0->1 length edits if (lastChar == null) { return PartialParseResult.Rejected; } // Accepts cases when insertions are made at the end of a span or '.' is inserted within a span. if (IsAcceptableInsertion(target, normalizedChange)) { // Handle the insertion return HandleInsertion(target, lastChar.Value, normalizedChange); } if (IsAcceptableDeletion(target, normalizedChange)) { return HandleDeletion(target, lastChar.Value, normalizedChange); } return PartialParseResult.Rejected; } private void Initialize(ISet<string> keywords, bool acceptTrailingDot) { Keywords = keywords ?? new HashSet<string>(); AcceptTrailingDot = acceptTrailingDot; } // A dotless commit is the process of inserting a '.' with an intellisense selection. private static bool IsDotlessCommitInsertion(Span target, TextChange change) { return IsNewDotlessCommitInsertion(target, change) || IsSecondaryDotlessCommitInsertion(target, change); } // Completing 'DateTime' in intellisense with a '.' could result in: '@DateT' -> '@DateT.' -> '@DateTime.' which is accepted. private static bool IsNewDotlessCommitInsertion(Span target, TextChange change) { return !IsAtEndOfSpan(target, change) && change.NewPosition > 0 && change.NewLength > 0 && target.Content.Last() == '.' && ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false) && (change.OldLength == 0 || ParserHelpers.IsIdentifier(change.OldText, requireIdentifierStart: false)); } // Once a dotless commit has been performed you then have something like '@DateTime.'. This scenario is used to detect the // situation when you try to perform another dotless commit resulting in a textchange with '..'. Completing 'DateTime.Now' // in intellisense with a '.' could result in: '@DateTime.' -> '@DateTime..' -> '@DateTime.Now.' which is accepted. private static bool IsSecondaryDotlessCommitInsertion(Span target, TextChange change) { // Do not need to worry about other punctuation, just looking for double '.' (after change) return change.NewLength == 1 && !String.IsNullOrEmpty(target.Content) && target.Content.Last() == '.' && change.NewText == "." && change.OldLength == 0; } private static bool IsAcceptableReplace(Span target, TextChange change) { return IsEndReplace(target, change) || (change.IsReplace && RemainingIsWhitespace(target, change)); } private static bool IsAcceptableDeletion(Span target, TextChange change) { return IsEndDeletion(target, change) || (change.IsDelete && RemainingIsWhitespace(target, change)); } // Acceptable insertions can occur at the end of a span or when a '.' is inserted within a span. private static bool IsAcceptableInsertion(Span target, TextChange change) { return change.IsInsert && (IsAcceptableEndInsertion(target, change) || IsAcceptableInnerInsertion(target, change)); } // Accepts character insertions at the end of spans. AKA: '@foo' -> '@fooo' or '@foo' -> '@foo ' etc. private static bool IsAcceptableEndInsertion(Span target, TextChange change) { Debug.Assert(change.IsInsert); return IsAtEndOfSpan(target, change) || RemainingIsWhitespace(target, change); } // Accepts '.' insertions in the middle of spans. Ex: '@foo.baz.bar' -> '@foo..baz.bar' // This is meant to allow intellisense when editing a span. [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "target", Justification = "The 'target' parameter is used in Debug to validate that the function is called in the correct context.")] private static bool IsAcceptableInnerInsertion(Span target, TextChange change) { Debug.Assert(change.IsInsert); // Ensure that we're actually inserting in the middle of a span and not at the end. // This case will fail if the IsAcceptableEndInsertion does not capture an end insertion correctly. Debug.Assert(!IsAtEndOfSpan(target, change)); return change.NewPosition > 0 && change.NewText == "."; } private static bool RemainingIsWhitespace(Span target, TextChange change) { int offset = (change.OldPosition - target.Start.AbsoluteIndex) + change.OldLength; return String.IsNullOrWhiteSpace(target.Content.Substring(offset)); } private PartialParseResult HandleDotlessCommitInsertion(Span target) { PartialParseResult result = PartialParseResult.Accepted; if (!AcceptTrailingDot && target.Content.LastOrDefault() == '.') { result |= PartialParseResult.Provisional; } return result; } private PartialParseResult HandleReplacement(Span target, TextChange change) { // Special Case for IntelliSense commits. // When IntelliSense commits, we get two changes (for example user typed "Date", then committed "DateTime" by pressing ".") // 1. Insert "." at the end of this span // 2. Replace the "Date." at the end of the span with "DateTime." // We need partial parsing to accept case #2. string oldText = GetOldText(target, change); PartialParseResult result = PartialParseResult.Rejected; if (EndsWithDot(oldText) && EndsWithDot(change.NewText)) { result = PartialParseResult.Accepted; if (!AcceptTrailingDot) { result |= PartialParseResult.Provisional; } } return result; } private PartialParseResult HandleDeletion(Span target, char previousChar, TextChange change) { // What's left after deleting? if (previousChar == '.') { return TryAcceptChange(target, change, PartialParseResult.Accepted | PartialParseResult.Provisional); } else if (ParserHelpers.IsIdentifierPart(previousChar)) { return TryAcceptChange(target, change); } else { return PartialParseResult.Rejected; } } private PartialParseResult HandleInsertion(Span target, char previousChar, TextChange change) { // What are we inserting after? if (previousChar == '.') { return HandleInsertionAfterDot(target, change); } else if (ParserHelpers.IsIdentifierPart(previousChar) || previousChar == ')' || previousChar == ']') { return HandleInsertionAfterIdPart(target, change); } else { return PartialParseResult.Rejected; } } private PartialParseResult HandleInsertionAfterIdPart(Span target, TextChange change) { // If the insertion is a full identifier part, accept it if (ParserHelpers.IsIdentifier(change.NewText, requireIdentifierStart: false)) { return TryAcceptChange(target, change); } else if (EndsWithDot(change.NewText)) { // Accept it, possibly provisionally PartialParseResult result = PartialParseResult.Accepted; if (!AcceptTrailingDot) { result |= PartialParseResult.Provisional; } return TryAcceptChange(target, change, result); } else { return PartialParseResult.Rejected; } } private static bool EndsWithDot(string content) { return (content.Length == 1 && content[0] == '.') || (content[content.Length - 1] == '.' && content.Take(content.Length - 1).All(ParserHelpers.IsIdentifierPart)); } private PartialParseResult HandleInsertionAfterDot(Span target, TextChange change) { // If the insertion is a full identifier or another dot, accept it if (ParserHelpers.IsIdentifier(change.NewText) || change.NewText == ".") { return TryAcceptChange(target, change); } return PartialParseResult.Rejected; } private PartialParseResult TryAcceptChange(Span target, TextChange change, PartialParseResult acceptResult = PartialParseResult.Accepted) { string content = change.ApplyChange(target); if (StartsWithKeyword(content)) { return PartialParseResult.Rejected | PartialParseResult.SpanContextChanged; } return acceptResult; } private bool StartsWithKeyword(string newContent) { using (StringReader reader = new StringReader(newContent)) { return Keywords.Contains(reader.ReadWhile(ParserHelpers.IsIdentifierPart)); } } } }
/* * Copyright 2005 OpenXRI Foundation * Subsequently ported and altered by Andrew Arnott * * 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.Text; using System.Collections; using System; using DotNetXri.Syntax; namespace DotNetXri.Client.Resolve { //using java.net.Uri; //using java.util.ArrayList; //using org.openxri.GCSAuthority; //using org.openxri.XRI; //using org.openxri.XRIAuthority; //using org.openxri.xml.XRD; /** * This class <strong>used to provide</strong> encapsulation of the cache state of a Resolver obj. * Now, it is used to store information about the references processed, Uri traversed, etc. during * a resolution request. * The caching functionality may be revived at a later date. * * @author =chetan * @author =wil */ public class ResolverState { private long timeStarted; private ArrayList steps; private int numRefsFollowed; // successful or not private int numRequests; // # of requests private int numBytesReceived; // just the XRDS content size /** * Constructor */ public ResolverState() { timeStarted = System.currentTimeMillis(); // DateTime.Now.Ticks? steps = new ArrayList(); numRefsFollowed = 0; // successful or not numRequests = 0; numBytesReceived = 0; } /** * @return Returns the time that this obj was constructed. */ public long getTimeStarted() { return timeStarted; } /** * @return Returns the number of Refs followed. */ public int getNumRefsFollowed() { return numRefsFollowed; } /** * @return Returns the number of resolution requests attempted */ public int getNumRequests() { return numRequests; } /** * @return Returns the total size of XRDS's received. */ public int getNumBytesReceived() { return numBytesReceived; } public ResolverStep getStepAt(int i) { return (ResolverStep)steps[i]; } public int getNumSteps() { return steps.Count; } /** * * @param qxri QXRI that was resolved * @param xrds XRDS document received * @param uri Uri queried to resolve the QXRI */ public void pushResolved(string qxri, string trustType, string xrds, Uri uri) { ResolverStep step = new ResolverStep(qxri, trustType, xrds, null, uri); steps.Add(step); numRequests++; numBytesReceived += xrds.Length; } public void pushFollowingRef(XRI _ref) { ResolverStep step = new ResolverStep(null, null, null, _ref, null); steps.add(step); numRefsFollowed++; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("NumRequests=" + numRequests + ", numRefsFollowed=" + numRefsFollowed + ", numBytesReceived=" + numBytesReceived + "\n"); for (int i = 0; i < getNumSteps(); i++) { ResolverStep step = getStepAt(i); sb.Append(step.ToString()); sb.Append("\n"); } return sb.ToString(); } public class ResolverStep { public final string qxri; public final string trust; public final string xrds; public final Uri uri; public final XRI _ref; public final long timeCompleted; public ResolverStep(string qxri, string trust, string xrds, XRI _ref, Uri uri) { this.qxri = qxri; this.trust = trust; this.xrds = xrds; this._ref = _ref; this.uri = uri; this.timeCompleted = System.currentTimeMillis(); } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("QXRI="); sb.Append(qxri); sb.Append(", trust="); sb.Append(trust); sb.Append(", uri="); sb.Append((uri == null)? "null" : uri.toASCIIString()); sb.Append(", ref="); sb.Append(_ref); sb.Append(", elapsed="); sb.Append(timeCompleted - timeStarted); sb.Append("ms\n\nXRDS = \n"); sb.Append(xrds); return sb.ToString(); } } ///////////// Deprecated stuff below. /** * @deprecated */ private Cache moBasicCache = new Cache(1000); /** * @deprecated */ private Cache moTrustedCache = new Cache(1000); /** * Returns the Cache obj for the security model * @param bTrusted if true, returns the trusted cache, if false, returns * the regular cache. * @deprecated */ public Cache getCache(bool bTrusted) { return (bTrusted == true) ? moBasicCache : moTrustedCache; } /** * Sets the XRD for the final subsegment of the XRIAuthority. * The authority may contain multiple subgments. Each internal subsegment * will not be set. * @param oAuth The XRIAuthority element to set * @param oDesc The descriptor for the final subsegment in the oAuth * @deprecated */ public void set(XRIAuthority oAuth, XRD oDesc) { moBasicCache.stuff(oAuth, oDesc); moTrustedCache.stuff(oAuth, oDesc); } /** * Resets the internal XRD cache for this XRIAuthority * @param oAuth The XRIAuthority element to prune */ public void reset(XRIAuthority oAuth) { moBasicCache.prune(oAuth); moTrustedCache.prune(oAuth); } /** * Sets the XRD for the "@" Authority. * @param oDesc The descriptor for the "@" Authority * @deprecated */ public void setAtAuthority(XRD oDesc) { GCSAuthority oAuth = new GCSAuthority("@"); set(oAuth, oDesc); } /** * Sets the XRD for the "=" Authority. * @param oDesc The descriptor for the "=" Authority */ public void setEqualsAuthority(XRD oDesc) { GCSAuthority oAuth = new GCSAuthority("="); set(oAuth, oDesc); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Runtime.InteropServices; namespace Rawr { public partial class FormItemSelection : Form { private Character _character; public Character Character { get { return _character; } set { if (_character != null) { _character.CalculationsInvalidated -= new EventHandler(_character_ItemsChanged); } _character = value; _characterSlot = CharacterSlot.None; if (_character != null) { _character.CalculationsInvalidated += new EventHandler(_character_ItemsChanged); } } } private CharacterCalculationsBase _currentCalculations; public CharacterCalculationsBase CurrentCalculations { get { return _currentCalculations; } set { _currentCalculations = value; } } private ComparisonCalculationBase[] _itemCalculations; public ComparisonCalculationBase[] ItemCalculations { get { return _itemCalculations; } set { if (value == null) { _itemCalculations = new ComparisonCalculationBase[0]; } else { List<ComparisonCalculationBase> calcs = new List<ComparisonCalculationBase>(value); calcs.Sort(new System.Comparison<ComparisonCalculationBase>(CompareItemCalculations)); _itemCalculations = calcs.ToArray(); } RebuildItemList(); } } private ComparisonGraph.ComparisonSort _sort = ComparisonGraph.ComparisonSort.Overall; public ComparisonGraph.ComparisonSort Sort { get { return _sort; } set { _sort = value; ItemCalculations = ItemCalculations; } } protected int CompareItemCalculations(ComparisonCalculationBase a, ComparisonCalculationBase b) { if (Sort == ComparisonGraph.ComparisonSort.Overall) return a.OverallPoints.CompareTo(b.OverallPoints); else if (Sort == ComparisonGraph.ComparisonSort.Alphabetical) return b.Name.CompareTo(a.Name); else return a.SubPoints[(int)Sort].CompareTo(b.SubPoints[(int)Sort]); } public FormItemSelection() { InitializeComponent(); overallToolStripMenuItem.Tag = -1; alphabeticalToolStripMenuItem.Tag = -2; Calculations_ModelChanged(null, null); this.Activated += new EventHandler(FormItemSelection_Activated); ItemCache.Instance.ItemsChanged += new EventHandler(ItemCache_ItemsChanged); Calculations.ModelChanged += new EventHandler(Calculations_ModelChanged); } void Calculations_ModelChanged(object sender, EventArgs e) { _characterSlot = CharacterSlot.None; sortToolStripMenuItem_Click(overallToolStripMenuItem, EventArgs.Empty); toolStripDropDownButtonSort.DropDownItems.Clear(); toolStripDropDownButtonSort.DropDownItems.Add(overallToolStripMenuItem); toolStripDropDownButtonSort.DropDownItems.Add(alphabeticalToolStripMenuItem); foreach (string name in Calculations.SubPointNameColors.Keys) { ToolStripMenuItem toolStripMenuItemSubPoint = new ToolStripMenuItem(name); toolStripMenuItemSubPoint.Tag = toolStripDropDownButtonSort.DropDownItems.Count - 2; toolStripMenuItemSubPoint.Click += new System.EventHandler(this.sortToolStripMenuItem_Click); toolStripDropDownButtonSort.DropDownItems.Add(toolStripMenuItemSubPoint); } } void ItemCache_ItemsChanged(object sender, EventArgs e) { CharacterSlot characterSlot = _characterSlot; _characterSlot = CharacterSlot.None; LoadItemsBySlot(characterSlot); } void _character_ItemsChanged(object sender, EventArgs e) { _characterSlot = CharacterSlot.None; } void FormItemSelection_Activated(object sender, EventArgs e) { panelItems.AutoScrollPosition = new Point(0, 0); } private void CheckToHide(object sender, EventArgs e) { if (Visible) { ItemToolTip.Instance.Hide(this); this.Hide(); } } private void timerForceActivate_Tick(object sender, System.EventArgs e) { this.timerForceActivate.Enabled = false; this.Activate(); } public void ForceShow() { this.timerForceActivate.Enabled = true; } public void Show(ItemButton button, CharacterSlot slot) { _button = button; if (_buttonEnchant != null) { _characterSlot = CharacterSlot.None; _buttonEnchant = null; } this.SetAutoLocation(button); this.LoadItemsBySlot(slot); base.Show(); } public void Show(ItemButtonWithEnchant button, CharacterSlot slot) { _buttonEnchant = button; if (_button != null) { _characterSlot = CharacterSlot.None; _button = null; } this.SetAutoLocation(button); this.LoadEnchantsBySlot(slot); base.Show(); } public void SetAutoLocation(Control ctrl) { Point ctrlScreen = ctrl.Parent.PointToScreen(ctrl.Location); Point location = new Point(ctrlScreen.X + ctrl.Width, ctrlScreen.Y); Rectangle workingArea = System.Windows.Forms.Screen.GetWorkingArea(ctrl.Parent); if (location.X < workingArea.Left) location.X = workingArea.Left; if (location.Y < workingArea.Top) location.Y = workingArea.Top; if (location.X + this.Width > workingArea.Right) location.X = ctrlScreen.X - this.Width; if (location.Y + this.Height > workingArea.Bottom) location.Y = workingArea.Bottom - this.Height; this.Location = location; } private void sortToolStripMenuItem_Click(object sender, EventArgs e) { this.Cursor = Cursors.WaitCursor; ComparisonGraph.ComparisonSort sort = ComparisonGraph.ComparisonSort.Overall; foreach (ToolStripItem item in toolStripDropDownButtonSort.DropDownItems) { if (item is ToolStripMenuItem) { (item as ToolStripMenuItem).Checked = item == sender; if ((item as ToolStripMenuItem).Checked) { toolStripDropDownButtonSort.Text = item.Text; sort = (ComparisonGraph.ComparisonSort)((int)item.Tag); } } } this.Sort = sort;//(ComparisonGraph.ComparisonSort)Enum.Parse(typeof(ComparisonGraph.ComparisonSort), toolStripDropDownButtonSort.Text); this.Cursor = Cursors.Default; } private CharacterSlot _characterSlot = CharacterSlot.None; private ItemButton _button; private ItemButtonWithEnchant _buttonEnchant; public void LoadItemsBySlot(CharacterSlot slot) { if (_characterSlot != slot) { _characterSlot = slot; List<ComparisonCalculationBase> itemCalculations = new List<ComparisonCalculationBase>(); if ((int)slot >= 0 && (int)slot <= 20) { if (this.Character != null) { bool seenEquippedItem = Character[slot] == null; foreach (ItemInstance item in Character.GetRelevantItemInstances(slot)) { if (!seenEquippedItem && Character[slot].Equals(item)) seenEquippedItem = true; if (item.Item.FitsInSlot(slot, Character)) { itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, slot)); } } if (!seenEquippedItem) { itemCalculations.Add(Calculations.GetItemCalculations(Character[slot], this.Character, slot)); } } ComparisonCalculationBase emptyCalcs = Calculations.CreateNewComparisonCalculation(); emptyCalcs.Name = "Empty"; emptyCalcs.Item = new Item(); emptyCalcs.Item.Name = "Empty"; emptyCalcs.ItemInstance = new ItemInstance(); emptyCalcs.ItemInstance.Id = -1; emptyCalcs.Equipped = this.Character[slot] == null; itemCalculations.Add(emptyCalcs); } else { if (this.Character != null) { bool seenEquippedItem = false; if (_button != null && _button.SelectedItem == null) { seenEquippedItem = true; } foreach (Item item in Character.GetRelevantItems(slot)) { if (!seenEquippedItem && _button != null && item.Equals(_button.SelectedItem)) seenEquippedItem = true; if (item.FitsInSlot(slot, Character)) { if(slot == CharacterSlot.Gems) AddGemToItemCalculations(itemCalculations, item); else itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, slot)); } } if (!seenEquippedItem && _button != null && _button.SelectedItem != null) { itemCalculations.Add(Calculations.GetItemCalculations(_button.SelectedItem, this.Character, slot)); } } ComparisonCalculationBase emptyCalcs = Calculations.CreateNewComparisonCalculation(); emptyCalcs.Name = "Empty"; emptyCalcs.Item = new Item(); emptyCalcs.Item.Name = "Empty"; emptyCalcs.ItemInstance = new ItemInstance(); emptyCalcs.ItemInstance.Id = -1; if (_button != null && _button.SelectedItem != null) { emptyCalcs.Equipped = _button.SelectedItem == null; } else { emptyCalcs.Equipped = false; } itemCalculations.Add(emptyCalcs); } itemCalculations.Sort(new System.Comparison<ComparisonCalculationBase>(CompareItemCalculations)); Dictionary<int, int> countItem = new Dictionary<int, int>(); List<ComparisonCalculationBase> filteredItemCalculations = new List<ComparisonCalculationBase>(); for (int i = itemCalculations.Count - 1; i >= 0; i--) //foreach (ComparisonCalculationBase itemCalculation in itemCalculations) { ComparisonCalculationBase itemCalculation = itemCalculations[i]; int itemId = (itemCalculation.ItemInstance == null ? itemCalculation.Item.Id : itemCalculation.ItemInstance.Id); if (!countItem.ContainsKey(itemId)) countItem.Add(itemId, 0); if (countItem[itemId]++ < Properties.GeneralSettings.Default.CountGemmingsShown || itemCalculation.Equipped || itemCalculation.ItemInstance.ForceDisplay) { filteredItemCalculations.Add(itemCalculation); } } ItemCalculations = filteredItemCalculations.ToArray(); } } private void AddGemToItemCalculations(List<ComparisonCalculationBase> itemCalculations, Item item) { if (item.IsJewelersGem) { if (!Rawr.Properties.GeneralSettings.Default.HideProfEnchants || this.Character.HasProfession(Profession.Jewelcrafting)) { if (Character.JewelersGemCount < 3) itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, CharacterSlot.Gems)); else { Item nullItem = item.Clone(); nullItem.Stats = new Stats(); itemCalculations.Add(Calculations.GetItemCalculations(nullItem, this.Character, CharacterSlot.Gems)); } } } else if (item.IsLimitedGem) { if (!Character.IsUniqueGemEquipped(item)) itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, CharacterSlot.Gems)); else { Item nullItem = item.Clone(); nullItem.Stats = new Stats(); itemCalculations.Add(Calculations.GetItemCalculations(nullItem, this.Character, CharacterSlot.Gems)); } } else itemCalculations.Add(Calculations.GetItemCalculations(item, this.Character, CharacterSlot.Gems)); } private void LoadEnchantsBySlot(CharacterSlot slot) { if (_characterSlot != slot) { _characterSlot = slot; List<ComparisonCalculationBase> itemCalculations = null; if (Character != null && CurrentCalculations != null) { itemCalculations = Calculations.GetEnchantCalculations(Item.GetItemSlotByCharacterSlot(slot), Character, CurrentCalculations, false); } itemCalculations.Sort(new System.Comparison<ComparisonCalculationBase>(CompareItemCalculations)); ItemCalculations = itemCalculations.ToArray(); } } private List<ItemSelectorItem> _itemSelectorItems = new List<ItemSelectorItem>(); private void RebuildItemList() { if (this.InvokeRequired) { Invoke((MethodInvoker)RebuildItemList); //InvokeHelper.Invoke(this, "RebuildItemList", null); return; } panelItems.SuspendLayout(); ////Replaced this... //while (panelItems.Controls.Count < this.ItemCalculations.Length) // panelItems.Controls.Add(new ItemSelectorItem()); //while (panelItems.Controls.Count > this.ItemCalculations.Length) // panelItems.Controls.RemoveAt(panelItems.Controls.Count - 1); ////...with this, so as not to constantly create and remove lots of controls int currentItemLength = panelItems.Controls.Count; int targetItemLength = this.ItemCalculations.Length; if (currentItemLength < targetItemLength) { int itemSelectorsToCreate = targetItemLength - _itemSelectorItems.Count; for (int i = 0; i < itemSelectorsToCreate; i++) { _itemSelectorItems.Add(new ItemSelectorItem()); } for (int i = currentItemLength; i < targetItemLength; i++) { panelItems.Controls.Add(_itemSelectorItems[i]); } } else if (currentItemLength > targetItemLength) { for (int i = currentItemLength; i > targetItemLength; i--) { panelItems.Controls.RemoveAt(i - 1); } } float maxRating = 0; for (int i = 0; i < this.ItemCalculations.Length; i++) { ItemSelectorItem ctrl = panelItems.Controls[i] as ItemSelectorItem; ComparisonCalculationBase calc = this.ItemCalculations[i]; if (_button != null) { calc.Equipped = (calc.ItemInstance == _button.SelectedItemInstance && calc.Item == _button.SelectedItem) || (calc.Item.Id == 0 && _button.SelectedItem == null); ctrl.IsEnchant = false; } if (_buttonEnchant != null) { calc.Equipped = Math.Abs(calc.Item.Id % 10000) == _buttonEnchant.SelectedEnchantId; ctrl.IsEnchant = true; } ctrl.ItemCalculation = calc; ctrl.Character = Character; ctrl.CharacterSlot = _characterSlot; ctrl.Sort = this.Sort; ctrl.HideToolTip(); bool visible = string.IsNullOrEmpty(this.toolStripTextBoxFilter.Text) || calc.Name.ToLower().Contains(this.toolStripTextBoxFilter.Text.ToLower()); ctrl.Visible = visible; if (visible) { float calcRating; if (Sort == ComparisonGraph.ComparisonSort.Overall || this.Sort == ComparisonGraph.ComparisonSort.Alphabetical) { calcRating = calc.OverallPoints; } else { calcRating = calc.SubPoints[(int)Sort]; } maxRating = Math.Max(maxRating, calcRating); } } panelItems.ResumeLayout(true); foreach (ItemSelectorItem ctrl in panelItems.Controls) { ctrl.MaxRating = maxRating; } } private void toolStripTextBoxFilter_TextChanged(object sender, EventArgs e) { RebuildItemList(); } public void Select(ItemInstance item) { if (_button != null) _button.SelectedItemInstance = item == null ? null : item.Clone(); //if (_buttonEnchant != null) //{ // ItemInstance copy = _buttonEnchant.SelectedItem.Clone(); // copy.EnchantId = item == null ? 0 : Math.Abs(item.Id % 10000); // _buttonEnchant.SelectedItem = copy; //} _characterSlot = CharacterSlot.None; ItemToolTip.Instance.Hide(this); this.Hide(); } public void Select(Item item) { if (_button != null) _button.SelectedItem = item; if (_buttonEnchant != null) { if(_buttonEnchant.SelectedItem != null) { ItemInstance copy = _buttonEnchant.SelectedItem.Clone(); copy.EnchantId = item == null ? 0 : Math.Abs(item.Id % 10000); _buttonEnchant.SelectedItem = copy; } } _characterSlot = CharacterSlot.None; ItemToolTip.Instance.Hide(this); this.Hide(); } } public interface IFormItemSelectionProvider { FormItemSelection FormItemSelection { get; } } }
/* * 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.Globalization; using System.Runtime.Remoting; using System.Runtime.Remoting.Lifetime; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes; using OpenSim.Region.ScriptEngine.Interfaces; using OpenSim.Region.ScriptEngine.Shared; using OpenSim.Region.ScriptEngine.Shared.Api; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using OpenSim.Region.ScriptEngine.Shared.Api.Runtime; using OpenSim.Region.ScriptEngine.Shared.ScriptBase; using OpenSim.Region.ScriptEngine.Shared.CodeTools; namespace OpenSim.Region.ScriptEngine.DotNetEngine { public class InstanceData { public IScript Script; public string State; public bool Running; public bool Disabled; public string Source; public int StartParam; public AppDomain AppDomain; public Dictionary<string, IScriptApi> Apis; public Dictionary<KeyValuePair<int,int>, KeyValuePair<int,int>> LineMap; // public ISponsor ScriptSponsor; } public class ScriptManager { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Declares private Thread scriptLoadUnloadThread; private static Thread staticScriptLoadUnloadThread = null; private Queue<LUStruct> LUQueue = new Queue<LUStruct>(); private static bool PrivateThread; private int LoadUnloadMaxQueueSize; private Object scriptLock = new Object(); private bool m_started = false; private Dictionary<InstanceData, DetectParams[]> detparms = new Dictionary<InstanceData, DetectParams[]>(); // Load/Unload structure private struct LUStruct { public uint localID; public UUID itemID; public string script; public LUType Action; public int startParam; public bool postOnRez; } private enum LUType { Unknown = 0, Load = 1, Unload = 2 } public Dictionary<uint, Dictionary<UUID, InstanceData>> Scripts = new Dictionary<uint, Dictionary<UUID, InstanceData>>(); private Compiler LSLCompiler; public Scene World { get { return m_scriptEngine.World; } } #endregion public void Initialize() { // Create our compiler LSLCompiler = new Compiler(m_scriptEngine); } public void _StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez) { m_log.DebugFormat( "[{0}]: ScriptManager StartScript: localID: {1}, itemID: {2}", m_scriptEngine.ScriptEngineName, localID, itemID); // We will initialize and start the script. // It will be up to the script itself to hook up the correct events. string CompiledScriptFile = String.Empty; SceneObjectPart m_host = World.GetSceneObjectPart(localID); if (null == m_host) { m_log.ErrorFormat( "[{0}]: Could not find scene object part corresponding "+ "to localID {1} to start script", m_scriptEngine.ScriptEngineName, localID); return; } UUID assetID = UUID.Zero; TaskInventoryItem taskInventoryItem = new TaskInventoryItem(); if (m_host.TaskInventory.TryGetValue(itemID, out taskInventoryItem)) assetID = taskInventoryItem.AssetID; ScenePresence presence = World.GetScenePresence(taskInventoryItem.OwnerID); CultureInfo USCulture = new CultureInfo("en-US"); Thread.CurrentThread.CurrentCulture = USCulture; try { // Compile (We assume LSL) CompiledScriptFile = LSLCompiler.PerformScriptCompile(Script, assetID.ToString(), taskInventoryItem.OwnerID); if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage( "Compile successful", false); m_log.InfoFormat("[SCRIPT]: Compiled assetID {0}: {1}", assetID, CompiledScriptFile); InstanceData id = new InstanceData(); IScript CompiledScript; CompiledScript = m_scriptEngine.m_AppDomainManager.LoadScript( CompiledScriptFile, out id.AppDomain); //Register the sponsor // ISponsor scriptSponsor = new ScriptSponsor(); // ILease lease = (ILease)RemotingServices.GetLifetimeService(CompiledScript as MarshalByRefObject); // lease.Register(scriptSponsor); // id.ScriptSponsor = scriptSponsor; id.LineMap = LSLCompiler.LineMap(); id.Script = CompiledScript; id.Source = Script; id.StartParam = startParam; id.State = "default"; id.Running = true; id.Disabled = false; // Add it to our script memstruct m_scriptEngine.m_ScriptManager.SetScript(localID, itemID, id); id.Apis = new Dictionary<string, IScriptApi>(); ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { id.Apis[api] = am.CreateApi(api); id.Apis[api].Initialize(m_scriptEngine, m_host, localID, itemID); } foreach (KeyValuePair<string,IScriptApi> kv in id.Apis) { CompiledScript.InitApi(kv.Key, kv.Value); } // Fire the first start-event int eventFlags = m_scriptEngine.m_ScriptManager.GetStateEventFlags( localID, itemID); m_host.SetScriptEvents(itemID, eventFlags); m_scriptEngine.m_EventQueueManager.AddToScriptQueue( localID, itemID, "state_entry", new DetectParams[0], new object[] { }); if (postOnRez) { m_scriptEngine.m_EventQueueManager.AddToScriptQueue( localID, itemID, "on_rez", new DetectParams[0], new object[] { new LSL_Types.LSLInteger(startParam) }); } string[] warnings = LSLCompiler.GetWarnings(); if (warnings != null && warnings.Length != 0) { if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage( "Script saved with warnings, check debug window!", false); foreach (string warning in warnings) { try { // DISPLAY WARNING INWORLD string text = "Warning:\n" + warning; if (text.Length > 1100) text = text.Substring(0, 1099); World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, m_host.AbsolutePosition, m_host.Name, m_host.UUID, false); } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Error displaying warning in-world: " + e2.ToString()); m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " + "Warning:\r\n" + warning); } } } } catch (Exception e) // LEGIT: User Scripting { if (presence != null && (!postOnRez)) presence.ControllingClient.SendAgentAlertMessage( "Script saved with errors, check debug window!", false); try { // DISPLAY ERROR INWORLD string text = "Error compiling script:\n" + e.Message.ToString(); if (text.Length > 1100) text = text.Substring(0, 1099); World.SimChat(Utils.StringToBytes(text), ChatTypeEnum.DebugChannel, 2147483647, m_host.AbsolutePosition, m_host.Name, m_host.UUID, false); } catch (Exception e2) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Error displaying error in-world: " + e2.ToString()); m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: " + "Errormessage: Error compiling script:\r\n" + e2.Message.ToString()); } } } public void _StopScript(uint localID, UUID itemID) { InstanceData id = GetScript(localID, itemID); if (id == null) return; m_log.DebugFormat("[{0}]: Unloading script", m_scriptEngine.ScriptEngineName); // Stop long command on script AsyncCommandManager.RemoveScript(m_scriptEngine, localID, itemID); try { // Get AppDomain // Tell script not to accept new requests id.Running = false; id.Disabled = true; AppDomain ad = id.AppDomain; // Remove from internal structure RemoveScript(localID, itemID); // Tell AppDomain that we have stopped script m_scriptEngine.m_AppDomainManager.StopScript(ad); } catch (Exception e) // LEGIT: User Scripting { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: Exception stopping script localID: " + localID + " LLUID: " + itemID.ToString() + ": " + e.ToString()); } } public void ReadConfig() { // TODO: Requires sharing of all ScriptManagers to single thread PrivateThread = true; LoadUnloadMaxQueueSize = m_scriptEngine.ScriptConfigSource.GetInt( "LoadUnloadMaxQueueSize", 100); } #region Object init/shutdown public ScriptEngine m_scriptEngine; public ScriptManager(ScriptEngine scriptEngine) { m_scriptEngine = scriptEngine; } public void Setup() { ReadConfig(); Initialize(); } public void Start() { m_started = true; AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); // // CREATE THREAD // Private or shared // if (PrivateThread) { // Assign one thread per region //scriptLoadUnloadThread = StartScriptLoadUnloadThread(); } else { // Shared thread - make sure one exist, then assign it to the private if (staticScriptLoadUnloadThread == null) { //staticScriptLoadUnloadThread = // StartScriptLoadUnloadThread(); } scriptLoadUnloadThread = staticScriptLoadUnloadThread; } } ~ScriptManager() { // Abort load/unload thread try { if (scriptLoadUnloadThread != null && scriptLoadUnloadThread.IsAlive == true) { scriptLoadUnloadThread.Abort(); //scriptLoadUnloadThread.Join(); } } catch { } } #endregion #region Load / Unload scripts (Thread loop) public void DoScriptLoadUnload() { if (!m_started) return; lock (LUQueue) { if (LUQueue.Count > 0) { LUStruct item = LUQueue.Dequeue(); if (item.Action == LUType.Unload) { _StopScript(item.localID, item.itemID); RemoveScript(item.localID, item.itemID); } else if (item.Action == LUType.Load) { m_log.DebugFormat("[{0}]: Loading script", m_scriptEngine.ScriptEngineName); _StartScript(item.localID, item.itemID, item.script, item.startParam, item.postOnRez); } } } } #endregion #region Helper functions private static Assembly CurrentDomain_AssemblyResolve( object sender, ResolveEventArgs args) { return Assembly.GetExecutingAssembly().FullName == args.Name ? Assembly.GetExecutingAssembly() : null; } #endregion #region Start/Stop/Reset script /// <summary> /// Fetches, loads and hooks up a script to an objects events /// </summary> /// <param name="itemID"></param> /// <param name="localID"></param> public void StartScript(uint localID, UUID itemID, string Script, int startParam, bool postOnRez) { lock (LUQueue) { if ((LUQueue.Count >= LoadUnloadMaxQueueSize) && m_started) { m_log.Error("[" + m_scriptEngine.ScriptEngineName + "]: ERROR: Load/unload queue item count is at " + LUQueue.Count + ". Config variable \"LoadUnloadMaxQueueSize\" "+ "is set to " + LoadUnloadMaxQueueSize + ", so ignoring new script."); return; } LUStruct ls = new LUStruct(); ls.localID = localID; ls.itemID = itemID; ls.script = Script; ls.Action = LUType.Load; ls.startParam = startParam; ls.postOnRez = postOnRez; LUQueue.Enqueue(ls); } } /// <summary> /// Disables and unloads a script /// </summary> /// <param name="localID"></param> /// <param name="itemID"></param> public void StopScript(uint localID, UUID itemID) { LUStruct ls = new LUStruct(); ls.localID = localID; ls.itemID = itemID; ls.Action = LUType.Unload; ls.startParam = 0; ls.postOnRez = false; lock (LUQueue) { LUQueue.Enqueue(ls); } } #endregion #region Perform event execution in script // Execute a LL-event-function in Script internal void ExecuteEvent(uint localID, UUID itemID, string FunctionName, DetectParams[] qParams, object[] args) { int ExeStage=0; // ;^) Ewe Loon, for debuging InstanceData id=null; try // ;^) Ewe Loon,fix { // ;^) Ewe Loon,fix ExeStage = 1; // ;^) Ewe Loon, for debuging id = GetScript(localID, itemID); if (id == null) return; ExeStage = 2; // ;^) Ewe Loon, for debuging if (qParams.Length>0) // ;^) Ewe Loon,fix detparms[id] = qParams; ExeStage = 3; // ;^) Ewe Loon, for debuging if (id.Running) id.Script.ExecuteEvent(id.State, FunctionName, args); ExeStage = 4; // ;^) Ewe Loon, for debuging if (qParams.Length>0) // ;^) Ewe Loon,fix detparms.Remove(id); ExeStage = 5; // ;^) Ewe Loon, for debuging } catch (Exception e) // ;^) Ewe Loon, From here down tis fix { if ((ExeStage == 3)&&(qParams.Length>0)) detparms.Remove(id); SceneObjectPart ob = m_scriptEngine.World.GetSceneObjectPart(localID); m_log.InfoFormat("[Script Error] ,{0},{1},@{2},{3},{4},{5}", ob.Name , FunctionName, ExeStage, e.Message, qParams.Length, detparms.Count); if (ExeStage != 2) throw e; } } public uint GetLocalID(UUID itemID) { foreach (KeyValuePair<uint, Dictionary<UUID, InstanceData> > k in Scripts) { if (k.Value.ContainsKey(itemID)) return k.Key; } return 0; } public int GetStateEventFlags(uint localID, UUID itemID) { try { InstanceData id = GetScript(localID, itemID); if (id == null) { return 0; } int evflags = id.Script.GetStateEventFlags(id.State); return (int)evflags; } catch (Exception) { } return 0; } #endregion #region Internal functions to keep track of script public List<UUID> GetScriptKeys(uint localID) { if (Scripts.ContainsKey(localID) == false) return new List<UUID>(); Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); return new List<UUID>(Obj.Keys); } public InstanceData GetScript(uint localID, UUID itemID) { lock (scriptLock) { InstanceData id = null; if (Scripts.ContainsKey(localID) == false) return null; Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); if (Obj==null) return null; if (Obj.ContainsKey(itemID) == false) return null; // Get script Obj.TryGetValue(itemID, out id); return id; } } public void SetScript(uint localID, UUID itemID, InstanceData id) { lock (scriptLock) { // Create object if it doesn't exist if (Scripts.ContainsKey(localID) == false) { Scripts.Add(localID, new Dictionary<UUID, InstanceData>()); } // Delete script if it exists Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); if (Obj.ContainsKey(itemID) == true) Obj.Remove(itemID); // Add to object Obj.Add(itemID, id); } } public void RemoveScript(uint localID, UUID itemID) { if (localID == 0) localID = GetLocalID(itemID); // Don't have that object? if (Scripts.ContainsKey(localID) == false) return; // Delete script if it exists Dictionary<UUID, InstanceData> Obj; Scripts.TryGetValue(localID, out Obj); if (Obj.ContainsKey(itemID) == true) Obj.Remove(itemID); } #endregion public void ResetScript(uint localID, UUID itemID) { InstanceData id = GetScript(localID, itemID); string script = id.Source; StopScript(localID, itemID); SceneObjectPart part = World.GetSceneObjectPart(localID); part.Inventory.GetInventoryItem(itemID).PermsMask = 0; part.Inventory.GetInventoryItem(itemID).PermsGranter = UUID.Zero; StartScript(localID, itemID, script, id.StartParam, false); } #region Script serialization/deserialization public void GetSerializedScript(uint localID, UUID itemID) { // Serialize the script and return it // Should not be a problem FileStream fs = File.Create("SERIALIZED_SCRIPT_" + itemID); BinaryFormatter b = new BinaryFormatter(); b.Serialize(fs, GetScript(localID, itemID)); fs.Close(); } public void PutSerializedScript(uint localID, UUID itemID) { // Deserialize the script and inject it into an AppDomain // How to inject into an AppDomain? } #endregion public DetectParams[] GetDetectParams(InstanceData id) { if (detparms.ContainsKey(id)) return detparms[id]; return null; } public int GetStartParameter(UUID itemID) { uint localID = GetLocalID(itemID); InstanceData id = GetScript(localID, itemID); if (id == null) return 0; return id.StartParam; } public IScriptApi GetApi(UUID itemID, string name) { uint localID = GetLocalID(itemID); InstanceData id = GetScript(localID, itemID); if (id == null) return null; if (id.Apis.ContainsKey(name)) return id.Apis[name]; return null; } } }
// 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; namespace WebsitePanel.Providers.SharePoint { /// <summary> /// Represents SharePoint site collection information. /// </summary> [Serializable] public class SharePointEnterpriseSiteCollection : ServiceProviderItem { private int organizationId; private string url; private string physicalAddress; private string ownerLogin; private string ownerName; private string ownerEmail; private int localeId; private string title; private string description; private long bandwidth; private long diskspace; private long maxSiteStorage; private long warningStorage; private string rootWebApplicationInteralIpAddress; private string rootWebApplicationFQDN; [Persistent] public long MaxSiteStorage { get { return maxSiteStorage; } set { maxSiteStorage = value; } } [Persistent] public long WarningStorage { get { return warningStorage; } set { warningStorage = value; } } /// <summary> /// Gets or sets service item name. /// </summary> public override string Name { get { return this.Url; } set { this.Url = value; } } /// <summary> /// Gets or sets id of organization which owns this site collection. /// </summary> [Persistent] public int OrganizationId { get { return this.organizationId; } set { this.organizationId = value; } } /// <summary> /// Gets or sets url of the host named site collection to be created. It must not contain port number. /// </summary> [Persistent] public string Url { get { return this.url; } set { this.url = value; } } /// <summary> /// Gets or sets physical address of the host named site collection. It contains scheme and port number. /// </summary> [Persistent] public string PhysicalAddress { get { return this.physicalAddress; } set { this.physicalAddress = value; } } /// <summary> /// Gets or sets login name of the site collection's owner/primary site administrator. /// </summary> [Persistent] public string OwnerLogin { get { return this.ownerLogin; } set { this.ownerLogin = value; } } /// <summary> /// Gets or sets display name of the site collection's owner/primary site administrator. /// </summary> [Persistent] public string OwnerName { get { return this.ownerName; } set { this.ownerName = value; } } /// <summary> /// Gets or sets display email of the site collection's owner/primary site administrator. /// </summary> [Persistent] public string OwnerEmail { get { return this.ownerEmail; } set { this.ownerEmail = value; } } /// <summary> /// Gets or sets the internal ip address /// </summary> [Persistent] public string RootWebApplicationInteralIpAddress { get { return this.rootWebApplicationInteralIpAddress; } set { this.rootWebApplicationInteralIpAddress = value; } } /// <summary> /// Gets or sets the internal ip address /// </summary> [Persistent] public string RootWebApplicationFQDN { get { return this.rootWebApplicationFQDN; } set { this.rootWebApplicationFQDN = value; } } /// <summary> /// Gets or sets locale id of the site collection to be created. /// </summary> [Persistent] public int LocaleId { get { return this.localeId; } set { this.localeId = value; } } /// <summary> /// Gets or sets title of the the site collection to be created. /// </summary> [Persistent] public string Title { get { return this.title; } set { this.title = value; } } /// <summary> /// Gets or sets description of the the site collection to be created. /// </summary> [Persistent] public string Description { get { return this.description; } set { this.description = value; } } /// <summary> /// Gets or sets bandwidth of the the site collection. /// </summary> [Persistent] public long Bandwidth { get { return this.bandwidth; } set { this.bandwidth = value; } } /// <summary> /// Gets or sets diskspace of the the site collection. /// </summary> [Persistent] public long Diskspace { get { return this.diskspace; } set { this.diskspace = value; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using Mono.Unix; using Hyena; using Hyena.Data.Sqlite; using Banshee.Configuration; using Banshee.ServiceStack; using Banshee.Database; using Banshee.Sources; using Banshee.Playlists.Formats; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Streaming; namespace Banshee.Playlist { public class PlaylistImportCanceledException : ApplicationException { public PlaylistImportCanceledException (string message) : base (message) { } public PlaylistImportCanceledException () : base () { } } public static class PlaylistFileUtil { public static readonly SchemaEntry<string> DefaultExportFormat = new SchemaEntry<string> ( "player_window", "default_export_format", String.Empty, "Export Format", "The default playlist export format" ); private static PlaylistFormatDescription [] export_formats = new PlaylistFormatDescription [] { M3uPlaylistFormat.FormatDescription, PlsPlaylistFormat.FormatDescription, XspfPlaylistFormat.FormatDescription }; public static readonly string [] PlaylistExtensions = new string [] { M3uPlaylistFormat.FormatDescription.FileExtension, PlsPlaylistFormat.FormatDescription.FileExtension, XspfPlaylistFormat.FormatDescription.FileExtension }; public static PlaylistFormatDescription [] ExportFormats { get { return export_formats; } } public static bool IsSourceExportSupported (Source source) { bool supported = true; if (source == null || !(source is AbstractPlaylistSource)) { supported = false; } return supported; } public static PlaylistFormatDescription GetDefaultExportFormat () { PlaylistFormatDescription default_format = null; try { string exportFormat = DefaultExportFormat.Get (); PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats; foreach (PlaylistFormatDescription format in formats) { if (format.FileExtension.Equals (exportFormat)) { default_format = format; break; } } } catch { // Ignore errors, return our default if we encounter an error. } finally { if (default_format == null) { default_format = M3uPlaylistFormat.FormatDescription; } } return default_format; } public static void SetDefaultExportFormat (PlaylistFormatDescription format) { try { DefaultExportFormat.Set (format.FileExtension); } catch (Exception) { } } public static int GetFormatIndex (PlaylistFormatDescription [] formats, PlaylistFormatDescription playlist) { int default_export_index = -1; foreach (PlaylistFormatDescription format in formats) { default_export_index++; if (format.FileExtension.Equals (playlist.FileExtension)) { break; } } return default_export_index; } public static bool PathHasPlaylistExtension (string playlistUri) { if (System.IO.Path.HasExtension (playlistUri)) { string extension = System.IO.Path.GetExtension (playlistUri).ToLower (); foreach (PlaylistFormatDescription format in PlaylistFileUtil.ExportFormats) { if (extension.Equals ("." + format.FileExtension)) { return true; } } } return false; } public static IPlaylistFormat Load (string playlistUri, Uri baseUri, Uri rootPath) { PlaylistFormatDescription [] formats = PlaylistFileUtil.ExportFormats; // If the file has an extenstion, rearrange the format array so that the // appropriate format is tried first. if (System.IO.Path.HasExtension (playlistUri)) { string extension = System.IO.Path.GetExtension (playlistUri); extension = extension.ToLower (); int index = -1; foreach (PlaylistFormatDescription format in formats) { index++; if (extension.Equals ("." + format.FileExtension)) { break; } } if (index != -1 && index != 0 && index < formats.Length) { // Move to first position in array. PlaylistFormatDescription preferredFormat = formats[index]; formats[index] = formats[0]; formats[0] = preferredFormat; } } foreach (PlaylistFormatDescription format in formats) { try { IPlaylistFormat playlist = (IPlaylistFormat)Activator.CreateInstance (format.Type); playlist.BaseUri = baseUri; playlist.RootPath = rootPath; playlist.Load (Banshee.IO.File.OpenRead (new SafeUri (playlistUri)), true); return playlist; } catch (InvalidPlaylistException) { } } return null; } public static void ImportPlaylistToLibrary (string path) { ImportPlaylistToLibrary (path, null, null); } public static void ImportPlaylistToLibrary (string path, PrimarySource source, DatabaseImportManager importer) { try { SafeUri uri = new SafeUri (path); PlaylistParser parser = new PlaylistParser (); string relative_dir = System.IO.Path.GetDirectoryName (uri.LocalPath); if (relative_dir[relative_dir.Length - 1] != System.IO.Path.DirectorySeparatorChar) { relative_dir = relative_dir + System.IO.Path.DirectorySeparatorChar; } parser.BaseUri = new Uri (relative_dir); if (parser.Parse (uri)) { List<string> uris = new List<string> (); foreach (PlaylistElement element in parser.Elements) { uris.Add (element.Uri.LocalPath); } if (source == null) { if (uris.Count > 0) { // Get the media attribute of the 1st Uri in Playlist // and then determine whether the playlist belongs to Video or Music SafeUri uri1 = new SafeUri (uris[0]); var track = new TrackInfo (); StreamTagger.TrackInfoMerge (track, uri1); if (track.HasAttribute (TrackMediaAttributes.VideoStream)) source = ServiceManager.SourceManager.VideoLibrary; else source = ServiceManager.SourceManager.MusicLibrary; } } // Give source a fallback value - MusicLibrary when it's null if (source == null) source = ServiceManager.SourceManager.MusicLibrary; // Only import an non-empty playlist if (uris.Count > 0) { ImportPlaylistWorker worker = new ImportPlaylistWorker ( parser.Title, uris.ToArray (), source, importer); worker.Import (); } } } catch (Exception e) { Hyena.Log.Exception (e); } } } public class ImportPlaylistWorker { private string [] uris; private string name; private PrimarySource source; private DatabaseImportManager importer; private bool finished; public ImportPlaylistWorker (string name, string [] uris, PrimarySource source, DatabaseImportManager importer) { this.name = name; this.uris = uris; this.source = source; this.importer = importer; } public void Import () { try { if (importer == null) { importer = new Banshee.Library.LibraryImportManager (); } finished = false; importer.Finished += CreatePlaylist; importer.Enqueue (uris); } catch (PlaylistImportCanceledException e) { Hyena.Log.Exception (e); } } private void CreatePlaylist (object o, EventArgs args) { if (finished) { return; } finished = true; try { PlaylistSource playlist = new PlaylistSource (name, source); playlist.Save (); source.AddChildSource (playlist); HyenaSqliteCommand insert_command = new HyenaSqliteCommand (String.Format ( @"INSERT INTO CorePlaylistEntries (PlaylistID, TrackID) VALUES ({0}, ?)", playlist.DbId)); //ServiceManager.DbConnection.BeginTransaction (); foreach (string uri in uris) { // FIXME: Does the following call work if the source is just a PrimarySource (not LibrarySource)? int track_id = source.GetTrackIdForUri (uri); if (track_id > 0) { ServiceManager.DbConnection.Execute (insert_command, track_id); } } playlist.Reload (); playlist.NotifyUser (); } catch (Exception e) { Hyena.Log.Exception (e); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading; using System.Threading.Tasks; using Apache.Ignite.Core.Cache.Configuration; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Messaging; using Apache.Ignite.Core.Resource; using Apache.Ignite.Core.Tests.Cache; using NUnit.Framework; /// <summary> /// <see cref="IMessaging"/> tests. /// </summary> public sealed class MessagingTest { /** */ private IIgnite _grid1; /** */ private IIgnite _grid2; /** */ private IIgnite _grid3; /** */ private static int _messageId; /** Objects to test against. */ private static readonly object[] Objects = { // Primitives. null, "string topic", Guid.NewGuid(), DateTime.Now, byte.MinValue, short.MaxValue, // Enums. CacheMode.Local, GCCollectionMode.Forced, // Objects. new CacheTestKey(25), new IgniteGuid(Guid.NewGuid(), 123), }; /// <summary> /// Executes before each test. /// </summary> [SetUp] public void SetUp() { _grid1 = Ignition.Start(GetConfiguration("grid-1")); _grid2 = Ignition.Start(GetConfiguration("grid-2")); _grid3 = Ignition.Start(GetConfiguration("grid-3")); Assert.AreEqual(3, _grid1.GetCluster().GetNodes().Count); } /// <summary> /// Executes after each test. /// </summary> [TearDown] public void TearDown() { try { TestUtils.AssertHandleRegistryIsEmpty(1000, _grid1, _grid2, _grid3); MessagingTestHelper.AssertFailures(); } finally { // Stop all grids between tests to drop any hanging messages Ignition.StopAll(true); } } /// <summary> /// Tests that any data type can be used as a message. /// </summary> [Test] public void TestMessageDataTypes() { var topic = "dataTypes"; object lastMsg = null; var evt = new AutoResetEvent(false); var messaging1 = _grid1.GetMessaging(); var messaging2 = _grid2.GetMessaging(); var listener = new MessageListener<object>((nodeId, msg) => { lastMsg = msg; evt.Set(); return true; }); messaging1.LocalListen(listener, topic); foreach (var msg in Objects.Where(x => x != null)) { messaging2.Send(msg, topic); evt.WaitOne(500); Assert.AreEqual(msg, lastMsg); } messaging1.StopLocalListen(listener, topic); } /// <summary> /// Tests LocalListen. /// </summary> [Test] public void TestLocalListen() { TestLocalListen(NextId()); foreach (var topic in Objects) { TestLocalListen(topic); } } /// <summary> /// Tests LocalListen. /// </summary> [SuppressMessage("ReSharper", "AccessToModifiedClosure")] private void TestLocalListen(object topic) { var messaging = _grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); messaging.LocalListen(listener, topic); // Test sending CheckSend(topic); CheckSend(topic, _grid2); CheckSend(topic, _grid3); // Test different topic CheckNoMessage(NextId()); CheckNoMessage(NextId(), _grid2); // Test multiple subscriptions for the same filter messaging.LocalListen(listener, topic); messaging.LocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 3); // expect all messages repeated 3 times messaging.StopLocalListen(listener, topic); CheckSend(topic, repeatMultiplier: 2); // expect all messages repeated 2 times messaging.StopLocalListen(listener, topic); CheckSend(topic); // back to 1 listener // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen MessagingTestHelper.ListenResult = false; CheckSend(topic, single: true); // we'll receive one more and then unsubscribe because of delegate result. CheckNoMessage(topic); // Start again MessagingTestHelper.ListenResult = true; messaging.LocalListen(listener, topic); CheckSend(topic); // Stop messaging.StopLocalListen(listener, topic); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen with projection. /// </summary> [Test] public void TestLocalListenProjection() { TestLocalListenProjection(NextId()); TestLocalListenProjection("prj"); foreach (var topic in Objects) { TestLocalListenProjection(topic); } } /// <summary> /// Tests LocalListen with projection. /// </summary> private void TestLocalListenProjection(object topic) { var grid3GotMessage = false; var grid3Listener = new MessageListener<string>((id, x) => { grid3GotMessage = true; return true; }); _grid3.GetMessaging().LocalListen(grid3Listener, topic); var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); clusterMessaging.LocalListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); CheckSend(grid: _grid2, msg: clusterMessaging, topic: topic); Assert.IsFalse(grid3GotMessage, "Grid3 should not get messages"); clusterMessaging.StopLocalListen(clusterListener, topic); _grid3.GetMessaging().StopLocalListen(grid3Listener, topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [SuppressMessage("ReSharper", "AccessToModifiedClosure")] [Category(TestUtils.CategoryIntensive)] public void TestLocalListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = Task.Factory.StartNew(() => TestUtils.RunMultiThreaded(() => { messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedReceived = 0; var sharedListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref sharedReceived); Thread.MemoryBarrier(); return true; }); TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.LocalListen(sharedListener); for (int i = 0; i < 100; i++) { messaging.LocalListen(sharedListener); messaging.StopLocalListen(sharedListener); } var localReceived = 0; var stopLocal = 0; var localListener = new MessageListener<string>((id, x) => { Interlocked.Increment(ref localReceived); Thread.MemoryBarrier(); return Thread.VolatileRead(ref stopLocal) == 0; }); messaging.LocalListen(localListener); Thread.Sleep(100); Thread.VolatileWrite(ref stopLocal, 1); Thread.Sleep(1000); var result = Thread.VolatileRead(ref localReceived); Thread.Sleep(100); // Check that unsubscription worked properly Assert.AreEqual(result, Thread.VolatileRead(ref localReceived)); messaging.StopLocalListen(sharedListener); }, threadCnt, runSeconds); senders.Wait(); Thread.Sleep(100); var sharedResult = Thread.VolatileRead(ref sharedReceived); messaging.Send(NextMessage()); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly Assert.AreEqual(sharedResult, Thread.VolatileRead(ref sharedReceived)); } /// <summary> /// Tests RemoteListen. /// </summary> [Test] public void TestRemoteListen([Values(true, false)] bool async) { TestRemoteListen(NextId(), async); foreach (var topic in Objects) { TestRemoteListen(topic, async); } } /// <summary> /// Tests RemoteListen. /// </summary> private void TestRemoteListen(object topic, bool async = false) { var messaging =_grid1.GetMessaging(); var listener = MessagingTestHelper.GetListener(); var listenId = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); // Test sending CheckSend(topic, msg: messaging, remoteListen: true); // Test different topic CheckNoMessage(NextId()); // Test multiple subscriptions for the same filter var listenId2 = async ? messaging.RemoteListenAsync(listener, topic).Result : messaging.RemoteListen(listener, topic); CheckSend(topic, msg: messaging, remoteListen: true, repeatMultiplier: 2); // expect twice the messages if (async) messaging.StopRemoteListenAsync(listenId2).Wait(); else messaging.StopRemoteListen(listenId2); CheckSend(topic, msg: messaging, remoteListen: true); // back to normal after unsubscription // Test message type mismatch var ex = Assert.Throws<IgniteException>(() => messaging.Send(1.1, topic)); Assert.AreEqual("Unable to cast object of type 'System.Double' to type 'System.String'.", ex.Message); // Test end listen if (async) messaging.StopRemoteListenAsync(listenId).Wait(); else messaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests RemoteListen with a projection. /// </summary> [Test] public void TestRemoteListenProjection() { TestRemoteListenProjection(NextId()); foreach (var topic in Objects) { TestRemoteListenProjection(topic); } } /// <summary> /// Tests RemoteListen with a projection. /// </summary> private void TestRemoteListenProjection(object topic) { var clusterMessaging = _grid1.GetCluster().ForNodes(_grid1.GetCluster().GetLocalNode(), _grid2.GetCluster().GetLocalNode()).GetMessaging(); var clusterListener = MessagingTestHelper.GetListener(); var listenId = clusterMessaging.RemoteListen(clusterListener, topic); CheckSend(msg: clusterMessaging, topic: topic, remoteListen: true); clusterMessaging.StopRemoteListen(listenId); CheckNoMessage(topic); } /// <summary> /// Tests LocalListen in multithreaded mode. /// </summary> [Test] [Category(TestUtils.CategoryIntensive)] public void TestRemoteListenMultithreaded() { const int threadCnt = 20; const int runSeconds = 20; var messaging = _grid1.GetMessaging(); var senders = Task.Factory.StartNew(() => TestUtils.RunMultiThreaded(() => { MessagingTestHelper.ClearReceived(int.MaxValue); messaging.Send(NextMessage()); Thread.Sleep(50); }, threadCnt, runSeconds)); var sharedListener = MessagingTestHelper.GetListener(); for (int i = 0; i < 100; i++) messaging.RemoteListen(sharedListener); // add some listeners to be stopped by filter result TestUtils.RunMultiThreaded(() => { // Check that listen/stop work concurrently messaging.StopRemoteListen(messaging.RemoteListen(sharedListener)); }, threadCnt, runSeconds / 2); MessagingTestHelper.ListenResult = false; messaging.Send(NextMessage()); // send a message to make filters return false Thread.Sleep(MessagingTestHelper.SleepTimeout); // wait for all to unsubscribe MessagingTestHelper.ListenResult = true; senders.Wait(); // wait for senders to stop MessagingTestHelper.ClearReceived(int.MaxValue); var lastMsg = NextMessage(); messaging.Send(lastMsg); Thread.Sleep(MessagingTestHelper.SleepTimeout); // Check that unsubscription worked properly var sharedResult = MessagingTestHelper.ReceivedMessages.ToArray(); if (sharedResult.Length != 0) { Assert.Fail("Unexpected messages ({0}): {1}; last sent message: {2}", sharedResult.Length, string.Join(",", sharedResult), lastMsg); } } /// <summary> /// Sends messages in various ways and verefies correct receival. /// </summary> /// <param name="topic">Topic.</param> /// <param name="grid">The grid to use.</param> /// <param name="msg">Messaging to use.</param> /// <param name="remoteListen">Whether to expect remote listeners.</param> /// <param name="single">When true, only check one message.</param> /// <param name="repeatMultiplier">Expected message count multiplier.</param> private void CheckSend(object topic = null, IIgnite grid = null, IMessaging msg = null, bool remoteListen = false, bool single = false, int repeatMultiplier = 1) { IClusterGroup cluster; if (msg != null) cluster = msg.ClusterGroup; else { grid = grid ?? _grid1; msg = grid.GetMessaging(); cluster = grid.GetCluster().ForLocal(); } // Messages will repeat due to multiple nodes listening var expectedRepeat = repeatMultiplier * (remoteListen ? cluster.GetNodes().Count : 1); var messages = Enumerable.Range(1, 10).Select(x => NextMessage()).OrderBy(x => x).ToList(); // Single message MessagingTestHelper.ClearReceived(expectedRepeat); msg.Send(messages[0], topic); MessagingTestHelper.VerifyReceive(cluster, messages.Take(1), m => m.ToList(), expectedRepeat); if (single) return; // Multiple messages (receive order is undefined) MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); msg.SendAll(messages, topic); MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); // Multiple messages, ordered MessagingTestHelper.ClearReceived(messages.Count * expectedRepeat); messages.ForEach(x => msg.SendOrdered(x, topic, MessagingTestHelper.MessageTimeout)); if (remoteListen) // in remote scenario messages get mixed up due to different timing on different nodes MessagingTestHelper.VerifyReceive(cluster, messages, m => m.OrderBy(x => x), expectedRepeat); else MessagingTestHelper.VerifyReceive(cluster, messages, m => m.Reverse(), expectedRepeat); } /// <summary> /// Checks that no message has arrived. /// </summary> private void CheckNoMessage(object topic, IIgnite grid = null) { // this will result in an exception in case of a message MessagingTestHelper.ClearReceived(0); (grid ?? _grid1).GetMessaging().SendAll(NextMessage(), topic); Thread.Sleep(MessagingTestHelper.SleepTimeout); MessagingTestHelper.AssertFailures(); } /// <summary> /// Gets the Ignite configuration. /// </summary> private static IgniteConfiguration GetConfiguration(string name) { return new IgniteConfiguration(TestUtils.GetTestConfiguration()) { IgniteInstanceName = name }; } /// <summary> /// Generates next message with sequential ID and current test name. /// </summary> private static string NextMessage() { var id = NextId(); return id + "_" + TestContext.CurrentContext.Test.Name; } /// <summary> /// Generates next sequential ID. /// </summary> private static int NextId() { return Interlocked.Increment(ref _messageId); } } /// <summary> /// Messaging test helper class. /// </summary> [Serializable] public static class MessagingTestHelper { /** */ public static readonly ConcurrentStack<string> ReceivedMessages = new ConcurrentStack<string>(); /** */ private static readonly ConcurrentStack<string> Failures = new ConcurrentStack<string>(); /** */ private static readonly CountdownEvent ReceivedEvent = new CountdownEvent(0); /** */ private static readonly ConcurrentStack<Guid> LastNodeIds = new ConcurrentStack<Guid>(); /** */ public static volatile bool ListenResult = true; /** */ public static readonly TimeSpan MessageTimeout = TimeSpan.FromMilliseconds(5000); /** */ public static readonly TimeSpan SleepTimeout = TimeSpan.FromMilliseconds(50); /// <summary> /// Clears received message information. /// </summary> /// <param name="expectedCount">The expected count of messages to be received.</param> public static void ClearReceived(int expectedCount) { ReceivedMessages.Clear(); ReceivedEvent.Reset(expectedCount); LastNodeIds.Clear(); } /// <summary> /// Verifies received messages against expected messages. /// </summary> /// <param name="cluster">Cluster.</param> /// <param name="expectedMessages">Expected messages.</param> /// <param name="resultFunc">Result transform function.</param> /// <param name="expectedRepeat">Expected repeat count.</param> public static void VerifyReceive(IClusterGroup cluster, IEnumerable<string> expectedMessages, Func<IEnumerable<string>, IEnumerable<string>> resultFunc, int expectedRepeat) { // check if expected message count has been received; Wait returns false if there were none. Assert.IsTrue(ReceivedEvent.Wait(MessageTimeout), string.Format("expectedMessages: {0}, expectedRepeat: {1}, remaining: {2}", expectedMessages, expectedRepeat, ReceivedEvent.CurrentCount)); expectedMessages = expectedMessages.SelectMany(x => Enumerable.Repeat(x, expectedRepeat)); Assert.AreEqual(expectedMessages, resultFunc(ReceivedMessages)); // check that all messages came from local node. var localNodeId = cluster.Ignite.GetCluster().GetLocalNode().Id; Assert.AreEqual(localNodeId, LastNodeIds.Distinct().Single()); AssertFailures(); } /// <summary> /// Gets the message listener. /// </summary> /// <returns>New instance of message listener.</returns> public static IMessageListener<string> GetListener() { return new RemoteListener(); } /// <summary> /// Combines accumulated failures and throws an assertion, if there are any. /// Clears accumulated failures. /// </summary> public static void AssertFailures() { if (Failures.Any()) Assert.Fail(Failures.Reverse().Aggregate((x, y) => string.Format("{0}\n{1}", x, y))); Failures.Clear(); } /// <summary> /// Remote listener. /// </summary> private class RemoteListener : IMessageListener<string> { /** <inheritdoc /> */ public bool Invoke(Guid nodeId, string message) { try { LastNodeIds.Push(nodeId); ReceivedMessages.Push(message); ReceivedEvent.Signal(); return ListenResult; } catch (Exception ex) { // When executed on remote nodes, these exceptions will not go to sender, // so we have to accumulate them. Failures.Push(string.Format("Exception in Listen (msg: {0}, id: {1}): {2}", message, nodeId, ex)); throw; } } } } /// <summary> /// Test message filter. /// </summary> [Serializable] public class MessageListener<T> : IMessageListener<T> { /** */ private readonly Func<Guid, T, bool> _invoke; #pragma warning disable 649 /** Grid. */ [InstanceResource] private IIgnite _grid; #pragma warning restore 649 /// <summary> /// Initializes a new instance of the <see cref="MessageListener{T}"/> class. /// </summary> /// <param name="invoke">The invoke delegate.</param> public MessageListener(Func<Guid, T, bool> invoke) { _invoke = invoke; } /** <inheritdoc /> */ public bool Invoke(Guid nodeId, T message) { Assert.IsNotNull(_grid); return _invoke(nodeId, message); } } }
//============================================================================== // MyGeneration.dOOdads // // SqlClientDynamicQuery.cs // Version 5.00 // Updated - 10/08/2005 //------------------------------------------------------------------------------ // Copyright 2004, 2005 by MyGeneration Software. // All Rights Reserved. // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose and without fee is hereby granted, // provided that the above copyright notice appear in all copies and that // both that copyright notice and this permission notice appear in // supporting documentation. // // MYGENERATION SOFTWARE DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS // SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS, IN NO EVENT SHALL MYGENERATION SOFTWARE BE LIABLE FOR ANY // SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, // WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE // OR PERFORMANCE OF THIS SOFTWARE. //============================================================================== using System; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Collections; namespace MyGeneration.dOOdads { /// <summary> /// SqlClientDynamicQuery is the Microsoft SQL implementation of DynamicQuery /// </summary> public class SqlClientDynamicQuery : DynamicQuery { public SqlClientDynamicQuery(BusinessEntity entity) : base(entity) { } public override void AddOrderBy(string column, MyGeneration.dOOdads.WhereParameter.Dir direction) { base.AddOrderBy ("[" + column + "]", direction); } public override void AddOrderBy(DynamicQuery countAll, MyGeneration.dOOdads.WhereParameter.Dir direction) { if(countAll.CountAll) { base.AddOrderBy ("COUNT(*)", direction); } } public override void AddOrderBy(AggregateParameter aggregate, MyGeneration.dOOdads.WhereParameter.Dir direction) { base.AddOrderBy (GetAggregate(aggregate, false), direction); } public override void AddGroupBy(string column) { base.AddGroupBy ("[" + column + "]"); } public override void AddGroupBy(AggregateParameter aggregate) { // SQL Server does not support aggregates in a GROUP BY. // Common method base.AddGroupBy (GetAggregate(aggregate, false)); } public override void AddResultColumn(string columnName) { base.AddResultColumn ("[" + columnName + "]"); } protected string GetAggregate(AggregateParameter wItem, bool withAlias) { string query = string.Empty; switch(wItem.Function) { case AggregateParameter.Func.Avg: query += "AVG("; break; case AggregateParameter.Func.Count: query += "COUNT("; break; case AggregateParameter.Func.Max: query += "MAX("; break; case AggregateParameter.Func.Min: query += "MIN("; break; case AggregateParameter.Func.Sum: query += "SUM("; break; case AggregateParameter.Func.StdDev: query += "STDEV("; break; case AggregateParameter.Func.Var: query += "VAR("; break; } if(wItem.Distinct) { query += "DISTINCT "; } query += "[" + wItem.Column + "])"; if(withAlias && wItem.Alias != string.Empty) { // Need DBMS string delimiter here query += " AS '" + wItem.Alias + "'"; } return query; } override protected IDbCommand _Load(string conjuction) { bool hasColumn = false; bool selectAll = true; string query; query = "SELECT "; if( this._distinct) query += " DISTINCT "; if( this._top >= 0) query += " TOP " + this._top.ToString() + " "; if(this._resultColumns.Length > 0) { query += this._resultColumns; hasColumn = true; selectAll = false; } if(this._countAll) { if(hasColumn) { query += ", "; } query += "COUNT(*)"; if(this._countAllAlias != string.Empty) { // Need DBMS string delimiter here query += " AS '" + this._countAllAlias + "'"; } hasColumn = true; selectAll = false; } if(_aggregateParameters != null && _aggregateParameters.Count > 0) { bool isFirst = true; if(hasColumn) { query += ", "; } AggregateParameter wItem; foreach(object obj in _aggregateParameters) { wItem = obj as AggregateParameter; if(wItem.IsDirty) { if(isFirst) { query += GetAggregate(wItem, true); isFirst = false; } else { query += ", " + GetAggregate(wItem, true); } } } selectAll = false; } if(selectAll) { query += "*"; } query += " FROM [" + this._entity.QuerySource + "]"; SqlCommand cmd = new SqlCommand(); if(_whereParameters != null && _whereParameters.Count > 0) { query += " WHERE "; bool first = true; bool requiresParam; WhereParameter wItem; bool skipConjuction = false; string paramName; string columnName; foreach(object obj in _whereParameters) { // Maybe we injected text or a WhereParameter if(obj.GetType().ToString() == "System.String") { string text = obj as string; query += text; if(text == "(") { skipConjuction = true; } } else { wItem = obj as WhereParameter; if(wItem.IsDirty) { if(!first && !skipConjuction) { if(wItem.Conjuction != WhereParameter.Conj.UseDefault) { if(wItem.Conjuction == WhereParameter.Conj.And) query += " AND "; else query += " OR "; } else { query += " " + conjuction + " "; } } requiresParam = true; columnName = "[" + wItem.Column + "]"; paramName = "@" + wItem.Column + (++inc).ToString(); wItem.Param.ParameterName = paramName; switch(wItem.Operator) { case WhereParameter.Operand.Equal: query += columnName + " = " + paramName + " "; break; case WhereParameter.Operand.NotEqual: query += columnName + " <> " + paramName + " "; break; case WhereParameter.Operand.GreaterThan: query += columnName + " > " + paramName + " "; break; case WhereParameter.Operand.LessThan: query += columnName + " < " + paramName + " "; break; case WhereParameter.Operand.LessThanOrEqual: query += columnName + " <= " + paramName + " "; break; case WhereParameter.Operand.GreaterThanOrEqual: query += columnName + " >= " + paramName + " "; break; case WhereParameter.Operand.Like: query += columnName + " LIKE " + paramName + " "; break; case WhereParameter.Operand.NotLike: query += columnName + " NOT LIKE " + paramName + " "; break; case WhereParameter.Operand.IsNull: query += columnName + " IS NULL "; requiresParam = false; break; case WhereParameter.Operand.IsNotNull: query += columnName + " IS NOT NULL "; requiresParam = false; break; case WhereParameter.Operand.In: query += columnName + " IN (" + wItem.Value + ") "; requiresParam = false; break; case WhereParameter.Operand.NotIn: query += columnName + " NOT IN (" + wItem.Value + ") "; requiresParam = false; break; case WhereParameter.Operand.Between: query += columnName + " BETWEEN " + paramName; AddParameter(cmd, paramName, wItem.BetweenBeginValue); paramName = "@" + wItem.Column + (++inc).ToString(); query += " AND " + paramName; AddParameter(cmd, paramName, wItem.BetweenEndValue); requiresParam = false; break; } if(requiresParam) { IDbCommand dbCmd = cmd as IDbCommand; dbCmd.Parameters.Add(wItem.Param); wItem.Param.Value = wItem.Value; } first = false; skipConjuction = false; } } } } if(_groupBy.Length > 0) { query += " GROUP BY " + _groupBy; if(this._withRollup) { query += " WITH ROLLUP"; } } if(_orderBy.Length > 0) { query += " ORDER BY " + _orderBy; } cmd.CommandText = query; return cmd; } private void AddParameter(SqlCommand cmd, string paramName, object data) { #if(VS2005) cmd.Parameters.AddWithValue(paramName, data); #else cmd.Parameters.Add(paramName, data); #endif } } }
// // LibrarySource.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2005-2007 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Unix; using Hyena; using Hyena.Collections; using Hyena.Data.Sqlite; using Banshee.Base; using Banshee.Sources; using Banshee.Database; using Banshee.ServiceStack; using Banshee.Preferences; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Configuration; namespace Banshee.Library { public abstract class LibrarySource : PrimarySource { // Deprecated, don't use in new code internal static readonly Banshee.Configuration.SchemaEntry<string> OldLocationSchema = new Banshee.Configuration.SchemaEntry<string> ("library", "base_location", null, null, null); internal static readonly Banshee.Configuration.SchemaEntry<bool> OldImportSetting = new Banshee.Configuration.SchemaEntry<bool> ("library", "copy_on_import", false, null, null); internal static readonly Banshee.Configuration.SchemaEntry<bool> OldRenameSetting = new Banshee.Configuration.SchemaEntry<bool> ("library", "move_on_info_save", false, null, null); private Banshee.Configuration.SchemaEntry<string> base_dir_schema; private Banshee.Configuration.SchemaEntry<bool> copy_on_import; private Banshee.Configuration.SchemaEntry<bool> move_files; public LibrarySource (string label, string name, int order) : base (label, label, name, order) { Properties.SetString ("GtkActionPath", "/LibraryContextMenu"); Properties.SetString ("RemoveTracksActionLabel", Catalog.GetString ("Remove From Library")); IsLocal = true; base_dir_schema = CreateSchema<string> ("library-location", null, "The base directory under which files for this library are stored", null); copy_on_import = CreateSchema<bool> ("copy-on-import", false, "Copy files on import", "Copy and rename files to library directory when importing"); move_files = CreateSchema<bool>("move-on-info-save", false, "Move files on info save", "Move files within the library directory when saving track info"); AfterInitialized (); Section library_section = PreferencesPage.Add (new Section ("library-location", SectionName, 2)); library_section.Add (base_dir_schema); if (this.HasCopyOnImport || this.HasMoveFiles) { var file_system = PreferencesPage.FindOrAdd ( new Section ("file-system", Catalog.GetString ("File Organization"), 5)); if (this.HasCopyOnImport) { file_system.Add (new SchemaPreference<bool> ( copy_on_import, Catalog.GetString ("Co_py files to media folder when importing"))); } if (this.HasMoveFiles) { file_system.Add (new SchemaPreference<bool> ( move_files, Catalog.GetString ("_Update file and folder names"), Catalog.GetString ("Rename files and folders according to media metadata") )); } } } public string AttributesCondition { get { return String.Format ("((CoreTracks.Attributes & {0}) == {0} AND (CoreTracks.Attributes & {1}) == 0)", (int)MediaTypes, (int)NotMediaTypes); } } private string sync_condition; public string SyncCondition { get { return sync_condition; } protected set { sync_condition = value; } } private TrackMediaAttributes media_types; protected TrackMediaAttributes MediaTypes { get { return media_types; } set { media_types = value; } } private TrackMediaAttributes not_media_types = TrackMediaAttributes.None; protected TrackMediaAttributes NotMediaTypes { get { return not_media_types; } set { not_media_types = value; } } public override string PreferencesPageId { get { return UniqueId; } } public override bool HasEditableTrackProperties { get { return true; } } public override string BaseDirectory { get { string dir = base_dir_schema.Get (); if (dir == null) { BaseDirectory = dir = DefaultBaseDirectory; } return dir; } protected set { base_dir_schema.Set (value); base.BaseDirectory = value; } } public abstract string DefaultBaseDirectory { get; } public bool CopyOnImport { get { return copy_on_import.Get (); } protected set { copy_on_import.Set (value); } } public virtual bool HasCopyOnImport { get { return false; } } public bool MoveFiles { get { return move_files.Get (); } protected set { move_files.Set (value); } } public virtual bool HasMoveFiles { get { return false; } } public override bool Indexable { get { return true; } } protected virtual string SectionName { get { // Translators: {0} is the library name, eg 'Music Library' or 'Podcasts' return String.Format (Catalog.GetString ("{0} Folder"), Name); } } /*public override void CopyTrackTo (DatabaseTrackInfo track, SafeUri uri, UserJob job) { Banshee.IO.File.Copy (track.Uri, uri, false); }*/ protected override void AddTrack (DatabaseTrackInfo track) { // Ignore if already have it if (track.PrimarySourceId == DbId) return; PrimarySource source = track.PrimarySource; // If it's from a local primary source, change its PrimarySource if (source.IsLocal || source is LibrarySource) { track.PrimarySource = this; if (!(source is LibrarySource)) { track.CopyToLibraryIfAppropriate (false); } track.Save (false); // TODO optimize, remove this? I think it makes moving items // between local libraries very slow. //source.NotifyTracksChanged (); } else { // Figure out where we should put it if were to copy it var pattern = this.PathPattern ?? MusicLibrarySource.MusicFileNamePattern; string path = pattern.BuildFull (BaseDirectory, track); SafeUri uri = new SafeUri (path); // Make sure it's not already in the library // TODO optimize - no need to recreate this int [] every time if (DatabaseTrackInfo.ContainsUri (uri, new int [] {DbId})) { return; } // Since it's not, copy it and create a new TrackInfo object track.PrimarySource.CopyTrackTo (track, uri, AddTrackJob); // Create a new entry in CoreTracks for the copied file DatabaseTrackInfo new_track = new DatabaseTrackInfo (track); new_track.Uri = uri; new_track.PrimarySource = this; new_track.Save (false); } } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/protobuf/type.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Protobuf { namespace Proto { [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Type { #region Descriptor public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static Type() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Chpnb29nbGUvcHJvdG9idWYvdHlwZS5wcm90bxIPZ29vZ2xlLnByb3RvYnVm", "Ghlnb29nbGUvcHJvdG9idWYvYW55LnByb3RvGiRnb29nbGUvcHJvdG9idWYv", "c291cmNlX2NvbnRleHQucHJvdG8irgEKBFR5cGUSDAoEbmFtZRgBIAEoCRIm", "CgZmaWVsZHMYAiADKAsyFi5nb29nbGUucHJvdG9idWYuRmllbGQSDgoGb25l", "b2ZzGAMgAygJEigKB29wdGlvbnMYBCADKAsyFy5nb29nbGUucHJvdG9idWYu", "T3B0aW9uEjYKDnNvdXJjZV9jb250ZXh0GAUgASgLMh4uZ29vZ2xlLnByb3Rv", "YnVmLlNvdXJjZUNvbnRleHQimwUKBUZpZWxkEikKBGtpbmQYASABKA4yGy5n", "b29nbGUucHJvdG9idWYuRmllbGQuS2luZBI3CgtjYXJkaW5hbGl0eRgCIAEo", "DjIiLmdvb2dsZS5wcm90b2J1Zi5GaWVsZC5DYXJkaW5hbGl0eRIOCgZudW1i", "ZXIYAyABKAUSDAoEbmFtZRgEIAEoCRIQCgh0eXBlX3VybBgGIAEoCRITCgtv", "bmVvZl9pbmRleBgHIAEoBRIOCgZwYWNrZWQYCCABKAgSKAoHb3B0aW9ucxgJ", "IAMoCzIXLmdvb2dsZS5wcm90b2J1Zi5PcHRpb24iuAIKBEtpbmQSEAoMVFlQ", "RV9VTktOT1dOEAASDwoLVFlQRV9ET1VCTEUQARIOCgpUWVBFX0ZMT0FUEAIS", "DgoKVFlQRV9JTlQ2NBADEg8KC1RZUEVfVUlOVDY0EAQSDgoKVFlQRV9JTlQz", "MhAFEhAKDFRZUEVfRklYRUQ2NBAGEhAKDFRZUEVfRklYRUQzMhAHEg0KCVRZ", "UEVfQk9PTBAIEg8KC1RZUEVfU1RSSU5HEAkSEAoMVFlQRV9NRVNTQUdFEAsS", "DgoKVFlQRV9CWVRFUxAMEg8KC1RZUEVfVUlOVDMyEA0SDQoJVFlQRV9FTlVN", "EA4SEQoNVFlQRV9TRklYRUQzMhAPEhEKDVRZUEVfU0ZJWEVENjQQEBIPCgtU", "WVBFX1NJTlQzMhAREg8KC1RZUEVfU0lOVDY0EBIidAoLQ2FyZGluYWxpdHkS", "FwoTQ0FSRElOQUxJVFlfVU5LTk9XThAAEhgKFENBUkRJTkFMSVRZX09QVElP", "TkFMEAESGAoUQ0FSRElOQUxJVFlfUkVRVUlSRUQQAhIYChRDQVJESU5BTElU", "WV9SRVBFQVRFRBADIqUBCgRFbnVtEgwKBG5hbWUYASABKAkSLQoJZW51bXZh", "bHVlGAIgAygLMhouZ29vZ2xlLnByb3RvYnVmLkVudW1WYWx1ZRIoCgdvcHRp", "b25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbhI2Cg5zb3VyY2Vf", "Y29udGV4dBgEIAEoCzIeLmdvb2dsZS5wcm90b2J1Zi5Tb3VyY2VDb250ZXh0", "IlMKCUVudW1WYWx1ZRIMCgRuYW1lGAEgASgJEg4KBm51bWJlchgCIAEoBRIo", "CgdvcHRpb25zGAMgAygLMhcuZ29vZ2xlLnByb3RvYnVmLk9wdGlvbiI7CgZP", "cHRpb24SDAoEbmFtZRgBIAEoCRIjCgV2YWx1ZRgCIAEoCzIULmdvb2dsZS5w", "cm90b2J1Zi5BbnlCIgoTY29tLmdvb2dsZS5wcm90b2J1ZkIJVHlwZVByb3Rv", "UAFiBnByb3RvMw==")); descriptor = pbr::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbr::FileDescriptor[] { global::Google.Protobuf.Proto.Any.Descriptor, global::Google.Protobuf.Proto.SourceContext.Descriptor, }, new pbr::GeneratedCodeInfo(null, new pbr::GeneratedCodeInfo[] { new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Type), new[]{ "Name", "Fields", "Oneofs", "Options", "SourceContext" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Field), new[]{ "Kind", "Cardinality", "Number", "Name", "TypeUrl", "OneofIndex", "Packed", "Options" }, null, new[]{ typeof(global::Google.Protobuf.Field.Types.Kind), typeof(global::Google.Protobuf.Field.Types.Cardinality) }, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Enum), new[]{ "Name", "Enumvalue", "Options", "SourceContext" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.EnumValue), new[]{ "Name", "Number", "Options" }, null, null, null), new pbr::GeneratedCodeInfo(typeof(global::Google.Protobuf.Option), new[]{ "Name", "Value" }, null, null, null) })); } #endregion } } #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Type : pb::IMessage<Type> { private static readonly pb::MessageParser<Type> _parser = new pb::MessageParser<Type>(() => new Type()); public static pb::MessageParser<Type> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Proto.Type.Descriptor.MessageTypes[0]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Type() { OnConstruction(); } partial void OnConstruction(); public Type(Type other) : this() { name_ = other.name_; fields_ = other.fields_.Clone(); oneofs_ = other.oneofs_.Clone(); options_ = other.options_.Clone(); SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; } public Type Clone() { return new Type(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int FieldsFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.Field> _repeated_fields_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.Field.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Field> fields_ = new pbc::RepeatedField<global::Google.Protobuf.Field>(); public pbc::RepeatedField<global::Google.Protobuf.Field> Fields { get { return fields_; } } public const int OneofsFieldNumber = 3; private static readonly pb::FieldCodec<string> _repeated_oneofs_codec = pb::FieldCodec.ForString(26); private readonly pbc::RepeatedField<string> oneofs_ = new pbc::RepeatedField<string>(); public pbc::RepeatedField<string> Oneofs { get { return oneofs_; } } public const int OptionsFieldNumber = 4; private static readonly pb::FieldCodec<global::Google.Protobuf.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(34, global::Google.Protobuf.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.Option>(); public pbc::RepeatedField<global::Google.Protobuf.Option> Options { get { return options_; } } public const int SourceContextFieldNumber = 5; private global::Google.Protobuf.SourceContext sourceContext_; public global::Google.Protobuf.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } public override bool Equals(object other) { return Equals(other as Type); } public bool Equals(Type other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!fields_.Equals(other.fields_)) return false; if(!oneofs_.Equals(other.oneofs_)) return false; if(!options_.Equals(other.options_)) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= fields_.GetHashCode(); hash ^= oneofs_.GetHashCode(); hash ^= options_.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } fields_.WriteTo(output, _repeated_fields_codec); oneofs_.WriteTo(output, _repeated_oneofs_codec); options_.WriteTo(output, _repeated_options_codec); if (sourceContext_ != null) { output.WriteRawTag(42); output.WriteMessage(SourceContext); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += fields_.CalculateSize(_repeated_fields_codec); size += oneofs_.CalculateSize(_repeated_oneofs_codec); size += options_.CalculateSize(_repeated_options_codec); if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } return size; } public void MergeFrom(Type other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } fields_.Add(other.fields_); oneofs_.Add(other.oneofs_); options_.Add(other.options_); if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { fields_.AddEntriesFrom(input, _repeated_fields_codec); break; } case 26: { oneofs_.AddEntriesFrom(input, _repeated_oneofs_codec); break; } case 34: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 42: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.SourceContext(); } input.ReadMessage(sourceContext_); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Field : pb::IMessage<Field> { private static readonly pb::MessageParser<Field> _parser = new pb::MessageParser<Field>(() => new Field()); public static pb::MessageParser<Field> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Proto.Type.Descriptor.MessageTypes[1]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Field() { OnConstruction(); } partial void OnConstruction(); public Field(Field other) : this() { kind_ = other.kind_; cardinality_ = other.cardinality_; number_ = other.number_; name_ = other.name_; typeUrl_ = other.typeUrl_; oneofIndex_ = other.oneofIndex_; packed_ = other.packed_; options_ = other.options_.Clone(); } public Field Clone() { return new Field(this); } public const int KindFieldNumber = 1; private global::Google.Protobuf.Field.Types.Kind kind_ = global::Google.Protobuf.Field.Types.Kind.TYPE_UNKNOWN; public global::Google.Protobuf.Field.Types.Kind Kind { get { return kind_; } set { kind_ = value; } } public const int CardinalityFieldNumber = 2; private global::Google.Protobuf.Field.Types.Cardinality cardinality_ = global::Google.Protobuf.Field.Types.Cardinality.CARDINALITY_UNKNOWN; public global::Google.Protobuf.Field.Types.Cardinality Cardinality { get { return cardinality_; } set { cardinality_ = value; } } public const int NumberFieldNumber = 3; private int number_; public int Number { get { return number_; } set { number_ = value; } } public const int NameFieldNumber = 4; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int TypeUrlFieldNumber = 6; private string typeUrl_ = ""; public string TypeUrl { get { return typeUrl_; } set { typeUrl_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int OneofIndexFieldNumber = 7; private int oneofIndex_; public int OneofIndex { get { return oneofIndex_; } set { oneofIndex_ = value; } } public const int PackedFieldNumber = 8; private bool packed_; public bool Packed { get { return packed_; } set { packed_ = value; } } public const int OptionsFieldNumber = 9; private static readonly pb::FieldCodec<global::Google.Protobuf.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(74, global::Google.Protobuf.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.Option>(); public pbc::RepeatedField<global::Google.Protobuf.Option> Options { get { return options_; } } public override bool Equals(object other) { return Equals(other as Field); } public bool Equals(Field other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Kind != other.Kind) return false; if (Cardinality != other.Cardinality) return false; if (Number != other.Number) return false; if (Name != other.Name) return false; if (TypeUrl != other.TypeUrl) return false; if (OneofIndex != other.OneofIndex) return false; if (Packed != other.Packed) return false; if(!options_.Equals(other.options_)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Kind != global::Google.Protobuf.Field.Types.Kind.TYPE_UNKNOWN) hash ^= Kind.GetHashCode(); if (Cardinality != global::Google.Protobuf.Field.Types.Cardinality.CARDINALITY_UNKNOWN) hash ^= Cardinality.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); if (Name.Length != 0) hash ^= Name.GetHashCode(); if (TypeUrl.Length != 0) hash ^= TypeUrl.GetHashCode(); if (OneofIndex != 0) hash ^= OneofIndex.GetHashCode(); if (Packed != false) hash ^= Packed.GetHashCode(); hash ^= options_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Kind != global::Google.Protobuf.Field.Types.Kind.TYPE_UNKNOWN) { output.WriteRawTag(8); output.WriteEnum((int) Kind); } if (Cardinality != global::Google.Protobuf.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { output.WriteRawTag(16); output.WriteEnum((int) Cardinality); } if (Number != 0) { output.WriteRawTag(24); output.WriteInt32(Number); } if (Name.Length != 0) { output.WriteRawTag(34); output.WriteString(Name); } if (TypeUrl.Length != 0) { output.WriteRawTag(50); output.WriteString(TypeUrl); } if (OneofIndex != 0) { output.WriteRawTag(56); output.WriteInt32(OneofIndex); } if (Packed != false) { output.WriteRawTag(64); output.WriteBool(Packed); } options_.WriteTo(output, _repeated_options_codec); } public int CalculateSize() { int size = 0; if (Kind != global::Google.Protobuf.Field.Types.Kind.TYPE_UNKNOWN) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Kind); } if (Cardinality != global::Google.Protobuf.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { size += 1 + pb::CodedOutputStream.ComputeEnumSize((int) Cardinality); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (TypeUrl.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(TypeUrl); } if (OneofIndex != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(OneofIndex); } if (Packed != false) { size += 1 + 1; } size += options_.CalculateSize(_repeated_options_codec); return size; } public void MergeFrom(Field other) { if (other == null) { return; } if (other.Kind != global::Google.Protobuf.Field.Types.Kind.TYPE_UNKNOWN) { Kind = other.Kind; } if (other.Cardinality != global::Google.Protobuf.Field.Types.Cardinality.CARDINALITY_UNKNOWN) { Cardinality = other.Cardinality; } if (other.Number != 0) { Number = other.Number; } if (other.Name.Length != 0) { Name = other.Name; } if (other.TypeUrl.Length != 0) { TypeUrl = other.TypeUrl; } if (other.OneofIndex != 0) { OneofIndex = other.OneofIndex; } if (other.Packed != false) { Packed = other.Packed; } options_.Add(other.options_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 8: { kind_ = (global::Google.Protobuf.Field.Types.Kind) input.ReadEnum(); break; } case 16: { cardinality_ = (global::Google.Protobuf.Field.Types.Cardinality) input.ReadEnum(); break; } case 24: { Number = input.ReadInt32(); break; } case 34: { Name = input.ReadString(); break; } case 50: { TypeUrl = input.ReadString(); break; } case 56: { OneofIndex = input.ReadInt32(); break; } case 64: { Packed = input.ReadBool(); break; } case 74: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } } } } #region Nested types [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Types { public enum Kind { TYPE_UNKNOWN = 0, TYPE_DOUBLE = 1, TYPE_FLOAT = 2, TYPE_INT64 = 3, TYPE_UINT64 = 4, TYPE_INT32 = 5, TYPE_FIXED64 = 6, TYPE_FIXED32 = 7, TYPE_BOOL = 8, TYPE_STRING = 9, TYPE_MESSAGE = 11, TYPE_BYTES = 12, TYPE_UINT32 = 13, TYPE_ENUM = 14, TYPE_SFIXED32 = 15, TYPE_SFIXED64 = 16, TYPE_SINT32 = 17, TYPE_SINT64 = 18, } public enum Cardinality { CARDINALITY_UNKNOWN = 0, CARDINALITY_OPTIONAL = 1, CARDINALITY_REQUIRED = 2, CARDINALITY_REPEATED = 3, } } #endregion } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Enum : pb::IMessage<Enum> { private static readonly pb::MessageParser<Enum> _parser = new pb::MessageParser<Enum>(() => new Enum()); public static pb::MessageParser<Enum> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Proto.Type.Descriptor.MessageTypes[2]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Enum() { OnConstruction(); } partial void OnConstruction(); public Enum(Enum other) : this() { name_ = other.name_; enumvalue_ = other.enumvalue_.Clone(); options_ = other.options_.Clone(); SourceContext = other.sourceContext_ != null ? other.SourceContext.Clone() : null; } public Enum Clone() { return new Enum(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int EnumvalueFieldNumber = 2; private static readonly pb::FieldCodec<global::Google.Protobuf.EnumValue> _repeated_enumvalue_codec = pb::FieldCodec.ForMessage(18, global::Google.Protobuf.EnumValue.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.EnumValue> enumvalue_ = new pbc::RepeatedField<global::Google.Protobuf.EnumValue>(); public pbc::RepeatedField<global::Google.Protobuf.EnumValue> Enumvalue { get { return enumvalue_; } } public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.Option>(); public pbc::RepeatedField<global::Google.Protobuf.Option> Options { get { return options_; } } public const int SourceContextFieldNumber = 4; private global::Google.Protobuf.SourceContext sourceContext_; public global::Google.Protobuf.SourceContext SourceContext { get { return sourceContext_; } set { sourceContext_ = value; } } public override bool Equals(object other) { return Equals(other as Enum); } public bool Equals(Enum other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if(!enumvalue_.Equals(other.enumvalue_)) return false; if(!options_.Equals(other.options_)) return false; if (!object.Equals(SourceContext, other.SourceContext)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); hash ^= enumvalue_.GetHashCode(); hash ^= options_.GetHashCode(); if (sourceContext_ != null) hash ^= SourceContext.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } enumvalue_.WriteTo(output, _repeated_enumvalue_codec); options_.WriteTo(output, _repeated_options_codec); if (sourceContext_ != null) { output.WriteRawTag(34); output.WriteMessage(SourceContext); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } size += enumvalue_.CalculateSize(_repeated_enumvalue_codec); size += options_.CalculateSize(_repeated_options_codec); if (sourceContext_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(SourceContext); } return size; } public void MergeFrom(Enum other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } enumvalue_.Add(other.enumvalue_); options_.Add(other.options_); if (other.sourceContext_ != null) { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.SourceContext(); } SourceContext.MergeFrom(other.SourceContext); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { enumvalue_.AddEntriesFrom(input, _repeated_enumvalue_codec); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } case 34: { if (sourceContext_ == null) { sourceContext_ = new global::Google.Protobuf.SourceContext(); } input.ReadMessage(sourceContext_); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class EnumValue : pb::IMessage<EnumValue> { private static readonly pb::MessageParser<EnumValue> _parser = new pb::MessageParser<EnumValue>(() => new EnumValue()); public static pb::MessageParser<EnumValue> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Proto.Type.Descriptor.MessageTypes[3]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public EnumValue() { OnConstruction(); } partial void OnConstruction(); public EnumValue(EnumValue other) : this() { name_ = other.name_; number_ = other.number_; options_ = other.options_.Clone(); } public EnumValue Clone() { return new EnumValue(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int NumberFieldNumber = 2; private int number_; public int Number { get { return number_; } set { number_ = value; } } public const int OptionsFieldNumber = 3; private static readonly pb::FieldCodec<global::Google.Protobuf.Option> _repeated_options_codec = pb::FieldCodec.ForMessage(26, global::Google.Protobuf.Option.Parser); private readonly pbc::RepeatedField<global::Google.Protobuf.Option> options_ = new pbc::RepeatedField<global::Google.Protobuf.Option>(); public pbc::RepeatedField<global::Google.Protobuf.Option> Options { get { return options_; } } public override bool Equals(object other) { return Equals(other as EnumValue); } public bool Equals(EnumValue other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (Number != other.Number) return false; if(!options_.Equals(other.options_)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (Number != 0) hash ^= Number.GetHashCode(); hash ^= options_.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (Number != 0) { output.WriteRawTag(16); output.WriteInt32(Number); } options_.WriteTo(output, _repeated_options_codec); } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (Number != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Number); } size += options_.CalculateSize(_repeated_options_codec); return size; } public void MergeFrom(EnumValue other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.Number != 0) { Number = other.Number; } options_.Add(other.options_); } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 16: { Number = input.ReadInt32(); break; } case 26: { options_.AddEntriesFrom(input, _repeated_options_codec); break; } } } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Option : pb::IMessage<Option> { private static readonly pb::MessageParser<Option> _parser = new pb::MessageParser<Option>(() => new Option()); public static pb::MessageParser<Option> Parser { get { return _parser; } } public static pbr::MessageDescriptor Descriptor { get { return global::Google.Protobuf.Proto.Type.Descriptor.MessageTypes[4]; } } pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } public Option() { OnConstruction(); } partial void OnConstruction(); public Option(Option other) : this() { name_ = other.name_; Value = other.value_ != null ? other.Value.Clone() : null; } public Option Clone() { return new Option(this); } public const int NameFieldNumber = 1; private string name_ = ""; public string Name { get { return name_; } set { name_ = pb::Preconditions.CheckNotNull(value, "value"); } } public const int ValueFieldNumber = 2; private global::Google.Protobuf.Any value_; public global::Google.Protobuf.Any Value { get { return value_; } set { value_ = value; } } public override bool Equals(object other) { return Equals(other as Option); } public bool Equals(Option other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Name != other.Name) return false; if (!object.Equals(Value, other.Value)) return false; return true; } public override int GetHashCode() { int hash = 1; if (Name.Length != 0) hash ^= Name.GetHashCode(); if (value_ != null) hash ^= Value.GetHashCode(); return hash; } public override string ToString() { return pb::JsonFormatter.Default.Format(this); } public void WriteTo(pb::CodedOutputStream output) { if (Name.Length != 0) { output.WriteRawTag(10); output.WriteString(Name); } if (value_ != null) { output.WriteRawTag(18); output.WriteMessage(Value); } } public int CalculateSize() { int size = 0; if (Name.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Name); } if (value_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Value); } return size; } public void MergeFrom(Option other) { if (other == null) { return; } if (other.Name.Length != 0) { Name = other.Name; } if (other.value_ != null) { if (value_ == null) { value_ = new global::Google.Protobuf.Any(); } Value.MergeFrom(other.Value); } } public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { Name = input.ReadString(); break; } case 18: { if (value_ == null) { value_ = new global::Google.Protobuf.Any(); } input.ReadMessage(value_); break; } } } } } #endregion } #endregion Designer generated code
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedNodeGroupsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = NodeGroup.Types.Status.Ready, MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = NodeGroup.Types.MaintenancePolicy.Unspecified, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = NodeGroup.Types.Status.Ready, MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = NodeGroup.Types.MaintenancePolicy.Unspecified, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NodeGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NodeGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = NodeGroup.Types.Status.Ready, MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = NodeGroup.Types.MaintenancePolicy.Unspecified, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup response = client.Get(request.Project, request.Zone, request.NodeGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNodeGroupRequest request = new GetNodeGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NodeGroup = "node_groupa42a295a", }; NodeGroup expectedResponse = new NodeGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", Status = NodeGroup.Types.Status.Ready, MaintenanceWindow = new NodeGroupMaintenanceWindow(), AutoscalingPolicy = new NodeGroupAutoscalingPolicy(), Fingerprint = "fingerprint009e6052", NodeTemplate = "node_template118e38ae", LocationHint = "location_hint666f366c", Description = "description2cf9da67", SelfLink = "self_link7e87f12d", MaintenancePolicy = NodeGroup.Types.MaintenancePolicy.Unspecified, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NodeGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); NodeGroup responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.NodeGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NodeGroup responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.NodeGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicyRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", OptionsRequestedPolicyVersion = -1471234741, }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void GetIamPolicy() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.GetIamPolicy(request.Project, request.Zone, request.Resource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetIamPolicyAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetIamPolicyNodeGroupRequest request = new GetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.GetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.GetIamPolicyAsync(request.Project, request.Zone, request.Resource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicyRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void SetIamPolicy() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicy(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy response = client.SetIamPolicy(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task SetIamPolicyAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); SetIamPolicyNodeGroupRequest request = new SetIamPolicyNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", ZoneSetPolicyRequestResource = new ZoneSetPolicyRequest(), }; Policy expectedResponse = new Policy { Etag = "etage8ad7218", Rules = { new Rule(), }, AuditConfigs = { new AuditConfig(), }, Version = 271578922, Bindings = { new Binding(), }, IamOwned = false, }; mockGrpcClient.Setup(x => x.SetIamPolicyAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<Policy>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); Policy responseCallSettings = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); Policy responseCancellationToken = await client.SetIamPolicyAsync(request.Project, request.Zone, request.Resource, request.ZoneSetPolicyRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<NodeGroups.NodeGroupsClient> mockGrpcClient = new moq::Mock<NodeGroups.NodeGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNodeGroupRequest request = new TestIamPermissionsNodeGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NodeGroupsClient client = new NodeGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsAzureCompositeModelClient { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// PolymorphismOperations operations. /// </summary> internal partial class PolymorphismOperations : IServiceOperations<AzureCompositeModel>, IPolymorphismOperations { /// <summary> /// Initializes a new instance of the PolymorphismOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PolymorphismOperations(AzureCompositeModel client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AzureCompositeModel /// </summary> public AzureCompositeModel Client { get; private set; } /// <summary> /// Get complex types that are polymorphic /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<Fish>> GetValidWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<Fish>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Fish>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that are polymorphic /// </summary> /// <param name='complexBody'> /// Please put a salmon that looks like this: /// { /// 'fishtype':'Salmon', /// 'location':'alaska', /// 'iswild':true, /// 'species':'king', /// 'length':1.0, /// 'siblings':[ /// { /// 'fishtype':'Shark', /// 'age':6, /// 'birthday': '2012-01-05T01:00:00Z', /// 'length':20.0, /// 'species':'predator', /// }, /// { /// 'fishtype':'Sawshark', /// 'age':105, /// 'birthday': '1900-01-05T01:00:00Z', /// 'length':10.0, /// 'picture': new Buffer([255, 255, 255, 255, /// 254]).toString('base64'), /// 'species':'dangerous', /// }, /// { /// 'fishtype': 'goblin', /// 'age': 1, /// 'birthday': '2015-08-08T00:00:00Z', /// 'length': 30.0, /// 'species': 'scary', /// 'jawsize': 5 /// } /// ] /// }; /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } if (complexBody != null) { complexBody.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValid", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/valid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Put complex types that are polymorphic, attempting to omit required /// 'birthday' field - the request should not be allowed from the client /// </summary> /// <param name='complexBody'> /// Please attempt put a sawshark that looks like this, the client should not /// allow this data to be sent: /// { /// "fishtype": "sawshark", /// "species": "snaggle toothed", /// "length": 18.5, /// "age": 2, /// "birthday": "2013-06-01T01:00:00Z", /// "location": "alaska", /// "picture": base64(FF FF FF FF FE), /// "siblings": [ /// { /// "fishtype": "shark", /// "species": "predator", /// "birthday": "2012-01-05T01:00:00Z", /// "length": 20, /// "age": 6 /// }, /// { /// "fishtype": "sawshark", /// "species": "dangerous", /// "picture": base64(FF FF FF FF FE), /// "length": 10, /// "age": 105 /// } /// ] /// } /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> PutValidMissingRequiredWithHttpMessagesAsync(Fish complexBody, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (complexBody == null) { throw new ValidationException(ValidationRules.CannotBeNull, "complexBody"); } if (complexBody != null) { complexBody.Validate(); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("complexBody", complexBody); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PutValidMissingRequired", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "complex/polymorphism/missingrequired/invalid").ToString(); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(complexBody != null) { _requestContent = SafeJsonConvert.SerializeObject(complexBody, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
/* * UltraCart Rest API V2 * * UltraCart REST API Version 2 * * OpenAPI spec version: 2.0.0 * Contact: support@ultracart.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = com.ultracart.admin.v2.Client.SwaggerDateConverter; namespace com.ultracart.admin.v2.Model { /// <summary> /// CustomerBilling /// </summary> [DataContract] public partial class CustomerBilling : IEquatable<CustomerBilling>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="CustomerBilling" /> class. /// </summary> /// <param name="address1">Address line 1.</param> /// <param name="address2">Address line 2.</param> /// <param name="city">City.</param> /// <param name="company">Company.</param> /// <param name="countryCode">ISO-3166 two letter country code.</param> /// <param name="customerBillingOid">Customer profile billing object identifier.</param> /// <param name="customerProfileOid">Customer profile object identifier.</param> /// <param name="dayPhone">Day phone.</param> /// <param name="defaultBilling">Default billing.</param> /// <param name="eveningPhone">Evening phone.</param> /// <param name="firstName">First name.</param> /// <param name="lastName">Last name.</param> /// <param name="lastUsedDts">Last used date.</param> /// <param name="postalCode">Postal code.</param> /// <param name="stateRegion">State for United States otherwise region or province for other countries.</param> /// <param name="taxCounty">Tax County.</param> /// <param name="title">Title.</param> public CustomerBilling(string address1 = default(string), string address2 = default(string), string city = default(string), string company = default(string), string countryCode = default(string), int? customerBillingOid = default(int?), int? customerProfileOid = default(int?), string dayPhone = default(string), bool? defaultBilling = default(bool?), string eveningPhone = default(string), string firstName = default(string), string lastName = default(string), string lastUsedDts = default(string), string postalCode = default(string), string stateRegion = default(string), string taxCounty = default(string), string title = default(string)) { this.Address1 = address1; this.Address2 = address2; this.City = city; this.Company = company; this.CountryCode = countryCode; this.CustomerBillingOid = customerBillingOid; this.CustomerProfileOid = customerProfileOid; this.DayPhone = dayPhone; this.DefaultBilling = defaultBilling; this.EveningPhone = eveningPhone; this.FirstName = firstName; this.LastName = lastName; this.LastUsedDts = lastUsedDts; this.PostalCode = postalCode; this.StateRegion = stateRegion; this.TaxCounty = taxCounty; this.Title = title; } /// <summary> /// Address line 1 /// </summary> /// <value>Address line 1</value> [DataMember(Name="address1", EmitDefaultValue=false)] public string Address1 { get; set; } /// <summary> /// Address line 2 /// </summary> /// <value>Address line 2</value> [DataMember(Name="address2", EmitDefaultValue=false)] public string Address2 { get; set; } /// <summary> /// City /// </summary> /// <value>City</value> [DataMember(Name="city", EmitDefaultValue=false)] public string City { get; set; } /// <summary> /// Company /// </summary> /// <value>Company</value> [DataMember(Name="company", EmitDefaultValue=false)] public string Company { get; set; } /// <summary> /// ISO-3166 two letter country code /// </summary> /// <value>ISO-3166 two letter country code</value> [DataMember(Name="country_code", EmitDefaultValue=false)] public string CountryCode { get; set; } /// <summary> /// Customer profile billing object identifier /// </summary> /// <value>Customer profile billing object identifier</value> [DataMember(Name="customer_billing_oid", EmitDefaultValue=false)] public int? CustomerBillingOid { get; set; } /// <summary> /// Customer profile object identifier /// </summary> /// <value>Customer profile object identifier</value> [DataMember(Name="customer_profile_oid", EmitDefaultValue=false)] public int? CustomerProfileOid { get; set; } /// <summary> /// Day phone /// </summary> /// <value>Day phone</value> [DataMember(Name="day_phone", EmitDefaultValue=false)] public string DayPhone { get; set; } /// <summary> /// Default billing /// </summary> /// <value>Default billing</value> [DataMember(Name="default_billing", EmitDefaultValue=false)] public bool? DefaultBilling { get; set; } /// <summary> /// Evening phone /// </summary> /// <value>Evening phone</value> [DataMember(Name="evening_phone", EmitDefaultValue=false)] public string EveningPhone { get; set; } /// <summary> /// First name /// </summary> /// <value>First name</value> [DataMember(Name="first_name", EmitDefaultValue=false)] public string FirstName { get; set; } /// <summary> /// Last name /// </summary> /// <value>Last name</value> [DataMember(Name="last_name", EmitDefaultValue=false)] public string LastName { get; set; } /// <summary> /// Last used date /// </summary> /// <value>Last used date</value> [DataMember(Name="last_used_dts", EmitDefaultValue=false)] public string LastUsedDts { get; set; } /// <summary> /// Postal code /// </summary> /// <value>Postal code</value> [DataMember(Name="postal_code", EmitDefaultValue=false)] public string PostalCode { get; set; } /// <summary> /// State for United States otherwise region or province for other countries /// </summary> /// <value>State for United States otherwise region or province for other countries</value> [DataMember(Name="state_region", EmitDefaultValue=false)] public string StateRegion { get; set; } /// <summary> /// Tax County /// </summary> /// <value>Tax County</value> [DataMember(Name="tax_county", EmitDefaultValue=false)] public string TaxCounty { get; set; } /// <summary> /// Title /// </summary> /// <value>Title</value> [DataMember(Name="title", EmitDefaultValue=false)] public string Title { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CustomerBilling {\n"); sb.Append(" Address1: ").Append(Address1).Append("\n"); sb.Append(" Address2: ").Append(Address2).Append("\n"); sb.Append(" City: ").Append(City).Append("\n"); sb.Append(" Company: ").Append(Company).Append("\n"); sb.Append(" CountryCode: ").Append(CountryCode).Append("\n"); sb.Append(" CustomerBillingOid: ").Append(CustomerBillingOid).Append("\n"); sb.Append(" CustomerProfileOid: ").Append(CustomerProfileOid).Append("\n"); sb.Append(" DayPhone: ").Append(DayPhone).Append("\n"); sb.Append(" DefaultBilling: ").Append(DefaultBilling).Append("\n"); sb.Append(" EveningPhone: ").Append(EveningPhone).Append("\n"); sb.Append(" FirstName: ").Append(FirstName).Append("\n"); sb.Append(" LastName: ").Append(LastName).Append("\n"); sb.Append(" LastUsedDts: ").Append(LastUsedDts).Append("\n"); sb.Append(" PostalCode: ").Append(PostalCode).Append("\n"); sb.Append(" StateRegion: ").Append(StateRegion).Append("\n"); sb.Append(" TaxCounty: ").Append(TaxCounty).Append("\n"); sb.Append(" Title: ").Append(Title).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as CustomerBilling); } /// <summary> /// Returns true if CustomerBilling instances are equal /// </summary> /// <param name="input">Instance of CustomerBilling to be compared</param> /// <returns>Boolean</returns> public bool Equals(CustomerBilling input) { if (input == null) return false; return ( this.Address1 == input.Address1 || (this.Address1 != null && this.Address1.Equals(input.Address1)) ) && ( this.Address2 == input.Address2 || (this.Address2 != null && this.Address2.Equals(input.Address2)) ) && ( this.City == input.City || (this.City != null && this.City.Equals(input.City)) ) && ( this.Company == input.Company || (this.Company != null && this.Company.Equals(input.Company)) ) && ( this.CountryCode == input.CountryCode || (this.CountryCode != null && this.CountryCode.Equals(input.CountryCode)) ) && ( this.CustomerBillingOid == input.CustomerBillingOid || (this.CustomerBillingOid != null && this.CustomerBillingOid.Equals(input.CustomerBillingOid)) ) && ( this.CustomerProfileOid == input.CustomerProfileOid || (this.CustomerProfileOid != null && this.CustomerProfileOid.Equals(input.CustomerProfileOid)) ) && ( this.DayPhone == input.DayPhone || (this.DayPhone != null && this.DayPhone.Equals(input.DayPhone)) ) && ( this.DefaultBilling == input.DefaultBilling || (this.DefaultBilling != null && this.DefaultBilling.Equals(input.DefaultBilling)) ) && ( this.EveningPhone == input.EveningPhone || (this.EveningPhone != null && this.EveningPhone.Equals(input.EveningPhone)) ) && ( this.FirstName == input.FirstName || (this.FirstName != null && this.FirstName.Equals(input.FirstName)) ) && ( this.LastName == input.LastName || (this.LastName != null && this.LastName.Equals(input.LastName)) ) && ( this.LastUsedDts == input.LastUsedDts || (this.LastUsedDts != null && this.LastUsedDts.Equals(input.LastUsedDts)) ) && ( this.PostalCode == input.PostalCode || (this.PostalCode != null && this.PostalCode.Equals(input.PostalCode)) ) && ( this.StateRegion == input.StateRegion || (this.StateRegion != null && this.StateRegion.Equals(input.StateRegion)) ) && ( this.TaxCounty == input.TaxCounty || (this.TaxCounty != null && this.TaxCounty.Equals(input.TaxCounty)) ) && ( this.Title == input.Title || (this.Title != null && this.Title.Equals(input.Title)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Address1 != null) hashCode = hashCode * 59 + this.Address1.GetHashCode(); if (this.Address2 != null) hashCode = hashCode * 59 + this.Address2.GetHashCode(); if (this.City != null) hashCode = hashCode * 59 + this.City.GetHashCode(); if (this.Company != null) hashCode = hashCode * 59 + this.Company.GetHashCode(); if (this.CountryCode != null) hashCode = hashCode * 59 + this.CountryCode.GetHashCode(); if (this.CustomerBillingOid != null) hashCode = hashCode * 59 + this.CustomerBillingOid.GetHashCode(); if (this.CustomerProfileOid != null) hashCode = hashCode * 59 + this.CustomerProfileOid.GetHashCode(); if (this.DayPhone != null) hashCode = hashCode * 59 + this.DayPhone.GetHashCode(); if (this.DefaultBilling != null) hashCode = hashCode * 59 + this.DefaultBilling.GetHashCode(); if (this.EveningPhone != null) hashCode = hashCode * 59 + this.EveningPhone.GetHashCode(); if (this.FirstName != null) hashCode = hashCode * 59 + this.FirstName.GetHashCode(); if (this.LastName != null) hashCode = hashCode * 59 + this.LastName.GetHashCode(); if (this.LastUsedDts != null) hashCode = hashCode * 59 + this.LastUsedDts.GetHashCode(); if (this.PostalCode != null) hashCode = hashCode * 59 + this.PostalCode.GetHashCode(); if (this.StateRegion != null) hashCode = hashCode * 59 + this.StateRegion.GetHashCode(); if (this.TaxCounty != null) hashCode = hashCode * 59 + this.TaxCounty.GetHashCode(); if (this.Title != null) hashCode = hashCode * 59 + this.Title.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // Address1 (string) maxLength if(this.Address1 != null && this.Address1.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Address1, length must be less than 50.", new [] { "Address1" }); } // Address2 (string) maxLength if(this.Address2 != null && this.Address2.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Address2, length must be less than 50.", new [] { "Address2" }); } // City (string) maxLength if(this.City != null && this.City.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for City, length must be less than 32.", new [] { "City" }); } // Company (string) maxLength if(this.Company != null && this.Company.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Company, length must be less than 50.", new [] { "Company" }); } // CountryCode (string) maxLength if(this.CountryCode != null && this.CountryCode.Length > 2) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for CountryCode, length must be less than 2.", new [] { "CountryCode" }); } // DayPhone (string) maxLength if(this.DayPhone != null && this.DayPhone.Length > 25) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for DayPhone, length must be less than 25.", new [] { "DayPhone" }); } // EveningPhone (string) maxLength if(this.EveningPhone != null && this.EveningPhone.Length > 25) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for EveningPhone, length must be less than 25.", new [] { "EveningPhone" }); } // FirstName (string) maxLength if(this.FirstName != null && this.FirstName.Length > 30) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for FirstName, length must be less than 30.", new [] { "FirstName" }); } // LastName (string) maxLength if(this.LastName != null && this.LastName.Length > 30) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for LastName, length must be less than 30.", new [] { "LastName" }); } // PostalCode (string) maxLength if(this.PostalCode != null && this.PostalCode.Length > 20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PostalCode, length must be less than 20.", new [] { "PostalCode" }); } // StateRegion (string) maxLength if(this.StateRegion != null && this.StateRegion.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for StateRegion, length must be less than 32.", new [] { "StateRegion" }); } // TaxCounty (string) maxLength if(this.TaxCounty != null && this.TaxCounty.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for TaxCounty, length must be less than 32.", new [] { "TaxCounty" }); } // Title (string) maxLength if(this.Title != null && this.Title.Length > 50) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Title, length must be less than 50.", new [] { "Title" }); } yield break; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GenerateGraph { private List<Node> nodes; public Node endNode; public GenerateGraph() { //get nav mesh characteristics from pre-made nav mesh. Will write script later that generates //a nav-mesh for any map. NavMeshTriangulation navmesh = NavMesh.CalculateTriangulation(); //initialize triangles array Triangle[] meshTriangles = new Triangle[navmesh.indices.Length/3]; //will contain mapping from a string containing the Vector3 pair side and the lane type of a node(ex: (1,2,3) and (4,5,6) //in "middle" will be respresented as "1,2,3 - 4,5,6 middle" with the smaller Vector3 coming first) to the node on that //side with that lane type. Dictionary<string, Node> sideToNode = new Dictionary<string, Node>(); //will contain mapping from a Node to the list of Triangles that contain that Node on a side Dictionary<Node, List<Triangle>> nodeToTriangles = new Dictionary<Node, List<Triangle>>(); nodes = new List<Node>(); //will contain a mapping from Vector3 coordinates (ex: (1,2,3) will be represented as "1,2,3") to //a Node Dictionary<string, Node> coordinatesToNode = new Dictionary<string, Node>(); //Made sure nav mesh indices is a multiple of 3 for (int i = 0; i < navmesh.indices.Length / 3; i++) { Vector3[] currentVectors = new Vector3[3]; Vector3 v1 = navmesh.vertices[navmesh.indices[i*3]]; Vector3 v2 = navmesh.vertices[navmesh.indices[i*3 + 1]]; Vector3 v3 = navmesh.vertices[navmesh.indices[i*3 + 2]]; meshTriangles[i] = new Triangle(v1, v2, v3, NavMesh.GetAreaCost(navmesh.areas[i])); List<Vector3Pair> trianglePairs = new List<Vector3Pair>(); //Add the pair v1, v2 to trianglePairs trianglePairs.Add(new Vector3Pair(v1, v2)); //Add the pair v2, v3 trianglePairs trianglePairs.Add(new Vector3Pair(v2, v3)); //Add the pair v1, v3 trianglePairs.Add(new Vector3Pair(v1, v3)); //Calculate bisections. Needed to generate smoother paths foreach (Vector3Pair currentVector3Pair in trianglePairs) { Vector3 currentFirst = currentVector3Pair.first; Vector3 currentSecond = currentVector3Pair.second; Vector3 bisect1 = new Vector3((currentFirst.x + currentSecond.x)/2, (currentFirst.y + currentSecond.y)/2, (currentFirst.z + currentSecond.z)/2); Vector3 bisect2 = new Vector3((bisect1.x + currentFirst.x)/2, (bisect1.y + currentFirst.y)/2, (bisect1.z + currentFirst.z)/2); Vector3 bisect3 = new Vector3((bisect1.x + currentSecond.x)/2, (bisect1.y + currentSecond.y)/2, (bisect1.z + currentSecond.z)/2); Node bisect1Node = getNodeWithVectorCoordinates(ref coordinatesToNode, bisect1); Node bisect2Node = getNodeWithVectorCoordinates(ref coordinatesToNode, bisect2); Node bisect3Node = getNodeWithVectorCoordinates(ref coordinatesToNode, bisect3); AddToDictionary(ref nodeToTriangles, bisect1Node, meshTriangles[i]); AddToDictionary(ref nodeToTriangles, bisect2Node, meshTriangles[i]); AddToDictionary(ref nodeToTriangles, bisect3Node, meshTriangles[i]); sideToNode[GetPairString(currentFirst, currentSecond) + " middle"] = bisect1Node; sideToNode[GetPairString(currentFirst, currentSecond) + " outer1"] = bisect2Node; sideToNode[GetPairString(currentFirst, currentSecond) + " outer2"] = bisect3Node; } Vector3 currentCentroid = meshTriangles[i].Centroid (); Node centroidNode = getNodeWithVectorCoordinates(ref coordinatesToNode, currentCentroid); AddToDictionary(ref nodeToTriangles, centroidNode, meshTriangles[i]); sideToNode[GetPairString (currentCentroid, currentCentroid) + " middle"] = centroidNode; } //set neighbors of each node foreach (var item in nodeToTriangles) { Node currentNode = item.Key; //iterate through all triangles that contain the currentNode on a side foreach (Triangle t in item.Value) { List<Vector3Pair> trianglePairs = new List<Vector3Pair>(); trianglePairs.Add(new Vector3Pair(t.vertex1, t.vertex2)); trianglePairs.Add(new Vector3Pair(t.vertex2, t.vertex3)); trianglePairs.Add(new Vector3Pair(t.vertex1, t.vertex3)); foreach (Vector3Pair trianglePair in trianglePairs) { Vector3 currentFirst = trianglePair.first; Vector3 currentSecond = trianglePair.second; Vector3 currentCentroid = t.Centroid(); addNodeNeighbor(sideToNode, ref currentNode, currentFirst, currentSecond, "middle"); addNodeNeighbor(sideToNode, ref currentNode, currentFirst, currentSecond, "outer1"); addNodeNeighbor(sideToNode, ref currentNode, currentFirst, currentSecond, "outer2"); addNodeNeighbor(sideToNode, ref currentNode, currentCentroid, currentCentroid, "middle"); } } nodes.Add(currentNode); } //set end node of the cars endNode = getClosestNode (GameObject.Find("FinishLine").transform.position); } // <summary> // Returns the node that corresponds to the coordinates of the given Vector3. Checks // for the node corresponding to the key constructured from the coordinates in the // coordinatesToNode dictionary; if not in the dictionary, creates the node and adds // it to the dictionary. // </summary> // <param name="coordinatesToNode"> // dictionary containing mappings from the coordinates of a Vector3 to the corresponding // node // </param> // <param name="givenVector"> a Vector3</param> // <param name="laneType"> // the lane type of the node if creating it is necessary ("middle" or "outer") // </param> public Node getNodeWithVectorCoordinates(ref Dictionary<string, Node> coordinatesToNode, Vector3 givenVector) { string vectorKey = givenVector.x + "," + givenVector.y + "," + givenVector.z; Node nodeOfVector; if (coordinatesToNode.ContainsKey(vectorKey)) { nodeOfVector = coordinatesToNode[vectorKey]; } else { nodeOfVector = new Node(givenVector); coordinatesToNode.Add(vectorKey, nodeOfVector); } return nodeOfVector; } // <summary> // Given a Vector3 pos, returns the Node in the list of Nodes that is closest to it. // </summary> // <param name="pos"> a Vector3 </param> public Node getClosestNode(Vector3 pos) { float minimumDistance = Mathf.Infinity; Node closestNode = null; foreach (Node node in nodes) { float distance = Vector3.Distance(node.position, pos); if (distance < minimumDistance) { closestNode = node; minimumDistance = distance; } } return closestNode; } // <summary> // Adds a neighbor to a given Node. The value of the neighbor is constructed from the // sideToNode dictionary that is passed in; the dictionary requires a key specified // by two Vector3 points and a laneName // </summary> // <param name="sideToNode"> // Maps a key specified by two Vector3 points (to specify a side) and a // laneName ("middle", "outer1", or "outer2") to a Node // </param> // <param name="givenNode"> a Node to add a neighbor to </param> // <param name="first"> the first Vector3 point </param> // <param name="second"> the second Vector3 point </param> // <param name="laneName"> the lane name ("middle", "outer1", or "outer2") </param> public void addNodeNeighbor(Dictionary<string, Node> sideToNode, ref Node givenNode, Vector3 first, Vector3 second, string laneName) { if (sideToNode.ContainsKey(GetPairString (first, second) + " " + laneName)) { Node neighbor = sideToNode[GetPairString (first, second) + " " + laneName]; if (neighbor != givenNode) { givenNode.neighbors.Add (neighbor); } } } // <summary> // Given a dictionary that maps a Node to the list of Triangles that contain // that Node on a side, add the value to the list of Triangles that the key // currently maps to // </summary> // <param name="dict"> // the dictionary that maps a Node to the list of Triangles that contain // that Node on a side // </param> // <param name="key"> a Node </param> // <param name="value"> a Triangle to add to the list of Triangles that the key currently maps to </param> public void AddToDictionary(ref Dictionary<Node, List<Triangle>> dict, Node key, Triangle value) { if (dict.ContainsKey (key)) { List<Triangle> currentNodes = dict[key]; currentNodes.Add(value); dict[key] = currentNodes; } else { List<Triangle> newNodes = new List<Triangle>(); newNodes.Add(value); dict.Add(key, newNodes); } } // <summary> // Given two Vector3 objects, creates a string representation of that pair with the // smaller Vector3 object coming first (ex: (1,2,3) and (4,5,6) will be respresented // as "1,2,3 - 4,5,6" with the smaller Vector3 coming first) // </summary> // <param name="v1"> the first given Vector3 </param> // <param name="v2"> the second given Vector3 </param> public string GetPairString(Vector3 v1, Vector3 v2) { float[] v1Components = new float[3]; v1Components[0] = v1.x; v1Components[1] = v1.y; v1Components[2] = v1.z; float[] v2Components = new float[3]; v2Components[0] = v2.x; v2Components[1] = v2.y; v2Components[2] = v2.z; Vector3 first = v1; Vector3 second = v2; for (int i = 0; i < 3; i++) { if (v1Components[i] > v2Components[i]) { Vector3 temp = second; second = first; first = temp; break; } else if(v1Components[i] < v2Components[i]) { break; } } return first.x + "," + first.y + "," + first.z + " - " + second.x + "," + second.y + "," + second.z; } public int Size() { return nodes.Count; } // <summary> // Returns a string representation of all the triangles of the nodes // </summary> public override string ToString() { string return_string = ""; foreach (Node node in nodes) { return_string += "\n" + (node.position.ToString()); } return return_string; } public string ToStringWithNeighbors() { string return_string = ""; Dictionary<Node, int> pairToNodes = new Dictionary<Node, int>(); for (int i = 0; i < nodes.Count; i++) { pairToNodes.Add (nodes[i], i); } for (int i = 0; i < nodes.Count; i++) { return_string += "\n" + "Node: " + i + " has neighbors "; for (int j = 0; j < nodes[i].neighbors.Count; j++) { return_string += pairToNodes[nodes[i].neighbors[j]] + ", "; } } return return_string; } public class Vector3Pair { public Vector3 first; //represents the first Vector3 in the Vector3Pair public Vector3 second; //represents the second Vector3 in the Vector3Pair public Vector3Pair(Vector3 first, Vector3 second) { this.first = first; this.second = second; } } }
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.ComponentModel.Design; using System.ComponentModel.Design.Serialization; using System.Drawing; using System.Windows.Forms; namespace CloudBox.Controller.TreeList { [TypeConverterAttribute(typeof(OptionsSettingTypeConverter))] public class TextFormatting { ContentAlignment m_alignment = ContentAlignment.MiddleLeft; Color m_foreColor = SystemColors.ControlText; Color m_backColor = Color.Transparent; Padding m_padding = new Padding(0,0,0,0); public TextFormatFlags GetFormattingFlags() { TextFormatFlags flags = 0; switch (TextAlignment) { case ContentAlignment.TopLeft: flags = TextFormatFlags.Top | TextFormatFlags.Left; break; case ContentAlignment.TopCenter: flags = TextFormatFlags.Top | TextFormatFlags.HorizontalCenter; break; case ContentAlignment.TopRight: flags = TextFormatFlags.Top | TextFormatFlags.Right; break; case ContentAlignment.MiddleLeft: flags = TextFormatFlags.VerticalCenter | TextFormatFlags.Left; break; case ContentAlignment.MiddleCenter: flags = TextFormatFlags.VerticalCenter | TextFormatFlags.HorizontalCenter; break; case ContentAlignment.MiddleRight: flags = TextFormatFlags.VerticalCenter | TextFormatFlags.Right; break; case ContentAlignment.BottomLeft: flags = TextFormatFlags.Bottom | TextFormatFlags.Left; break; case ContentAlignment.BottomCenter: flags = TextFormatFlags.Bottom | TextFormatFlags.HorizontalCenter; break; case ContentAlignment.BottomRight: flags = TextFormatFlags.Bottom | TextFormatFlags.Right; break; } return flags; } [DefaultValue(typeof(Padding), "0,0,0,0")] public Padding Padding { get { return m_padding; } set { m_padding = value; } } [DefaultValue(typeof(ContentAlignment), "MiddleLeft")] public ContentAlignment TextAlignment { get { return m_alignment; } set { m_alignment = value; } } [DefaultValue(typeof(Color), "ControlText")] public Color ForeColor { get { return m_foreColor; } set { m_foreColor = value; } } [DefaultValue(typeof(Color), "Transparent")] public Color BackColor { get { return m_backColor; } set { m_backColor = value; } } public TextFormatting() { } public TextFormatting(TextFormatting aCopy) { m_alignment = aCopy.m_alignment; m_foreColor = aCopy.m_foreColor; m_backColor = aCopy.m_backColor; m_padding = aCopy.m_padding; } } [TypeConverterAttribute(typeof(OptionsSettingTypeConverter))] public class ViewSetting { TreeListView m_owner; BorderStyle m_borderStyle = BorderStyle.None; int m_indent = 16; bool m_showLine = true; bool m_showPlusMinus = true; bool m_showGridLines = true; [Category("Behavior")] [DefaultValue(typeof(int), "16")] public int Indent { get { return m_indent; } set { m_indent = value; m_owner.Invalidate(); } } [Category("Behavior")] [DefaultValue(typeof(bool), "True")] public bool ShowLine { get { return m_showLine; } set { m_showLine = value; m_owner.Invalidate(); } } [Category("Behavior")] [DefaultValue(typeof(bool), "True")] public bool ShowPlusMinus { get { return m_showPlusMinus; } set { m_showPlusMinus = value; m_owner.Invalidate(); } } [Category("Behavior")] [DefaultValue(typeof(bool), "True")] public bool ShowGridLines { get { return m_showGridLines; } set { m_showGridLines = value; m_owner.Invalidate(); } } [Category("Appearance")] [DefaultValue(typeof(BorderStyle), "None")] public BorderStyle BorderStyle { get { return m_borderStyle; } set { if (m_borderStyle != value) { m_borderStyle = value; m_owner.internalUpdateStyles(); m_owner.Invalidate(); } } } public ViewSetting(TreeListView owner) { m_owner = owner; } } [TypeConverterAttribute(typeof(OptionsSettingTypeConverter))] public class CollumnSetting { int m_leftMargin = 5; int m_headerHeight = 20; TreeListView m_owner; [DefaultValue(5)] public int LeftMargin { get { return m_leftMargin; } set { m_leftMargin = value; m_owner.Columns.RecalcVisibleColumsRect(); m_owner.Invalidate(); } } [DefaultValue(20)] public int HeaderHeight { get { return m_headerHeight; } set { m_headerHeight = value; m_owner.Columns.RecalcVisibleColumsRect(); m_owner.Invalidate(); } } public CollumnSetting(TreeListView owner) { m_owner = owner; } } [TypeConverterAttribute(typeof(OptionsSettingTypeConverter))] public class RowSetting { TreeListView m_owner; bool m_showHeader = true; int m_headerWidth = 15; int m_itemHeight = 16; [DefaultValue(true)] public bool ShowHeader { get { return m_showHeader; } set { if (m_showHeader == value) return; m_showHeader = value; m_owner.Columns.RecalcVisibleColumsRect(); m_owner.Invalidate(); } } [DefaultValue(15)] public int HeaderWidth { get { return m_headerWidth; } set { if (m_headerWidth == value) return; m_headerWidth = value; m_owner.Columns.RecalcVisibleColumsRect(); m_owner.Invalidate(); } } [Category("Behavior")] [DefaultValue(typeof(int), "16")] public int ItemHeight { get { return m_itemHeight; } set { m_itemHeight = value; m_owner.Invalidate(); } } public RowSetting(TreeListView owner) { m_owner = owner; } } class OptionsSettingTypeConverter : ExpandableObjectConverter { public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (destinationType == typeof(ViewSetting)) return true; if (destinationType == typeof(RowSetting)) return true; if (destinationType == typeof(CollumnSetting)) return true; if (destinationType == typeof(TextFormatting)) return true; return base.CanConvertTo(context, destinationType); } public override object ConvertTo(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, Type destinationType) { if (destinationType == typeof(string) && value.GetType() == typeof(ViewSetting)) return "(View Options)"; if (destinationType == typeof(string) && value.GetType() == typeof(RowSetting)) return "(Row Header Options)"; if (destinationType == typeof(string) && value.GetType() == typeof(CollumnSetting)) return "(Columns Options)"; if (destinationType == typeof(string) && value.GetType() == typeof(TextFormatting)) return "(Formatting)"; return base.ConvertTo(context, culture, value, destinationType); } } }
using System; using System.Collections; using System.Collections.Generic; using Epi; namespace Epi.Collections { /// <summary> /// Class NamedObjectCollection /// </summary> /// <typeparam name="T">Type</typeparam> public class NamedObjectCollection<T> : ICollection, IDisposable { #region Private Class Members private object syncRoot = null; private Dictionary<string, T> master = null; private Dictionary<string, object> tags = null; #endregion Private Class Members #region Constructors /// <summary> /// Default constructor /// </summary> public NamedObjectCollection() { ////Only objects that implement INamedObject interface can be used in this collection. //string interfaceName = typeof(Epi.INamedObject).FullName; //if (typeof(T).GetInterface(interfaceName, true) == null) //{ // throw new System.Exception("Only objects that implement Epi.INamedObject interface can be used in NamedObjectCollection"); //} master = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); tags = new Dictionary<string, object>(); syncRoot = new object(); } #endregion Constructors #region Public Properties /// <summary> /// Gets the number of key/value pairs contained in /// <see cref="System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;"/>. /// </summary> public int Count { get { return master.Count; } } /// <summary> /// Gets/sets Synchronization Root. /// </summary> public object SyncRoot { get { return this.syncRoot; } } /// <summary> /// Gets the is Synchronized flag. /// </summary> public bool IsSynchronized { get { return false; } } /// <summary> /// Gets a collection containing the keys in the /// <see cref="System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;"/>. /// </summary> public Dictionary<string, T>.KeyCollection Keys { get { return master.Keys; } } /// <summary> /// Returns a list of names of the objects contained in the collection /// </summary> public List<string> Names { get { List<string> namesList = new List<string>(); foreach (INamedObject obj in this) { namesList.Add(obj.Name); } return namesList; } } #endregion Public Properties #region Public Methods /// <summary> /// Addes the specified key and value to the dictionary. /// </summary> /// <param name="obj">The value of the element to add.</param> public virtual void Add(T obj) { string name = ((INamedObject)obj).Name.ToLowerInvariant(); master.Add(name, obj); } /// <summary> /// Addes the specified key and value to the dictionary. /// </summary> /// <param name="obj"></param> /// <param name="tag">The value of the element to add.</param> public void Add(T obj, object tag) { string name = ((INamedObject)obj).Name.ToLowerInvariant(); Add(obj); tags.Add(name, tag); } /// <summary> /// Removes the value with the specified key from the System.Collections.Generic.SortedDictionary&lt;T1,T2&gt;. /// </summary> /// <param name="obj">Named object to remove.</param> /// <returns>true if the value is successfully removed; otherwise, false. /// This method also returns false if key is not found in the System.Collections.Generic.SortedDictionary&lt;T1,T2&gt;.</returns> public virtual bool Remove(T obj) { INamedObject namedObject = obj as INamedObject; return master.Remove(namedObject.Name.ToLowerInvariant()); } /// <summary> /// Remove a string /// </summary> /// <param name="name">Name to remove</param> public virtual void Remove(string name) { T obj = this[name.ToLowerInvariant()]; Remove(obj); } /// <summary> /// Check to see if an object is contained /// </summary> /// <param name="obj">Object</param> /// <returns>Boolean</returns> public virtual bool Contains(T obj) { INamedObject namedObject = obj as INamedObject; return Contains(namedObject.Name.ToLowerInvariant()); } /// <summary> /// Check to see if an string name is contained /// </summary> /// <param name="name">Name</param> /// <returns>Boolean</returns> public virtual bool Contains(string name) { return master.ContainsKey(name.ToLowerInvariant()); } /// <summary> /// Copies and array to a given index /// </summary> /// <param name="array">Array</param> /// <param name="index">Index</param> public virtual void CopyTo(T[] array, int index) { master.Values.CopyTo(array, index); } /// <summary> /// Copies and array to a given index /// </summary> /// <param name="array">Array</param> /// <param name="index">Index</param> void ICollection.CopyTo(Array array, int index) { CopyTo((T[])array, index); } /// <summary> /// Add an array of Named objects to collection /// </summary> /// <param name="collection">A generic NamedObjectCollection</param> public void Add(NamedObjectCollection<T> collection) { foreach (T obj in collection) { Add(obj); } } /// <summary> /// Get Enum /// </summary> /// <returns>IEnumerator</returns> public virtual IEnumerator GetEnumerator() { return this.master.Values.GetEnumerator(); } /// <summary> /// Type Name /// </summary> /// <param name="name">Name</param> /// <returns>NamedObjectCollection</returns> public T this[string name] { get { return master[name]; } } /// <summary> /// Dispose master /// </summary> public virtual void Dispose() { if (master != null) { master.Clear(); master = null; } } /// <summary> /// Check if name exists /// </summary> /// <param name="name">Name</param> /// <returns>Boolean</returns> public bool Exists(string name) { return master.ContainsKey(name.ToLowerInvariant()); } /// <summary> /// Check if object exists /// </summary> /// <param name="obj">Object</param> /// <returns>Boolean</returns> public bool Exists(T obj) { return master.ContainsValue(obj); } /// <summary> /// Clear master /// </summary> public void Clear() { master.Clear(); } /// <summary> /// Returns the tag associated with the object. /// </summary> /// <param name="name">Name</param> /// <returns>object</returns> public object GetTag(string name) { return tags[name]; } #endregion Public Methods } }
// 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. namespace Microsoft.Xml.Schema { using System; using System.Text; using System.Collections; using System.Globalization; using System.Diagnostics; internal sealed class ConstraintStruct { // for each constraint internal CompiledIdentityConstraint constraint; // pointer to constraint internal SelectorActiveAxis axisSelector; internal ArrayList axisFields; // Add tableDim * LocatedActiveAxis in a loop internal Hashtable qualifiedTable; // Checking confliction internal Hashtable keyrefTable; // several keyref tables having connections to this one is possible private int _tableDim; // dimension of table = numbers of fields; internal int TableDim { get { return _tableDim; } } internal ConstraintStruct(CompiledIdentityConstraint constraint) { this.constraint = constraint; _tableDim = constraint.Fields.Length; this.axisFields = new ArrayList(); // empty fields this.axisSelector = new SelectorActiveAxis(constraint.Selector, this); if (this.constraint.Role != CompiledIdentityConstraint.ConstraintRole.Keyref) { this.qualifiedTable = new Hashtable(); } } } // ActiveAxis plus the location plus the state of matching in the constraint table : only for field internal class LocatedActiveAxis : ActiveAxis { private int _column; // the column in the table (the field sequence) internal bool isMatched; // if it's matched, then fill value in the validator later internal KeySequence Ks; // associated with a keysequence it will fills in internal int Column { get { return _column; } } internal LocatedActiveAxis(Asttree astfield, KeySequence ks, int column) : base(astfield) { this.Ks = ks; _column = column; this.isMatched = false; } internal void Reactivate(KeySequence ks) { Reactivate(); this.Ks = ks; } } // exist for optimization purpose // ActiveAxis plus // 1. overload endelement function from parent to return result // 2. combine locatedactiveaxis and keysequence more closely // 3. enable locatedactiveaxis reusing (the most important optimization point) // 4. enable ks adding to hashtable right after moving out selector node (to enable 3) // 5. will modify locatedactiveaxis class accordingly // 6. taking care of updating ConstraintStruct.axisFields // 7. remove constraintTable from ConstraintStruct // 8. still need centralized locatedactiveaxis for movetoattribute purpose internal class SelectorActiveAxis : ActiveAxis { private ConstraintStruct _cs; // pointer of constraintstruct, to enable 6 private ArrayList _KSs; // stack of KSStruct, will not become less private int _KSpointer = 0; // indicate current stack top (next available element); public bool EmptyStack { get { return _KSpointer == 0; } } public int lastDepth { get { return (_KSpointer == 0) ? -1 : ((KSStruct)_KSs[_KSpointer - 1]).depth; } } public SelectorActiveAxis(Asttree axisTree, ConstraintStruct cs) : base(axisTree) { _KSs = new ArrayList(); _cs = cs; } public override bool EndElement(string localname, string URN) { base.EndElement(localname, URN); if (_KSpointer > 0 && this.CurrentDepth == lastDepth) { return true; // next step PopPS, and insert into hash } return false; } // update constraintStruct.axisFields as well, if it's new LocatedActiveAxis public int PushKS(int errline, int errcol) { // new KeySequence each time KeySequence ks = new KeySequence(_cs.TableDim, errline, errcol); // needs to clear KSStruct before using KSStruct kss; if (_KSpointer < _KSs.Count) { // reuse, clear up KSs.KSpointer kss = (KSStruct)_KSs[_KSpointer]; kss.ks = ks; // reactivate LocatedActiveAxis for (int i = 0; i < _cs.TableDim; i++) { kss.fields[i].Reactivate(ks); // reassociate key sequence } } else { // "==", new kss = new KSStruct(ks, _cs.TableDim); for (int i = 0; i < _cs.TableDim; i++) { kss.fields[i] = new LocatedActiveAxis(_cs.constraint.Fields[i], ks, i); _cs.axisFields.Add(kss.fields[i]); // new, add to axisFields } _KSs.Add(kss); } kss.depth = this.CurrentDepth - 1; return (_KSpointer++); } public KeySequence PopKS() { return ((KSStruct)_KSs[--_KSpointer]).ks; } } internal class KSStruct { public int depth; // depth of selector when it matches public KeySequence ks; // ks of selector when it matches and assigned -- needs to new each time public LocatedActiveAxis[] fields; // array of fields activeaxis when it matches and assigned public KSStruct(KeySequence ks, int dim) { this.ks = ks; this.fields = new LocatedActiveAxis[dim]; } } internal class TypedObject { private class DecimalStruct { private bool _isDecimal = false; // rare case it will be used... private decimal[] _dvalue; // to accelerate equals operation. array <-> list public bool IsDecimal { get { return _isDecimal; } set { _isDecimal = value; } } public decimal[] Dvalue { get { return _dvalue; } } public DecimalStruct() { _dvalue = new decimal[1]; } //list public DecimalStruct(int dim) { _dvalue = new decimal[dim]; } } private DecimalStruct _dstruct = null; private object _ovalue; private string _svalue; // only for output private XmlSchemaDatatype _xsdtype; private int _dim = 1; private bool _isList = false; public int Dim { get { return _dim; } } public bool IsList { get { return _isList; } } public bool IsDecimal { get { Debug.Assert(_dstruct != null); return _dstruct.IsDecimal; } } public decimal[] Dvalue { get { Debug.Assert(_dstruct != null); return _dstruct.Dvalue; } } public object Value { get { return _ovalue; } set { _ovalue = value; } } public XmlSchemaDatatype Type { get { return _xsdtype; } set { _xsdtype = value; } } public TypedObject(object obj, string svalue, XmlSchemaDatatype xsdtype) { _ovalue = obj; _svalue = svalue; _xsdtype = xsdtype; if (xsdtype.Variety == XmlSchemaDatatypeVariety.List || xsdtype is Datatype_base64Binary || xsdtype is Datatype_hexBinary) { _isList = true; _dim = ((Array)obj).Length; } } public override string ToString() { // only for exception return _svalue; } public void SetDecimal() { if (_dstruct != null) { return; } // Debug.Assert(!this.IsDecimal); switch (_xsdtype.TypeCode) { case XmlTypeCode.Byte: case XmlTypeCode.UnsignedByte: case XmlTypeCode.Short: case XmlTypeCode.UnsignedShort: case XmlTypeCode.Int: case XmlTypeCode.UnsignedInt: case XmlTypeCode.Long: case XmlTypeCode.UnsignedLong: case XmlTypeCode.Decimal: case XmlTypeCode.Integer: case XmlTypeCode.PositiveInteger: case XmlTypeCode.NonNegativeInteger: case XmlTypeCode.NegativeInteger: case XmlTypeCode.NonPositiveInteger: if (_isList) { _dstruct = new DecimalStruct(_dim); for (int i = 0; i < _dim; i++) { _dstruct.Dvalue[i] = Convert.ToDecimal(((Array)_ovalue).GetValue(i), NumberFormatInfo.InvariantInfo); } } else { //not list _dstruct = new DecimalStruct(); //possibility of list of length 1. _dstruct.Dvalue[0] = Convert.ToDecimal(_ovalue, NumberFormatInfo.InvariantInfo); } _dstruct.IsDecimal = true; break; default: if (_isList) { _dstruct = new DecimalStruct(_dim); } else { _dstruct = new DecimalStruct(); } break; } } private bool ListDValueEquals(TypedObject other) { for (int i = 0; i < this.Dim; i++) { if (this.Dvalue[i] != other.Dvalue[i]) { return false; } } return true; } public bool Equals(TypedObject other) { // ? one is list with one member, another is not list -- still might be equal if (this.Dim != other.Dim) { return false; } if (this.Type != other.Type) { //Check if types are comparable if (!(this.Type.IsComparable(other.Type))) { return false; } other.SetDecimal(); // can't use cast and other.Type.IsEqual (value1, value2) this.SetDecimal(); if (this.IsDecimal && other.IsDecimal) { //Both are decimal / derived types return this.ListDValueEquals(other); } } // not-Decimal derivation or type equal if (this.IsList) { if (other.IsList) { //Both are lists and values are XmlAtomicValue[] or clrvalue[]. So use Datatype_List.Compare return this.Type.Compare(this.Value, other.Value) == 0; } else { //this is a list and other is a single value Array arr1 = this.Value as System.Array; XmlAtomicValue[] atomicValues1 = arr1 as XmlAtomicValue[]; if (atomicValues1 != null) { // this is a list of union return atomicValues1.Length == 1 && atomicValues1.GetValue(0).Equals(other.Value); } else { return arr1.Length == 1 && arr1.GetValue(0).Equals(other.Value); } } } else if (other.IsList) { Array arr2 = other.Value as System.Array; XmlAtomicValue[] atomicValues2 = arr2 as XmlAtomicValue[]; if (atomicValues2 != null) { // other is a list of union return atomicValues2.Length == 1 && atomicValues2.GetValue(0).Equals(this.Value); } else { return arr2.Length == 1 && arr2.GetValue(0).Equals(this.Value); } } else { //Both are not lists return this.Value.Equals(other.Value); } } } internal class KeySequence { private TypedObject[] _ks; private int _dim; private int _hashcode = -1; private int _posline,_poscol; // for error reporting internal KeySequence(int dim, int line, int col) { Debug.Assert(dim > 0); _dim = dim; _ks = new TypedObject[dim]; _posline = line; _poscol = col; } public int PosLine { get { return _posline; } } public int PosCol { get { return _poscol; } } public KeySequence(TypedObject[] ks) { _ks = ks; _dim = ks.Length; _posline = _poscol = 0; } public object this[int index] { get { object result = _ks[index]; return result; } set { _ks[index] = (TypedObject)value; } } // return true if no null field internal bool IsQualified() { for (int i = 0; i < _ks.Length; ++i) { if ((_ks[i] == null) || (_ks[i].Value == null)) return false; } return true; } // it's not directly suit for hashtable, because it's always calculating address public override int GetHashCode() { if (_hashcode != -1) { return _hashcode; } _hashcode = 0; // indicate it's changed. even the calculated hashcode below is 0 for (int i = 0; i < _ks.Length; i++) { if (_ks[i] != null) { // extract its primitive value to calculate hashcode // decimal is handled differently to enable among different CLR types _ks[i].SetDecimal(); if (_ks[i].IsDecimal) { for (int j = 0; j < _ks[i].Dim; j++) { _hashcode += _ks[i].Dvalue[j].GetHashCode(); } } // BUGBUG: will need to change below parts, using canonical presentation. else { Array arr = _ks[i].Value as System.Array; if (arr != null) { XmlAtomicValue[] atomicValues = arr as XmlAtomicValue[]; if (atomicValues != null) { for (int j = 0; j < atomicValues.Length; j++) { _hashcode += ((XmlAtomicValue)atomicValues.GetValue(j)).TypedValue.GetHashCode(); } } else { for (int j = 0; j < ((Array)_ks[i].Value).Length; j++) { _hashcode += ((Array)_ks[i].Value).GetValue(j).GetHashCode(); } } } else { //not a list _hashcode += _ks[i].Value.GetHashCode(); } } } } return _hashcode; } // considering about derived type public override bool Equals(object other) { /*if (LocalAppContextSwitches.IgnoreEmptyKeySequences) { // each key sequence member can have different type KeySequence keySequence = (KeySequence)other; for (int i = 0; i < this.ks.Length; i++) { if (!this.ks[i].Equals(keySequence.ks[i])) { return false; } } return true; } else*/ { // each key sequence member can have different type KeySequence keySequence = (KeySequence)other; for (int i = 0; i < _ks.Length; i++) { if (!(_ks[i] == null && keySequence._ks[i] == null) && (_ks[i] == null || keySequence._ks[i] == null || !_ks[i].Equals(keySequence._ks[i]))) { return false; } } return true; } } public override string ToString() { /*if (LocalAppContextSwitches.IgnoreEmptyKeySequences) { StringBuilder sb = new StringBuilder(); sb.Append(this.ks[0].ToString()); for (int i = 1; i < this.ks.Length; i++) { sb.Append(" "); sb.Append(this.ks[i].ToString()); } return sb.ToString(); } else*/ { StringBuilder sb = new StringBuilder(); sb.Append(_ks[0].ToString()); for (int i = 1; i < _ks.Length; i++) { sb.Append(" "); sb.Append(_ks[i] == null ? "{}" : _ks[i].ToString()); } return sb.ToString(); } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Tools; using Xunit; namespace System.Numerics.Tests { public class modpowTest { private static int s_samples = 10; private static Random s_random = new Random(100); [Fact] public static void ModPowValidSmallNumbers() { BigInteger result; bool b = BigInteger.TryParse("22", out result); byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - with small numbers - valid for (int i = 1; i <= 1; i++)//-2 { for (int j = 0; j <= 1; j++)//2 { for (int k = 1; k <= 1; k++) { if (k != 0) { VerifyModPowString(k.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow"); } } } } } [Fact] public static void ModPowNegative() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - with small numbers - invalid - zero modulus for (int i = -2; i <= 2; i++) { for (int j = 0; j <= 2; j++) { Assert.Throws<DivideByZeroException>(() => { VerifyModPowString(BigInteger.Zero.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow"); }); } } // ModPow Method - with small numbers - invalid - negative exponent for (int i = -2; i <= 2; i++) { for (int j = -2; j <= -1; j++) { for (int k = -2; k <= 2; k++) { if (k != 0) { Assert.Throws<ArgumentOutOfRangeException>(() => { VerifyModPowString(k.ToString() + " " + j.ToString() + " " + i.ToString() + " tModPow"); }); } } } } // ModPow Method - Negative Exponent for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomNegByteArray(s_random, 2); tempByteArray3 = GetRandomByteArray(s_random); Assert.Throws<ArgumentOutOfRangeException>(() => { VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); }); } // ModPow Method - Zero Modulus for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random, 1); Assert.Throws<DivideByZeroException>(() => { VerifyModPowString(BigInteger.Zero.ToString() + " " + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); }); } } [Fact] public static void ModPow3SmallInt() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - Three Small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 2); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow1Large2SmallInt() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - One large and two small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random, 2); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 1); tempByteArray3 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow2Large1SmallInt() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - Two large and one small BigIntegers for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomPosByteArray(s_random); tempByteArray3 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow0Power() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - zero power for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); tempByteArray1 = GetRandomByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + BigInteger.Zero.ToString() + " " + Print(tempByteArray1) + "tModPow"); } } [Fact] public static void ModPow0Base() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // ModPow Method - zero base for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); tempByteArray1 = GetRandomPosByteArray(s_random, 2); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); tempByteArray1 = GetRandomPosByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random, 2); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); tempByteArray1 = GetRandomPosByteArray(s_random); tempByteArray2 = GetRandomByteArray(s_random); VerifyModPowString(Print(tempByteArray2) + Print(tempByteArray1) + BigInteger.Zero.ToString() + " tModPow"); } } [Fact] public static void ModPowAxiom() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // Axiom (x^y)%z = modpow(x,y,z) for (int i = 0; i < s_samples; i++) { tempByteArray1 = GetRandomByteArray(s_random, 2); tempByteArray2 = GetRandomPosByteArray(s_random, 1); tempByteArray3 = GetRandomByteArray(s_random); VerifyIdentityString( Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "tModPow", Print(tempByteArray3) + Print(tempByteArray2) + Print(tempByteArray1) + "bPow" + " bRemainder" ); } } [Fact] public static void ModPowBoundary() { byte[] tempByteArray1 = new byte[0]; byte[] tempByteArray2 = new byte[0]; byte[] tempByteArray3 = new byte[0]; // Check interesting cases for boundary conditions // You'll either be shifting a 0 or 1 across the boundary // 32 bit boundary n2=0 VerifyModPowString(Math.Pow(2, 35) + " " + Math.Pow(2, 32) + " 2 tModPow"); // 32 bit boundary n1=0 n2=1 VerifyModPowString(Math.Pow(2, 35) + " " + Math.Pow(2, 33) + " 2 tModPow"); } private static void VerifyModPowString(string opstring) { StackCalc sc = new StackCalc(opstring); while (sc.DoNextOperation()) { Assert.Equal(sc.snCalc.Peek().ToString(), sc.myCalc.Peek().ToString()); } } private static void VerifyIdentityString(string opstring1, string opstring2) { StackCalc sc1 = new StackCalc(opstring1); while (sc1.DoNextOperation()) { //Run the full calculation sc1.DoNextOperation(); } StackCalc sc2 = new StackCalc(opstring2); while (sc2.DoNextOperation()) { //Run the full calculation sc2.DoNextOperation(); } Assert.Equal(sc1.snCalc.Peek().ToString(), sc2.snCalc.Peek().ToString()); } private static byte[] GetRandomByteArray(Random random) { return GetRandomByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomPosByteArray(Random random) { return GetRandomPosByteArray(random, random.Next(1, 100)); } private static byte[] GetRandomByteArray(Random random, int size) { return MyBigIntImp.GetNonZeroRandomByteArray(random, size); } private static byte[] GetRandomPosByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] &= 0x7F; return value; } private static byte[] GetRandomNegByteArray(Random random, int size) { byte[] value = new byte[size]; for (int i = 0; i < value.Length; ++i) { value[i] = (byte)random.Next(0, 256); } value[value.Length - 1] |= 0x80; return value; } private static String Print(byte[] bytes) { return MyBigIntImp.Print(bytes); } } }
/* The MIT License(MIT) Copyright(c) 2015 IgorSoft Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Security.Authentication; using System.Threading.Tasks; using MediaFireSDK; using MediaFireSDK.Core; using MediaFireSDK.Model; using MediaFireSDK.Model.Errors; using MediaFireSDK.Model.Responses; using IgorSoft.CloudFS.Authentication; namespace IgorSoft.CloudFS.Gateways.MediaFire.Auth { internal static class Authenticator { private class SynchronizationContext { private readonly IList<IMediaFireUserApi> contextHolders = new List<IMediaFireUserApi>(); public AuthenticationContext LatestContext { get; private set; } public bool ContextUpdated { get; private set; } public string SettingsPassPhrase { get; } public SynchronizationContext(IMediaFireUserApi contextHolder, string settingsPassPhrase) { contextHolders.Add(contextHolder); LatestContext = contextHolder.GetAuthenticationContext(); contextHolder.AuthenticationContextChanged += UpdateContexts; SettingsPassPhrase = settingsPassPhrase; } public void UpdateContexts(object source, EventArgs eventArgs) { LatestContext = ((IMediaFireUserApi)source).GetAuthenticationContext(); ContextUpdated = true; foreach (var contextHolder in contextHolders) if (source != contextHolder) contextHolder.SetAuthenticationContext(LatestContext); } public void AttachContextHolder(IMediaFireUserApi contextHolder) { contextHolder.SetAuthenticationContext(LatestContext); contextHolders.Add(contextHolder); contextHolder.AuthenticationContextChanged += UpdateContexts; } } private static DirectLogOn logOn; private static readonly IDictionary<string, SynchronizationContext> contextDirectory = new Dictionary<string, SynchronizationContext>(); [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static Authenticator() { AppDomain.CurrentDomain.DomainUnload += ShutdownHandler<EventArgs>; AppDomain.CurrentDomain.UnhandledException += ShutdownHandler<UnhandledExceptionEventArgs>; } private static void ShutdownHandler<T>(object sender, T eventArgs) where T : EventArgs { foreach (var item in contextDirectory) if (item.Value.ContextUpdated) SaveRefreshToken(item.Key, item.Value.LatestContext, item.Value.SettingsPassPhrase); } private static AuthenticationContext LoadRefreshToken(string account, string settingsPassPhrase) { var refreshTokens = Properties.Settings.Default.RefreshTokens; var setting = refreshTokens?.SingleOrDefault(s => s.Account == account); return setting != null ? new AuthenticationContext(setting.SessionToken.DecryptUsing(settingsPassPhrase), long.Parse(setting.SecretKey.DecryptUsing(settingsPassPhrase)), setting.Time.DecryptUsing(settingsPassPhrase)) : null; } internal static void SaveRefreshToken(string account, AuthenticationContext refreshToken, string settingsPassPhrase) { var refreshTokens = Properties.Settings.Default.RefreshTokens; if (refreshTokens != null) { var setting = refreshTokens.SingleOrDefault(s => s.Account == account); if (setting != null) refreshTokens.Remove(setting); } else { refreshTokens = new System.Collections.ObjectModel.Collection<RefreshTokenSetting>(); Properties.Settings.Default.RefreshTokens = refreshTokens; } refreshTokens.Insert(0, new RefreshTokenSetting() { Account = account, SessionToken = refreshToken.SessionToken.EncryptUsing(settingsPassPhrase), SecretKey = refreshToken.SecretKey.ToString().EncryptUsing(settingsPassPhrase), Time = refreshToken.Time.EncryptUsing(settingsPassPhrase) }); Properties.Settings.Default.Save(); } private static async Task<AuthenticationContext> RefreshSessionTokenAsync(IMediaFireAgent agent) { try { await agent.GetAsync<MediaFireGetUserInfoResponse>(MediaFireApiUserMethods.GetInfo); return agent.User.GetAuthenticationContext(); } catch (MediaFireApiException) { return null; } } private static string GetAuthCode(string account) { var authCode = string.Empty; if (logOn == null) logOn = new DirectLogOn(AsyncOperationManager.SynchronizationContext); EventHandler<AuthenticatedEventArgs> callback = (s, e) => authCode = string.Join(",", e.Parameters.Get("account"), e.Parameters.Get("password")); logOn.Authenticated += callback; logOn.Show("Mediafire", account); logOn.Authenticated -= callback; return authCode; } public static async Task<MediaFireAgent> LoginAsync(string account, string code, string settingsPassPhrase) { if (string.IsNullOrEmpty(account)) throw new ArgumentNullException(nameof(account)); var agent = new MediaFireAgent(new MediaFireApiConfiguration(Secrets.API_KEY, Secrets.APP_ID, useHttpV1: true, automaticallyRenewToken: false)); if (contextDirectory.TryGetValue(account, out SynchronizationContext synchronizationContext)) { synchronizationContext.AttachContextHolder(agent.User); } else { var refreshToken = LoadRefreshToken(account, settingsPassPhrase); if (refreshToken != null) { agent.User.SetAuthenticationContext(refreshToken); refreshToken = await RefreshSessionTokenAsync(agent); } if (refreshToken == null) { if (string.IsNullOrEmpty(code)) code = GetAuthCode(account); var parts = code?.Split(new[] { ',' }, 2) ?? Array.Empty<string>(); if (parts.Length != 2) throw new AuthenticationException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.ProvideAuthenticationData, account)); await agent.User.GetSessionToken(parts[0], parts[1], TokenVersion.V2); } synchronizationContext = new SynchronizationContext(agent.User, settingsPassPhrase); contextDirectory.Add(account, synchronizationContext); } return agent; } public static void PurgeRefreshToken(string account) { var refreshTokens = Properties.Settings.Default.RefreshTokens; if (refreshTokens == null) return; var settings = refreshTokens.Where(s => account == null || s.Account == account).ToArray(); foreach (var setting in settings) refreshTokens.Remove(setting); if (!refreshTokens.Any()) Properties.Settings.Default.RefreshTokens = null; Properties.Settings.Default.Save(); } } }
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. namespace NetworkProfiler { partial class MainWindow { /// <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.Windows.Forms.DataVisualization.Charting.ChartArea chartArea1 = new System.Windows.Forms.DataVisualization.Charting.ChartArea(); System.Windows.Forms.DataVisualization.Charting.Legend legend1 = new System.Windows.Forms.DataVisualization.Charting.Legend(); System.Windows.Forms.DataVisualization.Charting.Series series1 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series2 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series3 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series4 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series5 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series6 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series7 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series8 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series9 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series10 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series11 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series12 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series13 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series14 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series15 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series16 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series17 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series18 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series19 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series20 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series21 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series22 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series23 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series24 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series25 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series26 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series27 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series28 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series29 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series30 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series31 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series32 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series33 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series34 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series35 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series36 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series37 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series38 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series39 = new System.Windows.Forms.DataVisualization.Charting.Series(); System.Windows.Forms.DataVisualization.Charting.Series series40 = new System.Windows.Forms.DataVisualization.Charting.Series(); this.OpenButton = new System.Windows.Forms.Button(); this.NetworkChart = new System.Windows.Forms.DataVisualization.Charting.Chart(); this.ChartListBox = new System.Windows.Forms.CheckedListBox(); this.SummaryTextBox = new System.Windows.Forms.RichTextBox(); this.DetailTextBox = new System.Windows.Forms.RichTextBox(); this.ActorFilterTextBox = new System.Windows.Forms.TextBox(); this.PropertyFilterTextBox = new System.Windows.Forms.TextBox(); this.RPCFilterTextBox = new System.Windows.Forms.TextBox(); this.ApplyFiltersButton = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.StackedBunchSizeRadioButton = new System.Windows.Forms.RadioButton(); this.LineViewRadioButton = new System.Windows.Forms.RadioButton(); this.ActorPerformanceView = new System.Windows.Forms.TreeView(); this.panel1 = new System.Windows.Forms.Panel(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.ActorListView = new System.Windows.Forms.ListView(); this.columnHeader1 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader2 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader3 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader4 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader5 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.tabPage4 = new System.Windows.Forms.TabPage(); this.PropertyListView = new System.Windows.Forms.ListView(); this.SizeBits = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.Count = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.AvgSizeBytes = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.AvgSizeBits = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.Property = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.tabPage5 = new System.Windows.Forms.TabPage(); this.RPCListView = new System.Windows.Forms.ListView(); this.columnHeader6 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader7 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader8 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader9 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeader10 = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); ((System.ComponentModel.ISupportInitialize)(this.NetworkChart)).BeginInit(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.panel1.SuspendLayout(); this.tabPage3.SuspendLayout(); this.tabPage4.SuspendLayout(); this.tabPage5.SuspendLayout(); this.SuspendLayout(); // // OpenButton // this.OpenButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.OpenButton.Location = new System.Drawing.Point(12, 12); this.OpenButton.Name = "OpenButton"; this.OpenButton.Size = new System.Drawing.Size(1231, 31); this.OpenButton.TabIndex = 0; this.OpenButton.Text = "Open File"; this.OpenButton.UseVisualStyleBackColor = true; this.OpenButton.Click += new System.EventHandler(this.OpenButton_Click); // // NetworkChart // this.NetworkChart.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.NetworkChart.AntiAliasing = System.Windows.Forms.DataVisualization.Charting.AntiAliasingStyles.Graphics; this.NetworkChart.BackColor = System.Drawing.Color.Transparent; chartArea1.AxisX.MajorGrid.LineColor = System.Drawing.Color.DarkGray; chartArea1.AxisX.ScrollBar.IsPositionedInside = false; chartArea1.AxisY.MajorGrid.LineColor = System.Drawing.Color.DarkGray; chartArea1.AxisY.ScrollBar.IsPositionedInside = false; chartArea1.BackColor = System.Drawing.Color.Transparent; chartArea1.CursorX.IsUserEnabled = true; chartArea1.CursorX.IsUserSelectionEnabled = true; chartArea1.Name = "DefaultChartArea"; this.NetworkChart.ChartAreas.Add(chartArea1); legend1.BackColor = System.Drawing.Color.Transparent; legend1.DockedToChartArea = "DefaultChartArea"; legend1.Docking = System.Windows.Forms.DataVisualization.Charting.Docking.Top; legend1.LegendStyle = System.Windows.Forms.DataVisualization.Charting.LegendStyle.Column; legend1.Name = "DefaultLegend"; this.NetworkChart.Legends.Add(legend1); this.NetworkChart.Location = new System.Drawing.Point(15, 6); this.NetworkChart.Name = "NetworkChart"; this.NetworkChart.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.Bright; series1.ChartArea = "DefaultChartArea"; series1.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series1.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series1.Legend = "DefaultLegend"; series1.Name = "ActorCount"; series2.ChartArea = "DefaultChartArea"; series2.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series2.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series2.Legend = "DefaultLegend"; series2.Name = "ActorCountSec"; series3.ChartArea = "DefaultChartArea"; series3.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series3.Font = new System.Drawing.Font("Tahoma", 8.25F); series3.Legend = "DefaultLegend"; series3.Name = "PropertyCount"; series4.ChartArea = "DefaultChartArea"; series4.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series4.Font = new System.Drawing.Font("Tahoma", 8.25F); series4.Legend = "DefaultLegend"; series4.Name = "PropertyCountSec"; series5.ChartArea = "DefaultChartArea"; series5.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series5.Font = new System.Drawing.Font("Tahoma", 8.25F); series5.Legend = "DefaultLegend"; series5.Name = "PropertySize"; series6.ChartArea = "DefaultChartArea"; series6.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series6.Font = new System.Drawing.Font("Tahoma", 8.25F); series6.Legend = "DefaultLegend"; series6.Name = "PropertySizeSec"; series7.ChartArea = "DefaultChartArea"; series7.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series7.Font = new System.Drawing.Font("Tahoma", 8.25F); series7.Legend = "DefaultLegend"; series7.Name = "RPCCount"; series8.ChartArea = "DefaultChartArea"; series8.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series8.Font = new System.Drawing.Font("Tahoma", 8.25F); series8.Legend = "DefaultLegend"; series8.Name = "RPCCountSec"; series9.ChartArea = "DefaultChartArea"; series9.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series9.Font = new System.Drawing.Font("Tahoma", 8.25F); series9.Legend = "DefaultLegend"; series9.Name = "RPCSize"; series10.ChartArea = "DefaultChartArea"; series10.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series10.Font = new System.Drawing.Font("Tahoma", 8.25F); series10.Legend = "DefaultLegend"; series10.Name = "RPCSizeSec"; series11.ChartArea = "DefaultChartArea"; series11.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series11.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series11.Legend = "DefaultLegend"; series11.Name = "ExportBunchCount"; series12.ChartArea = "DefaultChartArea"; series12.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series12.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series12.Legend = "DefaultLegend"; series12.Name = "ExportBunchSize"; series13.ChartArea = "DefaultChartArea"; series13.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series13.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series13.Legend = "DefaultLegend"; series13.Name = "MustBeMappedGuidsCount"; series14.ChartArea = "DefaultChartArea"; series14.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series14.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series14.Legend = "DefaultLegend"; series14.Name = "MustBeMappedGuidsSize"; series15.ChartArea = "DefaultChartArea"; series15.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series15.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series15.Legend = "DefaultLegend"; series15.Name = "SendAckCount"; series16.ChartArea = "DefaultChartArea"; series16.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series16.Font = new System.Drawing.Font("Tahoma", 8.25F); series16.Legend = "DefaultLegend"; series16.Name = "SendAckCountSec"; series17.ChartArea = "DefaultChartArea"; series17.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series17.Font = new System.Drawing.Font("Tahoma", 8.25F); series17.Legend = "DefaultLegend"; series17.Name = "SendAckSize"; series18.ChartArea = "DefaultChartArea"; series18.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series18.Font = new System.Drawing.Font("Tahoma", 8.25F); series18.Legend = "DefaultLegend"; series18.Name = "SendAckSizeSec"; series19.ChartArea = "DefaultChartArea"; series19.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series19.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series19.Legend = "DefaultLegend"; series19.Name = "ContentBlockHeaderSize"; series20.ChartArea = "DefaultChartArea"; series20.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series20.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series20.Legend = "DefaultLegend"; series20.Name = "ContentBlockFooterSize"; series21.ChartArea = "DefaultChartArea"; series21.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series21.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series21.Legend = "DefaultLegend"; series21.Name = "PropertyHandleSize"; series22.ChartArea = "DefaultChartArea"; series22.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series22.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series22.Legend = "DefaultLegend"; series22.Name = "SendBunchHeaderSize"; series23.ChartArea = "DefaultChartArea"; series23.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series23.Font = new System.Drawing.Font("Tahoma", 8.25F); series23.Legend = "DefaultLegend"; series23.Name = "SendBunchCount"; series24.ChartArea = "DefaultChartArea"; series24.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series24.Font = new System.Drawing.Font("Tahoma", 8.25F); series24.Legend = "DefaultLegend"; series24.Name = "SendBunchCountSec"; series25.ChartArea = "DefaultChartArea"; series25.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series25.Font = new System.Drawing.Font("Tahoma", 8.25F); series25.Legend = "DefaultLegend"; series25.Name = "SendBunchSize"; series25.YValuesPerPoint = 2; series26.ChartArea = "DefaultChartArea"; series26.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series26.Font = new System.Drawing.Font("Tahoma", 8.25F); series26.Legend = "DefaultLegend"; series26.Name = "SendBunchSizeSec"; series27.ChartArea = "DefaultChartArea"; series27.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series27.Font = new System.Drawing.Font("Tahoma", 8.25F); series27.Legend = "DefaultLegend"; series27.Name = "GameSocketSendCount"; series28.ChartArea = "DefaultChartArea"; series28.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series28.Font = new System.Drawing.Font("Tahoma", 8.25F); series28.Legend = "DefaultLegend"; series28.Name = "GameSocketSendCountSec"; series29.ChartArea = "DefaultChartArea"; series29.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series29.Font = new System.Drawing.Font("Tahoma", 8.25F); series29.Legend = "DefaultLegend"; series29.Name = "GameSocketSendSize"; series30.ChartArea = "DefaultChartArea"; series30.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series30.Font = new System.Drawing.Font("Tahoma", 8.25F); series30.Legend = "DefaultLegend"; series30.Name = "GameSocketSendSizeSec"; series31.ChartArea = "DefaultChartArea"; series31.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series31.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series31.Legend = "DefaultLegend"; series31.Name = "GameSocketSendSizeAvgSec"; series32.ChartArea = "DefaultChartArea"; series32.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series32.Font = new System.Drawing.Font("Tahoma", 8.25F); series32.Legend = "DefaultLegend"; series32.Name = "MiscSocketSendCount"; series33.ChartArea = "DefaultChartArea"; series33.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series33.Font = new System.Drawing.Font("Tahoma", 8.25F); series33.Legend = "DefaultLegend"; series33.Name = "MiscSocketSendCountSec"; series34.ChartArea = "DefaultChartArea"; series34.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series34.Font = new System.Drawing.Font("Tahoma", 8.25F); series34.Legend = "DefaultLegend"; series34.Name = "MiscSocketSendSize"; series35.ChartArea = "DefaultChartArea"; series35.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series35.Font = new System.Drawing.Font("Tahoma", 8.25F); series35.Legend = "DefaultLegend"; series35.Name = "MiscSocketSendSizeSec"; series36.ChartArea = "DefaultChartArea"; series36.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point; series36.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); series36.Legend = "DefaultLegend"; series36.Name = "Events"; series37.ChartArea = "DefaultChartArea"; series37.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series37.Font = new System.Drawing.Font("Tahoma", 8.25F); series37.Legend = "DefaultLegend"; series37.Name = "OutgoingBandwidthSize"; series38.ChartArea = "DefaultChartArea"; series38.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series38.Font = new System.Drawing.Font("Tahoma", 8.25F); series38.Legend = "DefaultLegend"; series38.Name = "OutgoingBandwidthSizeSec"; series39.ChartArea = "DefaultChartArea"; series39.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series39.Font = new System.Drawing.Font("Tahoma", 8.25F); series39.Legend = "DefaultLegend"; series39.Name = "OutgoingBandwidthSizeAvgSec"; series40.ChartArea = "DefaultChartArea"; series40.ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.FastLine; series40.Font = new System.Drawing.Font("Tahoma", 8.25F); series40.Legend = "DefaultLegend"; series40.Name = "ActorReplicateTimeInMS"; this.NetworkChart.Series.Add(series1); this.NetworkChart.Series.Add(series2); this.NetworkChart.Series.Add(series3); this.NetworkChart.Series.Add(series4); this.NetworkChart.Series.Add(series5); this.NetworkChart.Series.Add(series6); this.NetworkChart.Series.Add(series7); this.NetworkChart.Series.Add(series8); this.NetworkChart.Series.Add(series9); this.NetworkChart.Series.Add(series10); this.NetworkChart.Series.Add(series11); this.NetworkChart.Series.Add(series12); this.NetworkChart.Series.Add(series13); this.NetworkChart.Series.Add(series14); this.NetworkChart.Series.Add(series15); this.NetworkChart.Series.Add(series16); this.NetworkChart.Series.Add(series17); this.NetworkChart.Series.Add(series18); this.NetworkChart.Series.Add(series19); this.NetworkChart.Series.Add(series20); this.NetworkChart.Series.Add(series21); this.NetworkChart.Series.Add(series22); this.NetworkChart.Series.Add(series23); this.NetworkChart.Series.Add(series24); this.NetworkChart.Series.Add(series25); this.NetworkChart.Series.Add(series26); this.NetworkChart.Series.Add(series27); this.NetworkChart.Series.Add(series28); this.NetworkChart.Series.Add(series29); this.NetworkChart.Series.Add(series30); this.NetworkChart.Series.Add(series31); this.NetworkChart.Series.Add(series32); this.NetworkChart.Series.Add(series33); this.NetworkChart.Series.Add(series34); this.NetworkChart.Series.Add(series35); this.NetworkChart.Series.Add(series36); this.NetworkChart.Series.Add(series37); this.NetworkChart.Series.Add(series38); this.NetworkChart.Series.Add(series39); this.NetworkChart.Series.Add(series40); this.NetworkChart.Size = new System.Drawing.Size(998, 418); this.NetworkChart.TabIndex = 2; this.NetworkChart.Text = "chart1"; this.NetworkChart.CursorPositionChanged += new System.EventHandler<System.Windows.Forms.DataVisualization.Charting.CursorEventArgs>(this.NetworkChart_CursorPositionChanged); this.NetworkChart.SelectionRangeChanged += new System.EventHandler<System.Windows.Forms.DataVisualization.Charting.CursorEventArgs>(this.NetworkChart_SelectionRangeChanged); this.NetworkChart.MouseClick += new System.Windows.Forms.MouseEventHandler(this.NetworkChart_MouseClick); // // ChartListBox // this.ChartListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.ChartListBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.ChartListBox.CheckOnClick = true; this.ChartListBox.FormattingEnabled = true; this.ChartListBox.Items.AddRange(new object[] { "Actor count", "Actor count / sec", "Property count", "Property count / sec", "Property size (bytes)", "Property size (bytes / sec)", "RPC count", "RPC count / sec", "RPC size (bytes)", "RPC size (bytes / sec)", "ExportBunch count", "ExportBunch size (bytes)", "MustBeMappedGuids count", "MustBeMappedGuids size (bytes)", "SendAck count", "SendAck count / sec", "SendAck size (bytes)", "SendAck size (bytes / sec)", "Content block header size", "Content block footer size", "Property handle size", "SendBunch header size (bytes)", "SendBunch count", "SendBunch count / sec", "SendBunch size (bytes)", "SendBunch size (bytes / sec)", "Game socket send count", "Game socket send count / sec", "Game socket send size (bytes)", "Game socket send size (bytes / sec)", "Game socket send size (avg / sec)", "Misc socket send count", "Misc socket send count / sec", "Misc socket send size", "Misc socket send size (bytes / sec)", "Events", "Outgoing bandwidth (bytes)", "Outgoing bandwidth (bytes/ sec)", "Outgoing bandwidth (avg/ sec)", "Actor replication time (ms)"}); this.ChartListBox.Location = new System.Drawing.Point(1019, 36); this.ChartListBox.Name = "ChartListBox"; this.ChartListBox.Size = new System.Drawing.Size(198, 390); this.ChartListBox.TabIndex = 3; this.ChartListBox.SelectedValueChanged += new System.EventHandler(this.ChartListBox_SelectedValueChanged); // // SummaryTextBox // this.SummaryTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.SummaryTextBox.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.SummaryTextBox.Location = new System.Drawing.Point(15, 430); this.SummaryTextBox.Name = "SummaryTextBox"; this.SummaryTextBox.ReadOnly = true; this.SummaryTextBox.Size = new System.Drawing.Size(352, 539); this.SummaryTextBox.TabIndex = 4; this.SummaryTextBox.Text = ""; // // DetailTextBox // this.DetailTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.DetailTextBox.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.DetailTextBox.Location = new System.Drawing.Point(374, 430); this.DetailTextBox.Name = "DetailTextBox"; this.DetailTextBox.ReadOnly = true; this.DetailTextBox.Size = new System.Drawing.Size(372, 539); this.DetailTextBox.TabIndex = 5; this.DetailTextBox.Text = ""; // // ActorFilterTextBox // this.ActorFilterTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.ActorFilterTextBox.Font = new System.Drawing.Font("Tahoma", 8.25F); this.ActorFilterTextBox.Location = new System.Drawing.Point(103, 15); this.ActorFilterTextBox.Name = "ActorFilterTextBox"; this.ActorFilterTextBox.Size = new System.Drawing.Size(198, 21); this.ActorFilterTextBox.TabIndex = 7; // // PropertyFilterTextBox // this.PropertyFilterTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.PropertyFilterTextBox.Font = new System.Drawing.Font("Tahoma", 8.25F); this.PropertyFilterTextBox.Location = new System.Drawing.Point(103, 54); this.PropertyFilterTextBox.Name = "PropertyFilterTextBox"; this.PropertyFilterTextBox.Size = new System.Drawing.Size(198, 21); this.PropertyFilterTextBox.TabIndex = 8; // // RPCFilterTextBox // this.RPCFilterTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.RPCFilterTextBox.Font = new System.Drawing.Font("Tahoma", 8.25F); this.RPCFilterTextBox.Location = new System.Drawing.Point(103, 91); this.RPCFilterTextBox.Name = "RPCFilterTextBox"; this.RPCFilterTextBox.Size = new System.Drawing.Size(198, 21); this.RPCFilterTextBox.TabIndex = 9; // // ApplyFiltersButton // this.ApplyFiltersButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.ApplyFiltersButton.Location = new System.Drawing.Point(24, 127); this.ApplyFiltersButton.Name = "ApplyFiltersButton"; this.ApplyFiltersButton.Size = new System.Drawing.Size(277, 23); this.ApplyFiltersButton.TabIndex = 10; this.ApplyFiltersButton.Text = "Apply Filters"; this.ApplyFiltersButton.UseVisualStyleBackColor = true; this.ApplyFiltersButton.Click += new System.EventHandler(this.ApplyFiltersButton_Click); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Tahoma", 8.25F); this.label1.Location = new System.Drawing.Point(37, 18); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(60, 13); this.label1.TabIndex = 11; this.label1.Text = "Actor Filter"; // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Tahoma", 8.25F); this.label2.Location = new System.Drawing.Point(21, 57); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(76, 13); this.label2.TabIndex = 12; this.label2.Text = "Property Filter"; // // label3 // this.label3.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Tahoma", 8.25F); this.label3.Location = new System.Drawing.Point(43, 94); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(54, 13); this.label3.TabIndex = 13; this.label3.Text = "RPC Filter"; // // tabControl1 // this.tabControl1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Controls.Add(this.tabPage4); this.tabControl1.Controls.Add(this.tabPage5); this.tabControl1.Location = new System.Drawing.Point(12, 56); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(1231, 1001); this.tabControl1.TabIndex = 14; // // tabPage1 // this.tabPage1.Controls.Add(this.StackedBunchSizeRadioButton); this.tabPage1.Controls.Add(this.LineViewRadioButton); this.tabPage1.Controls.Add(this.ActorPerformanceView); this.tabPage1.Controls.Add(this.panel1); this.tabPage1.Controls.Add(this.NetworkChart); this.tabPage1.Controls.Add(this.ChartListBox); this.tabPage1.Controls.Add(this.SummaryTextBox); this.tabPage1.Controls.Add(this.DetailTextBox); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(1223, 975); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Chart, Filters, Details"; this.tabPage1.UseVisualStyleBackColor = true; // // StackedBunchSizeRadioButton // this.StackedBunchSizeRadioButton.AutoSize = true; this.StackedBunchSizeRadioButton.Location = new System.Drawing.Point(1096, 7); this.StackedBunchSizeRadioButton.Name = "StackedBunchSizeRadioButton"; this.StackedBunchSizeRadioButton.Size = new System.Drawing.Size(119, 17); this.StackedBunchSizeRadioButton.TabIndex = 18; this.StackedBunchSizeRadioButton.Text = "Stacked bunch size"; this.StackedBunchSizeRadioButton.UseVisualStyleBackColor = true; this.StackedBunchSizeRadioButton.CheckedChanged += new System.EventHandler(this.StackedBunchSizeRadioButton_CheckChanged); // // LineViewRadioButton // this.LineViewRadioButton.AutoSize = true; this.LineViewRadioButton.Checked = true; this.LineViewRadioButton.Location = new System.Drawing.Point(1020, 7); this.LineViewRadioButton.Name = "LineViewRadioButton"; this.LineViewRadioButton.Size = new System.Drawing.Size(70, 17); this.LineViewRadioButton.TabIndex = 17; this.LineViewRadioButton.TabStop = true; this.LineViewRadioButton.Text = "Line view"; this.LineViewRadioButton.UseVisualStyleBackColor = true; this.LineViewRadioButton.CheckedChanged += new System.EventHandler(this.LineViewRadioButton_CheckChanged); // // ActorPerformanceView // this.ActorPerformanceView.Font = new System.Drawing.Font("Courier New", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ActorPerformanceView.Location = new System.Drawing.Point(752, 593); this.ActorPerformanceView.Name = "ActorPerformanceView"; this.ActorPerformanceView.Size = new System.Drawing.Size(465, 375); this.ActorPerformanceView.TabIndex = 16; // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.ActorFilterTextBox); this.panel1.Controls.Add(this.label3); this.panel1.Controls.Add(this.PropertyFilterTextBox); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.RPCFilterTextBox); this.panel1.Controls.Add(this.ApplyFiltersButton); this.panel1.Location = new System.Drawing.Point(847, 430); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(370, 158); this.panel1.TabIndex = 15; // // tabPage3 // this.tabPage3.Controls.Add(this.ActorListView); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Size = new System.Drawing.Size(1223, 975); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Actors"; this.tabPage3.UseVisualStyleBackColor = true; // // ActorListView // this.ActorListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.ActorListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2, this.columnHeader3, this.columnHeader4, this.columnHeader5}); this.ActorListView.Font = new System.Drawing.Font("Tahoma", 8.25F); this.ActorListView.FullRowSelect = true; this.ActorListView.GridLines = true; this.ActorListView.Location = new System.Drawing.Point(1, 2); this.ActorListView.Name = "ActorListView"; this.ActorListView.Size = new System.Drawing.Size(1220, 1119); this.ActorListView.TabIndex = 1; this.ActorListView.UseCompatibleStateImageBehavior = false; this.ActorListView.View = System.Windows.Forms.View.Details; this.ActorListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.ActorListView_ColumnClick); // // columnHeader1 // this.columnHeader1.Text = "Total Size (KBytes)"; // // columnHeader2 // this.columnHeader2.Text = "Count"; // // columnHeader3 // this.columnHeader3.Text = "Average Size (Bytes)"; // // columnHeader4 // this.columnHeader4.Text = "Average Size Bits"; // // columnHeader5 // this.columnHeader5.Text = "Actor Class"; this.columnHeader5.Width = 145; // // tabPage4 // this.tabPage4.Controls.Add(this.PropertyListView); this.tabPage4.Location = new System.Drawing.Point(4, 22); this.tabPage4.Name = "tabPage4"; this.tabPage4.Size = new System.Drawing.Size(1223, 975); this.tabPage4.TabIndex = 3; this.tabPage4.Text = "Properties"; this.tabPage4.UseVisualStyleBackColor = true; // // PropertyListView // this.PropertyListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.PropertyListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.SizeBits, this.Count, this.AvgSizeBytes, this.AvgSizeBits, this.Property}); this.PropertyListView.Font = new System.Drawing.Font("Tahoma", 8.25F); this.PropertyListView.FullRowSelect = true; this.PropertyListView.GridLines = true; this.PropertyListView.Location = new System.Drawing.Point(3, 3); this.PropertyListView.Name = "PropertyListView"; this.PropertyListView.Size = new System.Drawing.Size(1220, 1119); this.PropertyListView.TabIndex = 0; this.PropertyListView.UseCompatibleStateImageBehavior = false; this.PropertyListView.View = System.Windows.Forms.View.Details; this.PropertyListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.PropertyListView_ColumnClick); // // SizeBits // this.SizeBits.Text = "Total Size (KBytes)"; // // Count // this.Count.Text = "Count"; // // AvgSizeBytes // this.AvgSizeBytes.Text = "Average Size (Bytes)"; // // AvgSizeBits // this.AvgSizeBits.Text = "Average Size Bits"; // // Property // this.Property.Text = "Property"; this.Property.Width = 145; // // tabPage5 // this.tabPage5.Controls.Add(this.RPCListView); this.tabPage5.Location = new System.Drawing.Point(4, 22); this.tabPage5.Name = "tabPage5"; this.tabPage5.Size = new System.Drawing.Size(1223, 975); this.tabPage5.TabIndex = 4; this.tabPage5.Text = "RPCs"; this.tabPage5.UseVisualStyleBackColor = true; // // RPCListView // this.RPCListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.RPCListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader6, this.columnHeader7, this.columnHeader8, this.columnHeader9, this.columnHeader10}); this.RPCListView.Font = new System.Drawing.Font("Tahoma", 8.25F); this.RPCListView.FullRowSelect = true; this.RPCListView.GridLines = true; this.RPCListView.Location = new System.Drawing.Point(1, 2); this.RPCListView.Name = "RPCListView"; this.RPCListView.Size = new System.Drawing.Size(1220, 1119); this.RPCListView.TabIndex = 1; this.RPCListView.UseCompatibleStateImageBehavior = false; this.RPCListView.View = System.Windows.Forms.View.Details; this.RPCListView.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.RPCListView_ColumnClick); // // columnHeader6 // this.columnHeader6.Text = "Total Size (KBytes)"; // // columnHeader7 // this.columnHeader7.Text = "Count"; // // columnHeader8 // this.columnHeader8.Text = "Average Size (Bytes)"; // // columnHeader9 // this.columnHeader9.Text = "Average Size Bits"; // // columnHeader10 // this.columnHeader10.Text = "RPC"; this.columnHeader10.Width = 145; // // MainWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1255, 1069); this.Controls.Add(this.tabControl1); this.Controls.Add(this.OpenButton); this.Name = "MainWindow"; this.Text = "Network Profiler"; ((System.ComponentModel.ISupportInitialize)(this.NetworkChart)).EndInit(); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.tabPage3.ResumeLayout(false); this.tabPage4.ResumeLayout(false); this.tabPage5.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button OpenButton; private System.Windows.Forms.DataVisualization.Charting.Chart NetworkChart; private System.Windows.Forms.CheckedListBox ChartListBox; private System.Windows.Forms.RichTextBox SummaryTextBox; private System.Windows.Forms.RichTextBox DetailTextBox; private System.Windows.Forms.TextBox ActorFilterTextBox; private System.Windows.Forms.TextBox PropertyFilterTextBox; private System.Windows.Forms.TextBox RPCFilterTextBox; private System.Windows.Forms.Button ApplyFiltersButton; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TabPage tabPage4; private System.Windows.Forms.ListView PropertyListView; private System.Windows.Forms.ColumnHeader SizeBits; private System.Windows.Forms.ColumnHeader Count; private System.Windows.Forms.ColumnHeader AvgSizeBytes; private System.Windows.Forms.ColumnHeader Property; private System.Windows.Forms.TabPage tabPage5; private System.Windows.Forms.ColumnHeader AvgSizeBits; private System.Windows.Forms.ListView ActorListView; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.ColumnHeader columnHeader3; private System.Windows.Forms.ColumnHeader columnHeader4; private System.Windows.Forms.ColumnHeader columnHeader5; private System.Windows.Forms.ListView RPCListView; private System.Windows.Forms.ColumnHeader columnHeader6; private System.Windows.Forms.ColumnHeader columnHeader7; private System.Windows.Forms.ColumnHeader columnHeader8; private System.Windows.Forms.ColumnHeader columnHeader9; private System.Windows.Forms.ColumnHeader columnHeader10; private System.Windows.Forms.TreeView ActorPerformanceView; private System.Windows.Forms.RadioButton StackedBunchSizeRadioButton; private System.Windows.Forms.RadioButton LineViewRadioButton; } }
// 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. #nullable enable using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using osu.Framework; using osu.Framework.Bindables; using osu.Framework.Logging; using osu.Game.Online.API; namespace osu.Game.Online { public class HubClientConnector : IHubClientConnector { /// <summary> /// Invoked whenever a new hub connection is built, to configure it before it's started. /// </summary> public Action<HubConnection>? ConfigureConnection { get; set; } private readonly string clientName; private readonly string endpoint; private readonly string versionHash; private readonly bool preferMessagePack; private readonly IAPIProvider api; /// <summary> /// The current connection opened by this connector. /// </summary> public HubConnection? CurrentConnection { get; private set; } /// <summary> /// Whether this is connected to the hub, use <see cref="CurrentConnection"/> to access the connection, if this is <c>true</c>. /// </summary> public IBindable<bool> IsConnected => isConnected; private readonly Bindable<bool> isConnected = new Bindable<bool>(); private readonly SemaphoreSlim connectionLock = new SemaphoreSlim(1); private CancellationTokenSource connectCancelSource = new CancellationTokenSource(); private readonly IBindable<APIState> apiState = new Bindable<APIState>(); /// <summary> /// Constructs a new <see cref="HubClientConnector"/>. /// </summary> /// <param name="clientName">The name of the client this connector connects for, used for logging.</param> /// <param name="endpoint">The endpoint to the hub.</param> /// <param name="api"> An API provider used to react to connection state changes.</param> /// <param name="versionHash">The hash representing the current game version, used for verification purposes.</param> /// <param name="preferMessagePack">Whether to use MessagePack for serialisation if available on this platform.</param> public HubClientConnector(string clientName, string endpoint, IAPIProvider api, string versionHash, bool preferMessagePack = true) { this.clientName = clientName; this.endpoint = endpoint; this.api = api; this.versionHash = versionHash; this.preferMessagePack = preferMessagePack; apiState.BindTo(api.State); apiState.BindValueChanged(state => { switch (state.NewValue) { case APIState.Failing: case APIState.Offline: Task.Run(() => disconnect(true)); break; case APIState.Online: Task.Run(connect); break; } }, true); } private async Task connect() { cancelExistingConnect(); if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false)) throw new TimeoutException("Could not obtain a lock to connect. A previous attempt is likely stuck."); try { while (apiState.Value == APIState.Online) { // ensure any previous connection was disposed. // this will also create a new cancellation token source. await disconnect(false).ConfigureAwait(false); // this token will be valid for the scope of this connection. // if cancelled, we can be sure that a disconnect or reconnect is handled elsewhere. var cancellationToken = connectCancelSource.Token; cancellationToken.ThrowIfCancellationRequested(); Logger.Log($"{clientName} connecting...", LoggingTarget.Network); try { // importantly, rebuild the connection each attempt to get an updated access token. CurrentConnection = buildConnection(cancellationToken); await CurrentConnection.StartAsync(cancellationToken).ConfigureAwait(false); Logger.Log($"{clientName} connected!", LoggingTarget.Network); isConnected.Value = true; return; } catch (OperationCanceledException) { //connection process was cancelled. throw; } catch (Exception e) { await handleErrorAndDelay(e, cancellationToken).ConfigureAwait(false); } } } finally { connectionLock.Release(); } } /// <summary> /// Handles an exception and delays an async flow. /// </summary> private async Task handleErrorAndDelay(Exception exception, CancellationToken cancellationToken) { Logger.Log($"{clientName} connection error: {exception}", LoggingTarget.Network); await Task.Delay(5000, cancellationToken).ConfigureAwait(false); } private HubConnection buildConnection(CancellationToken cancellationToken) { var builder = new HubConnectionBuilder() .WithUrl(endpoint, options => { options.Headers.Add("Authorization", $"Bearer {api.AccessToken}"); options.Headers.Add("OsuVersionHash", versionHash); }); if (RuntimeInfo.SupportsJIT && preferMessagePack) { builder.AddMessagePackProtocol(options => { options.SerializerOptions = SignalRUnionWorkaroundResolver.OPTIONS; }); } else { // eventually we will precompile resolvers for messagepack, but this isn't working currently // see https://github.com/neuecc/MessagePack-CSharp/issues/780#issuecomment-768794308. builder.AddNewtonsoftJsonProtocol(options => { options.PayloadSerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; options.PayloadSerializerSettings.Converters = new List<JsonConverter> { new SignalRDerivedTypeWorkaroundJsonConverter(), }; }); } var newConnection = builder.Build(); ConfigureConnection?.Invoke(newConnection); newConnection.Closed += ex => onConnectionClosed(ex, cancellationToken); return newConnection; } private async Task onConnectionClosed(Exception? ex, CancellationToken cancellationToken) { isConnected.Value = false; if (ex != null) await handleErrorAndDelay(ex, cancellationToken).ConfigureAwait(false); else Logger.Log($"{clientName} disconnected", LoggingTarget.Network); // make sure a disconnect wasn't triggered (and this is still the active connection). if (!cancellationToken.IsCancellationRequested) await Task.Run(connect, default).ConfigureAwait(false); } private async Task disconnect(bool takeLock) { cancelExistingConnect(); if (takeLock) { if (!await connectionLock.WaitAsync(10000).ConfigureAwait(false)) throw new TimeoutException("Could not obtain a lock to disconnect. A previous attempt is likely stuck."); } try { if (CurrentConnection != null) await CurrentConnection.DisposeAsync().ConfigureAwait(false); } finally { CurrentConnection = null; if (takeLock) connectionLock.Release(); } } private void cancelExistingConnect() { connectCancelSource.Cancel(); connectCancelSource = new CancellationTokenSource(); } public override string ToString() => $"Connector for {clientName} ({(IsConnected.Value ? "connected" : "not connected")}"; public void Dispose() { apiState.UnbindAll(); cancelExistingConnect(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using Xunit; namespace System.Tests { public static partial class MathTests { public static IEnumerable<object[]> Clamp_UnsignedInt_TestData() { yield return new object[] { 1, 1, 3, 1 }; yield return new object[] { 2, 1, 3, 2 }; yield return new object[] { 3, 1, 3, 3 }; yield return new object[] { 1, 1, 1, 1 }; yield return new object[] { 0, 1, 3, 1 }; yield return new object[] { 4, 1, 3, 3 }; } public static IEnumerable<object[]> Clamp_SignedInt_TestData() { yield return new object[] { -1, -1, 1, -1 }; yield return new object[] { 0, -1, 1, 0 }; yield return new object[] { 1, -1, 1, 1 }; yield return new object[] { 1, -1, 1, 1 }; yield return new object[] { -2, -1, 1, -1 }; yield return new object[] { 2, -1, 1, 1 }; } [Theory] [InlineData( double.NegativeInfinity, double.NaN, 0.0)] [InlineData(-3.1415926535897932, double.NaN, 0.0)] // value: -(pi) [InlineData(-2.7182818284590452, double.NaN, 0.0)] // value: -(e) [InlineData(-1.4142135623730950, double.NaN, 0.0)] // value: -(sqrt(2)) [InlineData(-1.0, double.NaN, 0.0)] [InlineData(-0.69314718055994531, double.NaN, 0.0)] // value: -(ln(2)) [InlineData(-0.43429448190325183, double.NaN, 0.0)] // value: -(log10(e)) [InlineData(-0.0, double.NaN, 0.0)] [InlineData( double.NaN, double.NaN, 0.0)] [InlineData( 0.0, double.NaN, 0.0)] [InlineData( 1.0, 0.0, CrossPlatformMachineEpsilon)] [InlineData( 1.0510897883672876, 0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: (1 / pi) [InlineData( 1.0957974645564909, 0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: (log10(e)) [InlineData( 1.2095794864199787, 0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: (2 / pi) [InlineData( 1.25, 0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: (ln(2)) [InlineData( 1.2605918365213561, 0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2)) [InlineData( 1.3246090892520058, 0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: (pi / 4) [InlineData( 1.5430806348152438, 1.0, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.7071001431069344, 1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi)) [InlineData( 2.1781835566085709, 1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2)) [InlineData( 2.2341880974508023, 1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e)) [InlineData( 2.5091784786580568, 1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2) [InlineData( 5.05, 2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10)) [InlineData( 7.6101251386622884, 2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: (e) [InlineData( 11.591953275521521, 3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: (pi) [InlineData( double.PositiveInfinity, double.PositiveInfinity, 0.0)] public static void Acosh(double value, double expectedResult, double allowedVariance) { AssertEqual(expectedResult, Math.Acosh(value), allowedVariance); } [Theory] [InlineData( double.NegativeInfinity, double.NegativeInfinity, 0.0)] [InlineData(-11.548739357257748, -3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: -(pi) [InlineData(-7.5441371028169758, -2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: -(e) [InlineData(-4.95, -2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10)) [InlineData(-2.3012989023072949, -1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2) [InlineData(-1.9978980091062796, -1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e)) [InlineData(-1.9350668221743567, -1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2)) [InlineData(-1.3835428792038633, -1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi)) [InlineData(-1.1752011936438015, -1, CrossPlatformMachineEpsilon * 10)] [InlineData(-0.86867096148600961, -0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: -(pi / 4) [InlineData(-0.76752314512611633, -0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2)) [InlineData(-0.75, -0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: -(ln(2)) [InlineData(-0.68050167815224332, -0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: -(2 / pi) [InlineData(-0.44807597941469025, -0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: -(log10(e)) [InlineData(-0.32371243907207108, -0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: -(1 / pi) [InlineData(-0.0, -0.0, 0.0)] [InlineData( double.NaN, double.NaN, 0.0)] [InlineData( 0.0, 0.0, 0.0)] [InlineData( 0.32371243907207108, 0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: (1 / pi) [InlineData( 0.44807597941469025, 0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: (log10(e)) [InlineData( 0.68050167815224332, 0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: (2 / pi) [InlineData( 0.75, 0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: (ln(2)) [InlineData( 0.76752314512611633, 0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2)) [InlineData( 0.86867096148600961, 0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: (pi / 4) [InlineData( 1.1752011936438015, 1.0, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.3835428792038633, 1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi)) [InlineData( 1.9350668221743567, 1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2)) [InlineData( 1.9978980091062796, 1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e)) [InlineData( 2.3012989023072949, 1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2) [InlineData( 4.95, 2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10)) [InlineData( 7.5441371028169758, 2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: (e) [InlineData( 11.548739357257748, 3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: (pi) [InlineData( double.PositiveInfinity, double.PositiveInfinity, 0.0)] public static void Asinh(double value, double expectedResult, double allowedVariance) { AssertEqual(expectedResult, Math.Asinh(value), allowedVariance); } [Theory] [InlineData( double.NegativeInfinity, double.NaN, 0.0)] [InlineData(-3.1415926535897932, double.NaN, 0.0)] // value: -(pi) [InlineData(-2.7182818284590452, double.NaN, 0.0)] // value: -(e) [InlineData(-1.4142135623730950, double.NaN, 0.0)] // value: -(sqrt(2)) [InlineData(-1.0, double.NegativeInfinity, CrossPlatformMachineEpsilon * 10)] [InlineData(-0.99627207622074994, -3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: -(pi) [InlineData(-0.99132891580059984, -2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: -(e) [InlineData(-0.98019801980198020, -2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10)) [InlineData(-0.91715233566727435, -1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2) [InlineData(-0.89423894585503855, -1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e)) [InlineData(-0.88838556158566054, -1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2)) [InlineData(-0.81046380599898809, -1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi)) [InlineData(-0.76159415595576489, -1.0, CrossPlatformMachineEpsilon * 10)] [InlineData(-0.65579420263267244, -0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: -(pi / 4) [InlineData(-0.60885936501391381, -0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2)) [InlineData(-0.6, -0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: -(ln(2)) [InlineData(-0.56259360033158334, -0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: -(2 / pi) [InlineData(-0.40890401183401433, -0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: -(log10(e)) [InlineData(-0.30797791269089433, -0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: -(1 / pi) [InlineData(-0.0, -0.0, 0.0)] [InlineData( double.NaN, double.NaN, 0.0)] [InlineData( 0.0, 0.0, 0.0)] [InlineData( 0.30797791269089433, 0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: (1 / pi) [InlineData( 0.40890401183401433, 0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: (log10(e)) [InlineData( 0.56259360033158334, 0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: (2 / pi) [InlineData( 0.6, 0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: (ln(2)) [InlineData( 0.60885936501391381, 0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2)) [InlineData( 0.65579420263267244, 0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: (pi / 4) [InlineData( 0.76159415595576489, 1.0, CrossPlatformMachineEpsilon * 10)] [InlineData( 0.81046380599898809, 1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi)) [InlineData( 0.88838556158566054, 1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2)) [InlineData( 0.89423894585503855, 1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e)) [InlineData( 0.91715233566727435, 1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2) [InlineData( 0.98019801980198020, 2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10)) [InlineData( 0.99132891580059984, 2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: (e) [InlineData( 0.99627207622074994, 3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: (pi) [InlineData( 1.0, double.PositiveInfinity, 0.0)] [InlineData( 1.4142135623730950, double.NaN, 0.0)] // value: (sqrt(2)) [InlineData( 2.7182818284590452, double.NaN, 0.0)] // value: (e) [InlineData( 3.1415926535897932, double.NaN, 0.0)] // value: (pi) [InlineData( double.PositiveInfinity, double.NaN, 0.0)] public static void Atanh(double value, double expectedResult, double allowedVariance) { AssertEqual(expectedResult, Math.Atanh(value), allowedVariance); } [Theory] [InlineData( double.NegativeInfinity, double.NegativeInfinity)] [InlineData(-3.1415926535897932, -3.1415926535897936)] // value: -(pi) [InlineData(-2.7182818284590452, -2.7182818284590455)] // value: -(e) [InlineData(-2.3025850929940457, -2.3025850929940463)] // value: -(ln(10)) [InlineData(-1.5707963267948966, -1.5707963267948968)] // value: -(pi / 2) [InlineData(-1.4426950408889634, -1.4426950408889636)] // value: -(log2(e)) [InlineData(-1.4142135623730950, -1.4142135623730951)] // value: -(sqrt(2)) [InlineData(-1.1283791670955126, -1.1283791670955128)] // value: -(2 / sqrt(pi)) [InlineData(-1.0, -1.0000000000000002)] [InlineData(-0.78539816339744831, -0.78539816339744839)] // value: -(pi / 4) [InlineData(-0.70710678118654752, -0.70710678118654768)] // value: -(1 / sqrt(2)) [InlineData(-0.69314718055994531, -0.69314718055994540)] // value: -(ln(2)) [InlineData(-0.63661977236758134, -0.63661977236758149)] // value: -(2 / pi) [InlineData(-0.43429448190325183, -0.43429448190325187)] // value: -(log10(e)) [InlineData(-0.31830988618379067, -0.31830988618379075)] // value: -(1 / pi) [InlineData(-0.0, -double.Epsilon)] [InlineData( double.NaN, double.NaN)] [InlineData( 0.0, -double.Epsilon)] [InlineData( 0.31830988618379067, 0.31830988618379064)] // value: (1 / pi) [InlineData( 0.43429448190325183, 0.43429448190325176)] // value: (log10(e)) [InlineData( 0.63661977236758134, 0.63661977236758127)] // value: (2 / pi) [InlineData( 0.69314718055994531, 0.69314718055994518)] // value: (ln(2)) [InlineData( 0.70710678118654752, 0.70710678118654746)] // value: (1 / sqrt(2)) [InlineData( 0.78539816339744831, 0.78539816339744817)] // value: (pi / 4) [InlineData( 1.0, 0.99999999999999989)] [InlineData( 1.1283791670955126, 1.1283791670955123)] // value: (2 / sqrt(pi)) [InlineData( 1.4142135623730950, 1.4142135623730947)] // value: (sqrt(2)) [InlineData( 1.4426950408889634, 1.4426950408889632)] // value: (log2(e)) [InlineData( 1.5707963267948966, 1.5707963267948963)] // value: (pi / 2) [InlineData( 2.3025850929940457, 2.3025850929940455)] // value: (ln(10)) [InlineData( 2.7182818284590452, 2.7182818284590446)] // value: (e) [InlineData( 3.1415926535897932, 3.1415926535897927)] // value: (pi) [InlineData( double.PositiveInfinity, double.MaxValue)] public static void BitDecrement(double value, double expectedResult) { AssertEqual(expectedResult, Math.BitDecrement(value), 0.0); } [Theory] [InlineData( double.NegativeInfinity, double.MinValue)] [InlineData(-3.1415926535897932, -3.1415926535897927)] // value: -(pi) [InlineData(-2.7182818284590452, -2.7182818284590446)] // value: -(e) [InlineData(-2.3025850929940457, -2.3025850929940455)] // value: -(ln(10)) [InlineData(-1.5707963267948966, -1.5707963267948963)] // value: -(pi / 2) [InlineData(-1.4426950408889634, -1.4426950408889632)] // value: -(log2(e)) [InlineData(-1.4142135623730950, -1.4142135623730947)] // value: -(sqrt(2)) [InlineData(-1.1283791670955126, -1.1283791670955123)] // value: -(2 / sqrt(pi)) [InlineData(-1.0, -0.99999999999999989)] [InlineData(-0.78539816339744831, -0.78539816339744817)] // value: -(pi / 4) [InlineData(-0.70710678118654752, -0.70710678118654746)] // value: -(1 / sqrt(2)) [InlineData(-0.69314718055994531, -0.69314718055994518)] // value: -(ln(2)) [InlineData(-0.63661977236758134, -0.63661977236758127)] // value: -(2 / pi) [InlineData(-0.43429448190325183, -0.43429448190325176)] // value: -(log10(e)) [InlineData(-0.31830988618379067, -0.31830988618379064)] // value: -(1 / pi) [InlineData(-0.0, double.Epsilon)] [InlineData( double.NaN, double.NaN)] [InlineData( 0.0, double.Epsilon)] [InlineData( 0.31830988618379067, 0.31830988618379075)] // value: (1 / pi) [InlineData( 0.43429448190325183, 0.43429448190325187)] // value: (log10(e)) [InlineData( 0.63661977236758134, 0.63661977236758149)] // value: (2 / pi) [InlineData( 0.69314718055994531, 0.69314718055994540)] // value: (ln(2)) [InlineData( 0.70710678118654752, 0.70710678118654768)] // value: (1 / sqrt(2)) [InlineData( 0.78539816339744831, 0.78539816339744839)] // value: (pi / 4) [InlineData( 1.0, 1.0000000000000002 )] [InlineData( 1.1283791670955126, 1.1283791670955128 )] // value: (2 / sqrt(pi)) [InlineData( 1.4142135623730950, 1.4142135623730951 )] // value: (sqrt(2)) [InlineData( 1.4426950408889634, 1.4426950408889636 )] // value: (log2(e)) [InlineData( 1.5707963267948966, 1.5707963267948968 )] // value: (pi / 2) [InlineData( 2.3025850929940457, 2.3025850929940463 )] // value: (ln(10)) [InlineData( 2.7182818284590452, 2.7182818284590455 )] // value: (e) [InlineData( 3.1415926535897932, 3.1415926535897936 )] // value: (pi) [InlineData( double.PositiveInfinity, double.PositiveInfinity)] public static void BitIncrement(double value, double expectedResult) { AssertEqual(expectedResult, Math.BitIncrement(value), 0.0); } [Theory] [InlineData( double.NegativeInfinity, double.NegativeInfinity, 0.0)] [InlineData(-3.1415926535897932, -1.4645918875615233, CrossPlatformMachineEpsilon * 10)] // value: -(pi) [InlineData(-2.7182818284590452, -1.3956124250860895, CrossPlatformMachineEpsilon * 10)] // value: -(e) [InlineData(-2.3025850929940457, -1.3205004784536852, CrossPlatformMachineEpsilon * 10)] // value: -(ln(10)) [InlineData(-1.5707963267948966, -1.1624473515096265, CrossPlatformMachineEpsilon * 10)] // value: -(pi / 2) [InlineData(-1.4426950408889634, -1.1299472763373901, CrossPlatformMachineEpsilon * 10)] // value: -(log2(e)) [InlineData(-1.4142135623730950, -1.1224620483093730, CrossPlatformMachineEpsilon * 10)] // value: -(sqrt(2)) [InlineData(-1.1283791670955126, -1.0410821966965807, CrossPlatformMachineEpsilon * 10)] // value: -(2 / sqrt(pi)) [InlineData(-1.0, -1.0, CrossPlatformMachineEpsilon * 10)] [InlineData(-0.78539816339744831, -0.92263507432201421, CrossPlatformMachineEpsilon)] // value: -(pi / 4) [InlineData(-0.70710678118654752, -0.89089871814033930, CrossPlatformMachineEpsilon)] // value: -(1 / sqrt(2)) [InlineData(-0.69314718055994531, -0.88499704450051772, CrossPlatformMachineEpsilon)] // value: -(ln(2)) [InlineData(-0.63661977236758134, -0.86025401382809963, CrossPlatformMachineEpsilon)] // value: -(2 / pi) [InlineData(-0.43429448190325183, -0.75728863133090766, CrossPlatformMachineEpsilon)] // value: -(log10(e)) [InlineData(-0.31830988618379067, -0.68278406325529568, CrossPlatformMachineEpsilon)] // value: -(1 / pi) [InlineData(-0.0, -0.0, 0.0)] [InlineData( double.NaN, double.NaN, 0.0)] [InlineData( 0.0, 0.0, 0.0)] [InlineData( 0.31830988618379067, 0.68278406325529568, CrossPlatformMachineEpsilon)] // value: (1 / pi) [InlineData( 0.43429448190325183, 0.75728863133090766, CrossPlatformMachineEpsilon)] // value: (log10(e)) [InlineData( 0.63661977236758134, 0.86025401382809963, CrossPlatformMachineEpsilon)] // value: (2 / pi) [InlineData( 0.69314718055994531, 0.88499704450051772, CrossPlatformMachineEpsilon)] // value: (ln(2)) [InlineData( 0.70710678118654752, 0.89089871814033930, CrossPlatformMachineEpsilon)] // value: (1 / sqrt(2)) [InlineData( 0.78539816339744831, 0.92263507432201421, CrossPlatformMachineEpsilon)] // value: (pi / 4) [InlineData( 1.0, 1.0, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.1283791670955126, 1.0410821966965807, CrossPlatformMachineEpsilon * 10)] // value: (2 / sqrt(pi)) [InlineData( 1.4142135623730950, 1.1224620483093730, CrossPlatformMachineEpsilon * 10)] // value: (sqrt(2)) [InlineData( 1.4426950408889634, 1.1299472763373901, CrossPlatformMachineEpsilon * 10)] // value: (log2(e)) [InlineData( 1.5707963267948966, 1.1624473515096265, CrossPlatformMachineEpsilon * 10)] // value: (pi / 2) [InlineData( 2.3025850929940457, 1.3205004784536852, CrossPlatformMachineEpsilon * 10)] // value: (ln(10)) [InlineData( 2.7182818284590452, 1.3956124250860895, CrossPlatformMachineEpsilon * 10)] // value: (e) [InlineData( 3.1415926535897932, 1.4645918875615233, CrossPlatformMachineEpsilon * 10)] // value: (pi) [InlineData( double.PositiveInfinity, double.PositiveInfinity, 0.0)] public static void Cbrt(double value, double expectedResult, double allowedVariance) { AssertEqual(expectedResult, Math.Cbrt(value), allowedVariance); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] public static void Clamp_SByte(sbyte value, sbyte min, sbyte max, sbyte expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_UnsignedInt_TestData))] public static void Clamp_Byte(byte value, byte min, byte max, byte expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] public static void Clamp_Short(short value, short min, short max, short expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_UnsignedInt_TestData))] public static void Clamp_UShort(ushort value, ushort min, ushort max, ushort expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] public static void Clamp_Int(int value, int min, int max, int expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_UnsignedInt_TestData))] public static void Clamp_UInt(uint value, uint min, uint max, uint expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] public static void Clamp_Long(long value, long min, long max, long expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_UnsignedInt_TestData))] public static void Clamp_ULong(ulong value, ulong min, ulong max, ulong expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] [InlineData(double.NegativeInfinity, double.NegativeInfinity, double.PositiveInfinity, double.NegativeInfinity)] [InlineData(1, double.NegativeInfinity, double.PositiveInfinity, 1)] [InlineData(double.PositiveInfinity, double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(1, double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(1, double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity)] [InlineData(double.NaN, double.NaN, double.NaN, double.NaN)] [InlineData(double.NaN, double.NaN, 1, double.NaN)] [InlineData(double.NaN, 1, double.NaN, double.NaN)] [InlineData(double.NaN, 1, 1, double.NaN)] [InlineData(1, double.NaN, double.NaN, 1)] [InlineData(1, double.NaN, 1, 1)] [InlineData(1, 1, double.NaN, 1)] public static void Clamp_Double(double value, double min, double max, double expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] [InlineData(float.NegativeInfinity, float.NegativeInfinity, float.PositiveInfinity, float.NegativeInfinity)] [InlineData(1, float.NegativeInfinity, float.PositiveInfinity, 1)] [InlineData(float.PositiveInfinity, float.NegativeInfinity, float.PositiveInfinity, float.PositiveInfinity)] [InlineData(1, float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity)] [InlineData(1, float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity)] [InlineData(float.NaN, float.NaN, float.NaN, float.NaN)] [InlineData(float.NaN, float.NaN, 1, float.NaN)] [InlineData(float.NaN, 1, float.NaN, float.NaN)] [InlineData(float.NaN, 1, 1, float.NaN)] [InlineData(1, float.NaN, float.NaN, 1)] [InlineData(1, float.NaN, 1, 1)] [InlineData(1, 1, float.NaN, 1)] public static void Clamp_Float(float value, float min, float max, float expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Theory] [MemberData(nameof(Clamp_SignedInt_TestData))] public static void Clamp_Decimal(decimal value, decimal min, decimal max, decimal expected) { Assert.Equal(expected, Math.Clamp(value, min, max)); } [Fact] public static void Clamp_MinGreaterThanMax_ThrowsArgumentException() { AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((sbyte)1, (sbyte)2, (sbyte)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((byte)1, (byte)2, (byte)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((short)1, (short)2, (short)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((ushort)1, (ushort)2, (ushort)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((int)1, (int)2, (int)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((uint)1, (uint)2, (uint)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((long)1, (long)2, (long)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((ulong)1, (ulong)2, (ulong)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((float)1, (float)2, (float)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((double)1, (double)2, (double)1)); AssertExtensions.Throws<ArgumentException>(null, () => Math.Clamp((decimal)1, (decimal)2, (decimal)1)); } [Theory] [InlineData( double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity)] [InlineData( double.NegativeInfinity, -3.1415926535897932, double.NegativeInfinity)] [InlineData( double.NegativeInfinity, -0.0, double.NegativeInfinity)] [InlineData( double.NegativeInfinity, double.NaN, double.NegativeInfinity)] [InlineData( double.NegativeInfinity, 0.0, double.PositiveInfinity)] [InlineData( double.NegativeInfinity, 3.1415926535897932, double.PositiveInfinity)] [InlineData( double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(-3.1415926535897932, double.NegativeInfinity, -3.1415926535897932)] [InlineData(-3.1415926535897932, -3.1415926535897932, -3.1415926535897932)] [InlineData(-3.1415926535897932, -0.0, -3.1415926535897932)] [InlineData(-3.1415926535897932, double.NaN, -3.1415926535897932)] [InlineData(-3.1415926535897932, 0.0, 3.1415926535897932)] [InlineData(-3.1415926535897932, 3.1415926535897932, 3.1415926535897932)] [InlineData(-3.1415926535897932, double.PositiveInfinity, 3.1415926535897932)] [InlineData(-0.0, double.NegativeInfinity, -0.0)] [InlineData(-0.0, -3.1415926535897932, -0.0)] [InlineData(-0.0, -0.0, -0.0)] [InlineData(-0.0, double.NaN, -0.0)] [InlineData(-0.0, 0.0, 0.0)] [InlineData(-0.0, 3.1415926535897932, 0.0)] [InlineData(-0.0, double.PositiveInfinity, 0.0)] [InlineData( double.NaN, double.NegativeInfinity, double.NaN)] [InlineData( double.NaN, -3.1415926535897932, double.NaN)] [InlineData( double.NaN, -0.0, double.NaN)] [InlineData( double.NaN, double.NaN, double.NaN)] [InlineData( double.NaN, 0.0, double.NaN)] [InlineData( double.NaN, 3.1415926535897932, double.NaN)] [InlineData( double.NaN, double.PositiveInfinity, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, -0.0)] [InlineData( 0.0, -3.1415926535897932, -0.0)] [InlineData( 0.0, -0.0, -0.0)] [InlineData( 0.0, double.NaN, -0.0)] [InlineData( 0.0, 0.0, 0.0)] [InlineData( 0.0, 3.1415926535897932, 0.0)] [InlineData( 0.0, double.PositiveInfinity, 0.0)] [InlineData( 3.1415926535897932, double.NegativeInfinity, -3.1415926535897932)] [InlineData( 3.1415926535897932, -3.1415926535897932, -3.1415926535897932)] [InlineData( 3.1415926535897932, -0.0, -3.1415926535897932)] [InlineData( 3.1415926535897932, double.NaN, -3.1415926535897932)] [InlineData( 3.1415926535897932, 0.0, 3.1415926535897932)] [InlineData( 3.1415926535897932, 3.1415926535897932, 3.1415926535897932)] [InlineData( 3.1415926535897932, double.PositiveInfinity, 3.1415926535897932)] [InlineData( double.PositiveInfinity, double.NegativeInfinity, double.NegativeInfinity)] [InlineData( double.PositiveInfinity, -3.1415926535897932, double.NegativeInfinity)] [InlineData( double.PositiveInfinity, -0.0, double.NegativeInfinity)] [InlineData( double.PositiveInfinity, double.NaN, double.NegativeInfinity)] [InlineData( double.PositiveInfinity, 0.0, double.PositiveInfinity)] [InlineData( double.PositiveInfinity, 3.1415926535897932, double.PositiveInfinity)] [InlineData( double.PositiveInfinity, double.PositiveInfinity, double.PositiveInfinity)] public static void CopySign(double x, double y, double expectedResult) { AssertEqual(expectedResult, Math.CopySign(x, y), 0.0); } [Theory] [InlineData( double.NegativeInfinity, double.NegativeInfinity, double.NegativeInfinity, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, double.NegativeInfinity, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, -3.1415926535897932, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, -0.0, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, double.NaN, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, 0.0, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, 3.1415926535897932, double.NaN)] [InlineData( double.NegativeInfinity, -0.0, double.PositiveInfinity, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, double.NegativeInfinity, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, -3.1415926535897932, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, -0.0, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, double.NaN, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, 0.0, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, 3.1415926535897932, double.NaN)] [InlineData( double.NegativeInfinity, 0.0, double.PositiveInfinity, double.NaN)] [InlineData( double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity, double.NaN)] [InlineData(-1e308, 2.0, 1e308, -1e308)] [InlineData(-1e308, 2.0, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(-5, 4, -3, -23)] [InlineData(-0.0, double.NegativeInfinity, double.NegativeInfinity, double.NaN)] [InlineData(-0.0, double.NegativeInfinity, -3.1415926535897932, double.NaN)] [InlineData(-0.0, double.NegativeInfinity, -0.0, double.NaN)] [InlineData(-0.0, double.NegativeInfinity, double.NaN, double.NaN)] [InlineData(-0.0, double.NegativeInfinity, 0.0, double.NaN)] [InlineData(-0.0, double.NegativeInfinity, 3.1415926535897932, double.NaN)] [InlineData(-0.0, double.NegativeInfinity, double.PositiveInfinity, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, double.NegativeInfinity, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, -3.1415926535897932, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, -0.0, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, double.NaN, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, 0.0, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, 3.1415926535897932, double.NaN)] [InlineData(-0.0, double.PositiveInfinity, double.PositiveInfinity, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, double.NegativeInfinity, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, -3.1415926535897932, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, -0.0, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, double.NaN, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, 0.0, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, 3.1415926535897932, double.NaN)] [InlineData( 0.0, double.NegativeInfinity, double.PositiveInfinity, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, double.NegativeInfinity, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, -3.1415926535897932, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, -0.0, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, double.NaN, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, 0.0, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, 3.1415926535897932, double.NaN)] [InlineData( 0.0, double.PositiveInfinity, double.PositiveInfinity, double.NaN)] [InlineData( 5, 4, 3, 23)] [InlineData( 1e308, 2.0, -1e308, 1e308)] [InlineData( 1e308, 2.0, double.NegativeInfinity, double.NegativeInfinity)] [InlineData( double.PositiveInfinity, double.NegativeInfinity, double.PositiveInfinity, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, double.NegativeInfinity, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, -3.1415926535897932, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, -0.0, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, double.NaN, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, 0.0, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, 3.1415926535897932, double.NaN)] [InlineData( double.PositiveInfinity, -0.0, double.PositiveInfinity, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, double.NegativeInfinity, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, -3.1415926535897932, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, -0.0, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, double.NaN, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, 0.0, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, 3.1415926535897932, double.NaN)] [InlineData( double.PositiveInfinity, 0.0, double.PositiveInfinity, double.NaN)] [InlineData( double.PositiveInfinity, double.PositiveInfinity, double.NegativeInfinity, double.NaN)] public static void FusedMultiplyAdd(double x, double y, double z, double expectedResult) { AssertEqual(expectedResult, Math.FusedMultiplyAdd(x, y, z), 0.0); } [Theory] [InlineData( double.NegativeInfinity, unchecked((int)(0x7FFFFFFF)))] [InlineData(-0.0, unchecked((int)(0x80000000)))] [InlineData( double.NaN, unchecked((int)(0x7FFFFFFF)))] [InlineData( 0.0, unchecked((int)(0x80000000)))] [InlineData( 0.11331473229676087, -4)] [InlineData( 0.15195522325791297, -3)] [InlineData( 0.20269956628651730, -3)] [InlineData( 0.33662253682241906, -2)] [InlineData( 0.36787944117144232, -2)] [InlineData( 0.37521422724648177, -2)] [InlineData( 0.45742934732229695, -2)] [InlineData( 0.5, -1)] [InlineData( 0.58019181037172444, -1)] [InlineData( 0.61254732653606592, -1)] [InlineData( 0.61850313780157598, -1)] [InlineData( 0.64321824193300488, -1)] [InlineData( 0.74005557395545179, -1)] [InlineData( 0.80200887896145195, -1)] [InlineData( 1, 0)] [InlineData( 1.2468689889006383, 0)] [InlineData( 1.3512498725672678, 0)] [InlineData( 1.5546822754821001, 0)] [InlineData( 1.6168066722416747, 0)] [InlineData( 1.6325269194381528, 0)] [InlineData( 1.7235679341273495, 0)] [InlineData( 2, 1)] [InlineData( 2.1861299583286618, 1)] [InlineData( 2.6651441426902252, 1)] [InlineData( 2.7182818284590452, 1)] [InlineData( 2.9706864235520193, 1)] [InlineData( 4.9334096679145963, 2)] [InlineData( 6.5808859910179210, 2)] [InlineData( 8.8249778270762876, 3)] [InlineData( double.PositiveInfinity, unchecked((int)(0x7FFFFFFF)))] public static void ILogB(double value, int expectedResult) { Assert.Equal(expectedResult, Math.ILogB(value)); } [Theory] [InlineData( double.NegativeInfinity, double.NaN, 0.0)] [InlineData(-0.11331473229676087, double.NaN, 0.0)] [InlineData(-0.0, double.NegativeInfinity, 0.0)] [InlineData( double.NaN, double.NaN, 0.0)] [InlineData( 0.0, double.NegativeInfinity, 0.0)] [InlineData( 0.11331473229676087, -3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: -(pi) [InlineData( 0.15195522325791297, -2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: -(e) [InlineData( 0.20269956628651730, -2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: -(ln(10)) [InlineData( 0.33662253682241906, -1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: -(pi / 2) [InlineData( 0.36787944117144232, -1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: -(log2(e)) [InlineData( 0.37521422724648177, -1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: -(sqrt(2)) [InlineData( 0.45742934732229695, -1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: -(2 / sqrt(pi)) [InlineData( 0.5, -1.0, CrossPlatformMachineEpsilon * 10)] [InlineData( 0.58019181037172444, -0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: -(pi / 4) [InlineData( 0.61254732653606592, -0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: -(1 / sqrt(2)) [InlineData( 0.61850313780157598, -0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: -(ln(2)) [InlineData( 0.64321824193300488, -0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: -(2 / pi) [InlineData( 0.74005557395545179, -0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: -(log10(e)) [InlineData( 0.80200887896145195, -0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: -(1 / pi) [InlineData( 1, 0.0, 0.0)] [InlineData( 1.2468689889006383, 0.31830988618379067, CrossPlatformMachineEpsilon)] // expected: (1 / pi) [InlineData( 1.3512498725672678, 0.43429448190325183, CrossPlatformMachineEpsilon)] // expected: (log10(e)) [InlineData( 1.5546822754821001, 0.63661977236758134, CrossPlatformMachineEpsilon)] // expected: (2 / pi) [InlineData( 1.6168066722416747, 0.69314718055994531, CrossPlatformMachineEpsilon)] // expected: (ln(2)) [InlineData( 1.6325269194381528, 0.70710678118654752, CrossPlatformMachineEpsilon)] // expected: (1 / sqrt(2)) [InlineData( 1.7235679341273495, 0.78539816339744831, CrossPlatformMachineEpsilon)] // expected: (pi / 4) [InlineData( 2, 1.0, CrossPlatformMachineEpsilon * 10)] // value: (e) [InlineData( 2.1861299583286618, 1.1283791670955126, CrossPlatformMachineEpsilon * 10)] // expected: (2 / sqrt(pi)) [InlineData( 2.6651441426902252, 1.4142135623730950, CrossPlatformMachineEpsilon * 10)] // expected: (sqrt(2)) [InlineData( 2.7182818284590452, 1.4426950408889634, CrossPlatformMachineEpsilon * 10)] // expected: (log2(e)) [InlineData( 2.9706864235520193, 1.5707963267948966, CrossPlatformMachineEpsilon * 10)] // expected: (pi / 2) [InlineData( 4.9334096679145963, 2.3025850929940457, CrossPlatformMachineEpsilon * 10)] // expected: (ln(10)) [InlineData( 6.5808859910179210, 2.7182818284590452, CrossPlatformMachineEpsilon * 10)] // expected: (e) [InlineData( 8.8249778270762876, 3.1415926535897932, CrossPlatformMachineEpsilon * 10)] // expected: (pi) [InlineData( double.PositiveInfinity, double.PositiveInfinity, 0.0)] public static void Log2(double value, double expectedResult, double allowedVariance) { AssertEqual(expectedResult, Math.Log2(value), allowedVariance); } [Theory] [InlineData(double.NegativeInfinity, double.PositiveInfinity, double.PositiveInfinity)] [InlineData(double.MinValue, double.MaxValue, double.MaxValue)] [InlineData(double.NaN, double.NaN, double.NaN)] [InlineData(-0.0, 0.0, 0.0)] [InlineData(2.0, -3.0, -3.0)] [InlineData(3.0, -2.0, 3.0)] [InlineData(double.PositiveInfinity, double.NaN, double.NaN)] public static void MaxMagnitude(double x, double y, double expectedResult) { AssertEqual(expectedResult, Math.MaxMagnitude(x, y), 0.0); } [Theory] [InlineData(double.NegativeInfinity, double.PositiveInfinity, double.NegativeInfinity)] [InlineData(double.MinValue, double.MaxValue, double.MinValue)] [InlineData(double.NaN, double.NaN, double.NaN)] [InlineData(-0.0, 0.0, -0.0)] [InlineData(2.0, -3.0, 2.0)] [InlineData(3.0, -2.0, -2.0)] [InlineData(double.PositiveInfinity, double.NaN, double.NaN)] public static void MinMagnitude(double x, double y, double expectedResult) { AssertEqual(expectedResult, Math.MinMagnitude(x, y), 0.0); } [Theory] [InlineData( double.NegativeInfinity, unchecked((int)(0x7FFFFFFF)), double.NegativeInfinity, 0)] [InlineData(-0.11331473229676087, -3, -0.014164341537095108, CrossPlatformMachineEpsilon / 10)] [InlineData(-0.0, unchecked((int)(0x80000000)), -0.0, 0)] [InlineData( double.NaN, unchecked((int)(0x7FFFFFFF)), double.NaN, 0)] [InlineData( 0.0, unchecked((int)(0x80000000)), 0, 0)] [InlineData( 0.11331473229676087, -4, 0.0070821707685475542, CrossPlatformMachineEpsilon / 100)] [InlineData( 0.15195522325791297, -3, 0.018994402907239121, CrossPlatformMachineEpsilon / 10)] [InlineData( 0.20269956628651730, -3, 0.025337445785814663, CrossPlatformMachineEpsilon / 10)] [InlineData( 0.33662253682241906, -2, 0.084155634205604762, CrossPlatformMachineEpsilon / 10)] [InlineData( 0.36787944117144232, -2, 0.091969860292860584, CrossPlatformMachineEpsilon / 10)] [InlineData( 0.37521422724648177, -2, 0.093803556811620448, CrossPlatformMachineEpsilon / 10)] [InlineData( 0.45742934732229695, -2, 0.11435733683057424, CrossPlatformMachineEpsilon)] [InlineData( 0.5, -1, 0.25, CrossPlatformMachineEpsilon)] [InlineData( 0.58019181037172444, -1, 0.2900959051858622, CrossPlatformMachineEpsilon)] [InlineData( 0.61254732653606592, -1, 0.30627366326803296, CrossPlatformMachineEpsilon)] [InlineData( 0.61850313780157598, -1, 0.30925156890078798, CrossPlatformMachineEpsilon)] [InlineData( 0.64321824193300488, -1, 0.32160912096650246, CrossPlatformMachineEpsilon)] [InlineData( 0.74005557395545179, -1, 0.37002778697772587, CrossPlatformMachineEpsilon)] [InlineData( 0.80200887896145195, -1, 0.40100443948072595, CrossPlatformMachineEpsilon)] [InlineData( 1, 0, 1, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.2468689889006383, 0, 1.2468689889006384, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.3512498725672678, 0, 1.3512498725672677, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.5546822754821001, 0, 1.5546822754821001, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.6168066722416747, 0, 1.6168066722416747, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.6325269194381528, 0, 1.6325269194381529, CrossPlatformMachineEpsilon * 10)] [InlineData( 1.7235679341273495, 0, 1.7235679341273495, CrossPlatformMachineEpsilon * 10)] [InlineData( 2, 1, 4, CrossPlatformMachineEpsilon * 10)] [InlineData( 2.1861299583286618, 1, 4.3722599166573239, CrossPlatformMachineEpsilon * 10)] [InlineData( 2.6651441426902252, 1, 5.3302882853804503, CrossPlatformMachineEpsilon * 10)] [InlineData( 2.7182818284590452, 1, 5.4365636569180902, CrossPlatformMachineEpsilon * 10)] [InlineData( 2.9706864235520193, 1, 5.9413728471040388, CrossPlatformMachineEpsilon * 10)] [InlineData( 4.9334096679145963, 2, 19.733638671658387, CrossPlatformMachineEpsilon * 100)] [InlineData( 6.5808859910179210, 2, 26.323543964071686, CrossPlatformMachineEpsilon * 100)] [InlineData( 8.8249778270762876, 3, 70.599822616610297, CrossPlatformMachineEpsilon * 100)] [InlineData( double.PositiveInfinity, unchecked((int)(0x7FFFFFFF)), double.PositiveInfinity, 0)] public static void ScaleB(double x, int n, double expectedResult, double allowedVariance) { AssertEqual(expectedResult, Math.ScaleB(x, n), allowedVariance); } public static IEnumerable<object[]> Round_Digits_TestData { get { yield return new object[] {0, 0, 3, MidpointRounding.ToEven}; yield return new object[] {3.42156, 3.422, 3, MidpointRounding.ToEven}; yield return new object[] {-3.42156, -3.422, 3, MidpointRounding.ToEven}; yield return new object[] {0, 0, 3, MidpointRounding.AwayFromZero}; yield return new object[] {3.42156, 3.422, 3, MidpointRounding.AwayFromZero}; yield return new object[] {-3.42156, -3.422, 3, MidpointRounding.AwayFromZero}; yield return new object[] {0, 0, 3, MidpointRounding.ToZero}; yield return new object[] {3.42156, 3.421, 3, MidpointRounding.ToZero}; yield return new object[] {-3.42156, -3.421, 3, MidpointRounding.ToZero}; yield return new object[] {0, 0, 3, MidpointRounding.ToNegativeInfinity}; yield return new object[] {3.42156, 3.421, 3, MidpointRounding.ToNegativeInfinity}; yield return new object[] {-3.42156, -3.422, 3, MidpointRounding.ToNegativeInfinity}; yield return new object[] {0, 0, 3, MidpointRounding.ToPositiveInfinity}; yield return new object[] {3.42156, 3.422, 3, MidpointRounding.ToPositiveInfinity}; yield return new object[] {-3.42156, -3.421, 3, MidpointRounding.ToPositiveInfinity}; } } [Theory] [InlineData(MidpointRounding.ToEven)] [InlineData(MidpointRounding.AwayFromZero)] [InlineData(MidpointRounding.ToZero)] [InlineData(MidpointRounding.ToNegativeInfinity)] [InlineData(MidpointRounding.ToPositiveInfinity)] public static void Round_Double_Digits(MidpointRounding mode) { Assert.Equal(double.NaN, Math.Round(double.NaN, 3, mode)); Assert.Equal(double.PositiveInfinity, Math.Round(double.PositiveInfinity, 3, mode)); Assert.Equal(double.NegativeInfinity, Math.Round(double.NegativeInfinity, 3, mode)); } [Theory] [MemberData(nameof(Round_Digits_TestData))] public static void Round_Double_Digits(double x, double expected, int digits, MidpointRounding mode) { Assert.Equal(expected, Math.Round(x, digits, mode)); } [Theory] [MemberData(nameof(Round_Digits_TestData))] public static void Round_Decimal_Digits(decimal x, decimal expected, int digits, MidpointRounding mode) { Assert.Equal(expected, Math.Round(x, digits, mode)); } [Theory] [InlineData(MidpointRounding.ToEven)] [InlineData(MidpointRounding.AwayFromZero)] [InlineData(MidpointRounding.ToZero)] [InlineData(MidpointRounding.ToNegativeInfinity)] [InlineData(MidpointRounding.ToPositiveInfinity)] public static void Round_Decimal_Digits(MidpointRounding mode) { Assert.Equal(decimal.Zero, Math.Round(decimal.Zero, 3, mode)); } public static IEnumerable<object[]> Round_Modes_TestData { get { yield return new object[] {11, 11, MidpointRounding.ToEven}; yield return new object[] {11.4, 11, MidpointRounding.ToEven}; yield return new object[] {11.5, 12, MidpointRounding.ToEven}; yield return new object[] {11.6, 12, MidpointRounding.ToEven}; yield return new object[] {-11, -11, MidpointRounding.ToEven}; yield return new object[] {-11.4, -11, MidpointRounding.ToEven}; yield return new object[] {-11.5, -12, MidpointRounding.ToEven}; yield return new object[] {-11.6, -12, MidpointRounding.ToEven}; yield return new object[] {11, 11, MidpointRounding.AwayFromZero}; yield return new object[] {11.4, 11, MidpointRounding.AwayFromZero}; yield return new object[] {11.5, 12, MidpointRounding.AwayFromZero}; yield return new object[] {11.6, 12, MidpointRounding.AwayFromZero}; yield return new object[] {-11, -11, MidpointRounding.AwayFromZero}; yield return new object[] {-11.4, -11, MidpointRounding.AwayFromZero}; yield return new object[] {-11.5, -12, MidpointRounding.AwayFromZero}; yield return new object[] {-11.6, -12, MidpointRounding.AwayFromZero}; yield return new object[] {11, 11, MidpointRounding.ToPositiveInfinity}; yield return new object[] {11.4, 12, MidpointRounding.ToPositiveInfinity}; yield return new object[] {11.5, 12, MidpointRounding.ToPositiveInfinity}; yield return new object[] {11.6, 12, MidpointRounding.ToPositiveInfinity}; yield return new object[] {-11, -11, MidpointRounding.ToPositiveInfinity}; yield return new object[] {-11.4, -11, MidpointRounding.ToPositiveInfinity}; yield return new object[] {-11.5, -11, MidpointRounding.ToPositiveInfinity}; yield return new object[] {-11.6, -11, MidpointRounding.ToPositiveInfinity}; yield return new object[] {11.0, 11, MidpointRounding.ToNegativeInfinity}; yield return new object[] {11.4, 11, MidpointRounding.ToNegativeInfinity}; yield return new object[] {11.5, 11, MidpointRounding.ToNegativeInfinity}; yield return new object[] {11.6, 11, MidpointRounding.ToNegativeInfinity}; yield return new object[] {-11.0, -11, MidpointRounding.ToNegativeInfinity}; yield return new object[] {-11.4, -12, MidpointRounding.ToNegativeInfinity}; yield return new object[] {-11.5, -12, MidpointRounding.ToNegativeInfinity}; yield return new object[] {-11.6, -12, MidpointRounding.ToNegativeInfinity}; yield return new object[] {11.0, 11, MidpointRounding.ToZero}; yield return new object[] {11.4, 11, MidpointRounding.ToZero}; yield return new object[] {11.5, 11, MidpointRounding.ToZero}; yield return new object[] {11.6, 11, MidpointRounding.ToZero}; yield return new object[] {-11.0, -11, MidpointRounding.ToZero}; yield return new object[] {-11.4, -11, MidpointRounding.ToZero}; yield return new object[] {-11.5, -11, MidpointRounding.ToZero}; yield return new object[] {-11.6, -11, MidpointRounding.ToZero}; } } [MemberData(nameof(Round_Modes_TestData))] public static void Round_Double_Modes(double x, double expected, MidpointRounding mode) { Assert.Equal(expected, Math.Round(x, 0, mode)); } [MemberData(nameof(Round_Modes_TestData))] public static void Round_Float_Modes(float x, float expected, MidpointRounding mode) { Assert.Equal(expected, MathF.Round(x, 0, mode)); } [MemberData(nameof(Round_Modes_TestData))] public static void Round_Decimal_Modes(decimal x, decimal expected, MidpointRounding mode) { Assert.Equal(expected, Math.Round(x, 0, mode)); Assert.Equal(expected, decimal.Round(x, 0, mode)); } } }
#region License // Copyright (c) Jeremy Skinner (http://www.jeremyskinner.co.uk) // // 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. // // The latest version of this file can be found at http://www.codeplex.com/FluentValidation #endregion namespace FluentValidation { using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Internal; using Resources; using Validators; /// <summary> /// Default options that can be used to configure a validator. /// </summary> public static class DefaultValidatorOptions { /// <summary> /// Specifies the cascade mode for failures. /// If set to 'Stop' then execution of the rule will stop once the first validator in the chain fails. /// If set to 'Continue' then all validators in the chain will execute regardless of failures. /// </summary> public static IRuleBuilderInitial<T, TProperty> Cascade<T, TProperty>(this IRuleBuilderInitial<T, TProperty> ruleBuilder, CascadeMode cascadeMode) { return ruleBuilder.Configure(cfg => { cfg.CascadeMode = cascadeMode; }); } /// <summary> /// Specifies a custom action to be invoked when the validator fails. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="onFailure"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OnAnyFailure<T, TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Action<T> onFailure) { return rule.Configure(config => { config.OnFailure = onFailure.CoerceToNonGeneric(); }); } /// <summary> /// Specifies a custom error message to use if validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="errorMessage">The error message to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage) { return rule.WithMessage(errorMessage, null as object[]); } /// <summary> /// Specifies a custom error message to use if validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="errorMessage">The error message to use</param> /// <param name="formatArgs">Additional arguments to be specified when formatting the custom error message.</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params object[] formatArgs) { var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs); return rule.WithMessage(errorMessage, funcs); } /// <summary> /// Specifies a custom error message to use if validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="errorMessage">The error message to use</param> /// <param name="funcs">Additional property values to be included when formatting the custom error message.</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params Func<T, object>[] funcs) { errorMessage.Guard("A message must be specified when calling WithMessage."); return rule.Configure(config => { config.CurrentValidator.ErrorMessageSource = new StaticStringSource(errorMessage); funcs .Select(func => new Func<object, object, object>((instance, value) => func((T)instance))) .ForEach(config.CurrentValidator.CustomMessageFormatArguments.Add); }); } /// <summary> /// Specifies a custom error message to use if validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="errorMessage">The error message to use</param> /// <param name="funcs">Additional property values to use when formatting the custom error message.</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string errorMessage, params Func<T, TProperty, object>[] funcs) { errorMessage.Guard("A message must be specified when calling WithMessage."); return rule.Configure(config => { config.CurrentValidator.ErrorMessageSource = new StaticStringSource(errorMessage); funcs .Select(func => new Func<object, object, object>((instance, value) => func((T)instance, (TProperty)value))) .ForEach(config.CurrentValidator.CustomMessageFormatArguments.Add); }); } /// <summary> /// Specifies a custom error message resource to use when validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param> /// <returns></returns> public static IRuleBuilderOptions<T,TProperty> WithLocalizedMessage<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector) { // We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType. return rule.WithLocalizedMessage(resourceSelector, new StaticResourceAccessorBuilder()); } /// <summary> /// Specifies a custom error message resource to use when validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param> /// <param name="formatArgs">Custom message format args</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<string>> resourceSelector, params object[] formatArgs) { var funcs = ConvertArrayOfObjectsToArrayOfDelegates<T>(formatArgs); return rule.WithLocalizedMessage(resourceSelector, funcs); } /// <summary> /// Specifies a custom error message resource to use when validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param> /// <param name="formatArgs">Custom message format args</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithLocalizedMessage<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Expression<Func<string>> resourceSelector, params Func<T, object>[] formatArgs) { // We use the StaticResourceAccessorBuilder here because we don't want calls to WithLocalizedMessage to be overriden by the ResourceProviderType. return rule.WithLocalizedMessage(resourceSelector, new StaticResourceAccessorBuilder()) .Configure(cfg => { formatArgs .Select(func => new Func<object, object, object>((instance, value) => func((T)instance))) .ForEach(cfg.CurrentValidator.CustomMessageFormatArguments.Add); }); } /// <summary> /// Specifies a custom error message resource to use when validation fails. /// </summary> /// <param name="rule">The current rule</param> /// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param> /// <param name="resourceAccessorBuilder">The resource accessor builder to use. </param> /// <returns></returns> public static IRuleBuilderOptions<T,TProperty> WithLocalizedMessage<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector, IResourceAccessorBuilder resourceAccessorBuilder) { resourceSelector.Guard("An expression must be specified when calling WithLocalizedMessage, eg .WithLocalizedMessage(() => Messages.MyResource)"); return rule.Configure(config => { config.CurrentValidator.ErrorMessageSource = LocalizedStringSource.CreateFromExpression(resourceSelector, resourceAccessorBuilder); }); } /// <summary> /// Specifies a condition limiting when the validator should run. /// The validator will only be executed if the result of the lambda returns true. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> When<T,TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling When."); // Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain. return rule.Configure(config => { config.ApplyCondition(predicate.CoerceToNonGeneric(), applyConditionTo); }); } /// <summary> /// Specifies a condition limiting when the validator should not run. /// The validator will only be executed if the result of the lambda returns false. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> Unless<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, bool> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling Unless"); return rule.When(x => !predicate(x), applyConditionTo); } /// <summary> /// Specifies an asynchronous condition limiting when the validator should run. /// The validator will only be executed if the result of the lambda returns true. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WhenAsync<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling WhenAsync."); // Default behaviour for When/Unless as of v1.3 is to apply the condition to all previous validators in the chain. return rule.Configure(config => { config.ApplyAsyncCondition(predicate.CoerceToNonGeneric(), applyConditionTo); }); } /// <summary> /// Specifies an asynchronous condition limiting when the validator should not run. /// The validator will only be executed if the result of the lambda returns false. /// </summary> /// <param name="rule">The current rule</param> /// <param name="predicate">A lambda expression that specifies a condition for when the validator should not run</param> /// <param name="applyConditionTo">Whether the condition should be applied to the current rule or all rules in the chain</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> UnlessAsync<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, Task<bool>> predicate, ApplyConditionTo applyConditionTo = ApplyConditionTo.AllValidators) { predicate.Guard("A predicate must be specified when calling UnlessAsync"); return rule.WhenAsync(x => predicate(x).Then(y => !y), applyConditionTo); } /// <summary> /// Triggers an action when the rule passes. Typically used to configure dependent rules. This applies to all preceding rules in the chain. /// </summary> /// <param name="rule">The current rule</param> /// <param name="action">An action to be invoked if the rule is valid</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> DependentRules<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Action<DependentRules<T>> action) { var dependencyContainer = new DependentRules<T>(); action(dependencyContainer); rule.Configure(cfg => { cfg.DependentRules.AddRange(dependencyContainer); }); return rule; } /// <summary> /// Specifies a custom property name to use within the error message. /// </summary> /// <param name="rule">The current rule</param> /// <param name="overridePropertyName">The property name to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string overridePropertyName) { overridePropertyName.Guard("A property name must be specified when calling WithName."); return rule.Configure(config => { config.DisplayName = new StaticStringSource(overridePropertyName); }); } /// <summary> /// Specifies a localized name for the error message. /// </summary> /// <param name="rule">The current rule</param> /// <param name="resourceSelector">The resource to use as an expression, eg () => Messages.MyResource</param> /// <param name="resourceAccessorBuilder">Resource accessor builder to use</param> public static IRuleBuilderOptions<T, TProperty> WithLocalizedName<T,TProperty>(this IRuleBuilderOptions<T,TProperty> rule, Expression<Func<string>> resourceSelector, IResourceAccessorBuilder resourceAccessorBuilder = null) { resourceSelector.Guard("A resource selector must be specified."); // default to the static resource accessor builder - explicit resources configured with WithLocalizedName should take precedence over ResourceProviderType. resourceAccessorBuilder = resourceAccessorBuilder ?? new StaticResourceAccessorBuilder(); return rule.Configure(config => { config.DisplayName = LocalizedStringSource.CreateFromExpression(resourceSelector, resourceAccessorBuilder); }); } /// <summary> /// Overrides the name of the property associated with this rule. /// NOTE: This is a considered to be an advanced feature. 99% of the time that you use this, you actually meant to use WithName. /// </summary> /// <param name="rule">The current rule</param> /// <param name="propertyName">The property name to use</param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> OverridePropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) { propertyName.Guard("A property name must be specified when calling WithNamePropertyName."); return rule.Configure(config => config.PropertyName = propertyName); } /// <summary> /// Overrides the name of the property associated with this rule. /// NOTE: This is a considered to be an advanced feature. 99% of the time that you use this, you actually meant to use WithName. /// </summary> /// <param name="rule">The current rule</param> /// <param name="propertyName">The property name to use</param> /// <returns></returns> [Obsolete("WithPropertyName has been deprecated. If you wish to set the name of the property within the error message, use 'WithName'. If you actually intended to change which property this rule was declared against, use 'OverridePropertyName' instead.")] public static IRuleBuilderOptions<T, TProperty> WithPropertyName<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, string propertyName) { return rule.OverridePropertyName(propertyName); } /// <summary> /// Specifies custom state that should be stored alongside the validation message when validation fails for this rule. /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="TProperty"></typeparam> /// <param name="rule"></param> /// <param name="stateProvider"></param> /// <returns></returns> public static IRuleBuilderOptions<T, TProperty> WithState<T, TProperty>(this IRuleBuilderOptions<T, TProperty> rule, Func<T, object> stateProvider) { stateProvider.Guard("A lambda expression must be passed to WithState"); return rule.Configure(config => config.CurrentValidator.CustomStateProvider = stateProvider.CoerceToNonGeneric()); } static Func<T, object>[] ConvertArrayOfObjectsToArrayOfDelegates<T>(object[] objects) { if(objects == null || objects.Length == 0) { return new Func<T, object>[0]; } return objects.Select(obj => new Func<T, object>(x => obj)).ToArray(); } } }
using System; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Threading; using NSec.Cryptography.Formatting; using static Interop.Libsodium; namespace NSec.Cryptography { // // HMAC-SHA-512 // // Hashed Message Authentication Code (HMAC) based on SHA-512 // // References: // // RFC 2104 - HMAC: Keyed-Hashing for Message Authentication // // RFC 6234 - US Secure Hash Algorithms (SHA and SHA-based HMAC and // HKDF) // // Parameters: // // Key Size - The key for HMAC-SHA-512 can be of any length. A length // less than L=64 bytes (the output length of SHA-512) is strongly // discouraged. (libsodium recommends a default size of // crypto_auth_hmacsha512_KEYBYTES=32 bytes.) Keys longer than L do // not significantly increase the function strength. // // MAC Size - 64 bytes. The output can be truncated to 16 bytes // (128 bits of security). To match the security of SHA-512, the // output length should not be less than half of L (i.e., not less // than 32 bytes). // public sealed class HmacSha512 : MacAlgorithm { public static readonly int MinKeySize = crypto_hash_sha512_BYTES; public static readonly int MaxKeySize = crypto_hash_sha512_BYTES; public static readonly int MinMacSize = 16; public static readonly int MaxMacSize = crypto_auth_hmacsha512_BYTES; private const uint NSecBlobHeader = 0xDE6347DE; private static int s_selfTest; public HmacSha512() : this( keySize: crypto_hash_sha512_BYTES, macSize: crypto_auth_hmacsha512_BYTES) { } public HmacSha512(int keySize, int macSize) : base( keySize: keySize, macSize: macSize) { if (keySize < MinKeySize || keySize > MaxKeySize) { throw Error.ArgumentOutOfRange_KeySize(nameof(keySize), keySize, MinKeySize, MaxKeySize); } if (macSize < MinMacSize || macSize > MaxMacSize) { throw Error.ArgumentOutOfRange_MacSize(nameof(macSize), macSize, MaxMacSize, MaxMacSize); } if (s_selfTest == 0) { SelfTest(); Interlocked.Exchange(ref s_selfTest, 1); } } internal override void CreateKey( ReadOnlySpan<byte> seed, out SecureMemoryHandle keyHandle, out PublicKey? publicKey) { publicKey = null; keyHandle = SecureMemoryHandle.CreateFrom(seed); } internal unsafe override void FinalizeCore( ref IncrementalMacState state, Span<byte> mac) { Debug.Assert(mac.Length <= crypto_auth_hmacsha512_BYTES); byte* temp = stackalloc byte[crypto_auth_hmacsha512_BYTES]; fixed (crypto_auth_hmacsha512_state* state_ = &state.hmacsha512) { int error = crypto_auth_hmacsha512_final( state_, temp); Debug.Assert(error == 0); } fixed (byte* @out = mac) { Unsafe.CopyBlockUnaligned(@out, temp, (uint)mac.Length); } } internal override int GetSeedSize() { return KeySize; } internal unsafe override void InitializeCore( SecureMemoryHandle keyHandle, out IncrementalMacState state) { Debug.Assert(keyHandle.Size == crypto_hash_sha512_BYTES); fixed (crypto_auth_hmacsha512_state* state_ = &state.hmacsha512) { int error = crypto_auth_hmacsha512_init( state_, keyHandle, (nuint)keyHandle.Size); Debug.Assert(error == 0); } } internal override bool TryExportKey( SecureMemoryHandle keyHandle, KeyBlobFormat format, Span<byte> blob, out int blobSize) { return format switch { KeyBlobFormat.RawSymmetricKey => RawKeyFormatter.TryExport(keyHandle, blob, out blobSize), KeyBlobFormat.NSecSymmetricKey => NSecKeyFormatter.TryExport(NSecBlobHeader, KeySize, MacSize, keyHandle, blob, out blobSize), _ => throw Error.Argument_FormatNotSupported(nameof(format), format.ToString()), }; } internal override bool TryImportKey( ReadOnlySpan<byte> blob, KeyBlobFormat format, out SecureMemoryHandle? keyHandle, out PublicKey? publicKey) { publicKey = null; return format switch { KeyBlobFormat.RawSymmetricKey => RawKeyFormatter.TryImport(KeySize, blob, out keyHandle), KeyBlobFormat.NSecSymmetricKey => NSecKeyFormatter.TryImport(NSecBlobHeader, KeySize, MacSize, blob, out keyHandle), _ => throw Error.Argument_FormatNotSupported(nameof(format), format.ToString()), }; } internal unsafe override void UpdateCore( ref IncrementalMacState state, ReadOnlySpan<byte> data) { fixed (crypto_auth_hmacsha512_state* state_ = &state.hmacsha512) fixed (byte* @in = data) { int error = crypto_auth_hmacsha512_update( state_, @in, (ulong)data.Length); Debug.Assert(error == 0); } } private protected unsafe override void MacCore( SecureMemoryHandle keyHandle, ReadOnlySpan<byte> data, Span<byte> mac) { Debug.Assert(keyHandle.Size == crypto_hash_sha512_BYTES); Debug.Assert(mac.Length <= crypto_auth_hmacsha512_BYTES); byte* temp = stackalloc byte[crypto_auth_hmacsha512_BYTES]; fixed (byte* @in = data) { crypto_auth_hmacsha512_state state; crypto_auth_hmacsha512_init( &state, keyHandle, (nuint)keyHandle.Size); crypto_auth_hmacsha512_update( &state, @in, (ulong)data.Length); crypto_auth_hmacsha512_final( &state, temp); } fixed (byte* @out = mac) { Unsafe.CopyBlockUnaligned(@out, temp, (uint)mac.Length); } } private static void SelfTest() { if ((crypto_auth_hmacsha512_bytes() != crypto_auth_hmacsha512_BYTES) || (crypto_auth_hmacsha512_keybytes() != crypto_auth_hmacsha512_KEYBYTES) || (crypto_auth_hmacsha512_statebytes() != (nuint)Unsafe.SizeOf<crypto_auth_hmacsha512_state>())) { throw Error.InvalidOperation_InitializationFailed(); } } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // SpscTargetCore.cs // // // A fast single-producer-single-consumer core for a target block. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Runtime.CompilerServices; using System.Security; namespace System.Threading.Tasks.Dataflow.Internal { // SpscTargetCore provides a fast target core for use in blocks that will only have single-producer-single-consumer // semantics. Blocks configured with the default DOP==1 will be single consumer, so whether this core may be // used is largely up to whether the block is also single-producer. The ExecutionDataflowBlockOptions.SingleProducerConstrained // option can be used by a developer to inform a block that it will only be accessed by one producer at a time, // and a block like ActionBlock can utilize that knowledge to choose this target instead of the default TargetCore. // However, there are further constraints that might prevent this core from being used. // - If the user specifies a CancellationToken, this core can't be used, as the cancellation request // could come in concurrently with the single producer accessing the block, thus resulting in multiple producers. // - If the user specifies a bounding capacity, this core can't be used, as the consumer processing items // needs to synchronize with producers around the change in bounding count, and the consumer is again // in effect another producer. // - If the block has a source half (e.g. TransformBlock) and that source could potentially call back // to the target half to, for example, notify it of exceptions occurring, again there would potentially // be multiple producers. // Thus, when and how this SpscTargetCore may be applied is significantly constrained. /// <summary> /// Provides a core implementation of <see cref="ITargetBlock{TInput}"/> for use when there's only a single producer posting data. /// </summary> /// <typeparam name="TInput">Specifies the type of data accepted by the <see cref="TargetCore{TInput}"/>.</typeparam> [DebuggerDisplay("{DebuggerDisplayContent,nq}")] internal sealed class SpscTargetCore<TInput> { /// <summary>The target block using this helper.</summary> private readonly ITargetBlock<TInput> _owningTarget; /// <summary>The messages in this target.</summary> private readonly SingleProducerSingleConsumerQueue<TInput> _messages = new SingleProducerSingleConsumerQueue<TInput>(); /// <summary>The options to use to configure this block. The target core assumes these options are immutable.</summary> private readonly ExecutionDataflowBlockOptions _dataflowBlockOptions; /// <summary>An action to invoke for every accepted message.</summary> private readonly Action<TInput> _action; /// <summary>Exceptions that may have occurred and gone unhandled during processing. This field is lazily initialized.</summary> private volatile List<Exception> _exceptions; /// <summary>Whether to stop accepting new messages.</summary> private volatile bool _decliningPermanently; /// <summary>A task has reserved the right to run the completion routine.</summary> private volatile bool _completionReserved; /// <summary> /// The Task currently active to process the block. This field is used to synchronize between producer and consumer, /// and it should not be set to null once the block completes, as doing so would allow for races where the producer /// gets another consumer task queued even though the block has completed. /// </summary> private volatile Task _activeConsumer; /// <summary>A task representing the completion of the block. This field is lazily initialized.</summary> private TaskCompletionSource<VoidResult> _completionTask; /// <summary>Initialize the SPSC target core.</summary> /// <param name="owningTarget">The owning target block.</param> /// <param name="action">The action to be invoked for every message.</param> /// <param name="dataflowBlockOptions">The options to use to configure this block. The target core assumes these options are immutable.</param> internal SpscTargetCore( ITargetBlock<TInput> owningTarget, Action<TInput> action, ExecutionDataflowBlockOptions dataflowBlockOptions) { Debug.Assert(owningTarget != null, "Expected non-null owningTarget"); Debug.Assert(action != null, "Expected non-null action"); Debug.Assert(dataflowBlockOptions != null, "Expected non-null dataflowBlockOptions"); _owningTarget = owningTarget; _action = action; _dataflowBlockOptions = dataflowBlockOptions; } internal bool Post(TInput messageValue) { if (_decliningPermanently) return false; // Store the offered message into the queue. _messages.Enqueue(messageValue); Interlocked.MemoryBarrier(); // ensure the read of _activeConsumer doesn't move up before the writes in Enqueue // Make sure there's an active task available to handle processing this message. If we find the task // is null, we'll try to schedule one using an interlocked operation. If we find the task is non-null, // then there must be a task actively running. If there's a race where the task is about to complete // and nulls out its reference (using a barrier), it'll subsequently check whether there are any messages in the queue, // and since we put the messages into the queue before now, it'll find them and use an interlocked // to re-launch itself. if (_activeConsumer == null) { ScheduleConsumerIfNecessary(false); } return true; } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Targets/Member[@name="OfferMessage"]/*' /> internal DataflowMessageStatus OfferMessage(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept) { // If we're not required to go back to the source to consume the offered message, try fast path. return !consumeToAccept && Post(messageValue) ? DataflowMessageStatus.Accepted : OfferMessage_Slow(messageHeader, messageValue, source, consumeToAccept); } /// <summary>Implements the slow path for OfferMessage.</summary> /// <param name="messageHeader">The message header for the offered value.</param> /// <param name="messageValue">The offered value.</param> /// <param name="source">The source offering the message. This may be null.</param> /// <param name="consumeToAccept">true if we need to call back to the source to consume the message; otherwise, false if we can simply accept it directly.</param> /// <returns>The status of the message.</returns> private DataflowMessageStatus OfferMessage_Slow(DataflowMessageHeader messageHeader, TInput messageValue, ISourceBlock<TInput> source, bool consumeToAccept) { // If we're declining permanently, let the caller know. if (_decliningPermanently) { return DataflowMessageStatus.DecliningPermanently; } // If the message header is invalid, throw. if (!messageHeader.IsValid) { throw new ArgumentException(SR.Argument_InvalidMessageHeader, nameof(messageHeader)); } // If the caller has requested we consume the message using ConsumeMessage, do so. if (consumeToAccept) { if (source == null) throw new ArgumentException(SR.Argument_CantConsumeFromANullSource, nameof(consumeToAccept)); bool consumed; messageValue = source.ConsumeMessage(messageHeader, _owningTarget, out consumed); if (!consumed) return DataflowMessageStatus.NotAvailable; } // See the "fast path" comments in Post _messages.Enqueue(messageValue); Interlocked.MemoryBarrier(); // ensure the read of _activeConsumer doesn't move up before the writes in Enqueue if (_activeConsumer == null) { ScheduleConsumerIfNecessary(isReplica: false); } return DataflowMessageStatus.Accepted; } /// <summary>Schedules a consumer task if there's none currently running.</summary> /// <param name="isReplica">Whether the new consumer is being scheduled to replace a currently running consumer.</param> [SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope")] private void ScheduleConsumerIfNecessary(bool isReplica) { // If there's currently no active task... if (_activeConsumer == null) { // Create a new consumption task and try to set it as current as long as there's still no other task var newConsumer = new Task( state => ((SpscTargetCore<TInput>)state).ProcessMessagesLoopCore(), this, CancellationToken.None, Common.GetCreationOptionsForTask(isReplica)); if (Interlocked.CompareExchange(ref _activeConsumer, newConsumer, null) == null) { // We won the race. This task is now the consumer. #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.TaskLaunchedForMessageHandling( _owningTarget, newConsumer, DataflowEtwProvider.TaskLaunchedReason.ProcessingInputMessages, _messages.Count); } #endif // Start the task. In the erroneous case where the scheduler throws an exception, // just allow it to propagate. Our other option would be to fault the block with // that exception, but in order for the block to complete we need to schedule a consumer // task to do so, and it's very likely that if the scheduler is throwing an exception // now, it would do so again. newConsumer.Start(_dataflowBlockOptions.TaskScheduler); } } } /// <summary>Task body used to process messages.</summary> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")] private void ProcessMessagesLoopCore() { Debug.Assert( _activeConsumer != null && _activeConsumer.Id == Task.CurrentId, "This method should only be called when it's the active consumer."); int messagesProcessed = 0; int maxMessagesToProcess = _dataflowBlockOptions.ActualMaxMessagesPerTask; // Continue processing as long as there's more processing to be done bool continueProcessing = true; while (continueProcessing) { continueProcessing = false; TInput nextMessage = default(TInput); try { // While there are more messages to be processed, process each one. // NOTE: This loop is critical for performance. It must be super lean. while ( _exceptions == null && messagesProcessed < maxMessagesToProcess && _messages.TryDequeue(out nextMessage)) { messagesProcessed++; // done before _action invoked in case it throws exception _action(nextMessage); } } catch (Exception exc) { // If the exception is for cancellation, just ignore it. // Otherwise, store it, and the finally block will handle completion. if (!Common.IsCooperativeCancellation(exc)) { _decliningPermanently = true; // stop accepting from producers Common.StoreDataflowMessageValueIntoExceptionData<TInput>(exc, nextMessage, false); StoreException(exc); } } finally { // If more messages just arrived and we should still process them, // loop back around and keep going. if (!_messages.IsEmpty && _exceptions == null && (messagesProcessed < maxMessagesToProcess)) { continueProcessing = true; } else { // If messages are being declined and we're empty, or if there's an exception, // then there's no more work to be done and we should complete the block. bool wasDecliningPermanently = _decliningPermanently; if ((wasDecliningPermanently && _messages.IsEmpty) || _exceptions != null) { // Complete the block, as long as we're not already completing or completed. if (!_completionReserved) // no synchronization necessary; this can't happen concurrently { _completionReserved = true; CompleteBlockOncePossible(); } } else { // Mark that we're exiting. Task previousConsumer = Interlocked.Exchange(ref _activeConsumer, null); Debug.Assert(previousConsumer != null && previousConsumer.Id == Task.CurrentId, "The running task should have been denoted as the active task."); // Now that we're no longer the active task, double // check to make sure there's really nothing to do, // which could include processing more messages or completing. // If there is more to do, schedule a task to try to do it. // This is to handle a race with Post/Complete/Fault and this // task completing. if (!_messages.IsEmpty || // messages to be processed (!wasDecliningPermanently && _decliningPermanently) || // potentially completion to be processed _exceptions != null) // exceptions/completion to be processed { ScheduleConsumerIfNecessary(isReplica: true); } } } } } } /// <summary>Gets the number of messages waiting to be processed.</summary> internal int InputCount { get { return _messages.Count; } } /// <summary> /// Completes the target core. If an exception is provided, the block will end up in a faulted state. /// If Complete is invoked more than once, or if it's invoked after the block is already /// completing, all invocations after the first are ignored. /// </summary> /// <param name="exception">The exception to be stored.</param> internal void Complete(Exception exception) { // If we're not yet declining permanently... if (!_decliningPermanently) { // Mark us as declining permanently, and then kick off a processing task // if we need one. It's this processing task's job to complete the block // once all data has been consumed and/or we're in a valid state for completion. if (exception != null) StoreException(exception); _decliningPermanently = true; ScheduleConsumerIfNecessary(isReplica: false); } } /// <summary> /// Ensures the exceptions list is initialized and stores the exception into the list using a lock. /// </summary> /// <param name="exception">The exception to store.</param> private void StoreException(Exception exception) { // Ensure that the _exceptions field has been initialized. // We need to synchronize the initialization and storing of // the exception because this method could be accessed concurrently // by the producer and consumer, a producer calling Fault and the // processing task processing the user delegate which might throw. #pragma warning disable 0420 lock (LazyInitializer.EnsureInitialized(ref _exceptions, () => new List<Exception>())) #pragma warning restore 0420 { _exceptions.Add(exception); } } /// <summary> /// Completes the block. This must only be called once, and only once all of the completion conditions are met. /// </summary> private void CompleteBlockOncePossible() { Debug.Assert(_completionReserved, "Should only invoke once completion has been reserved."); // Dump any messages that might remain in the queue, which could happen if we completed due to exceptions. TInput dumpedMessage; while (_messages.TryDequeue(out dumpedMessage)) ; // Complete the completion task bool result; if (_exceptions != null) { Exception[] exceptions; lock (_exceptions) exceptions = _exceptions.ToArray(); result = CompletionSource.TrySetException(exceptions); } else { result = CompletionSource.TrySetResult(default(VoidResult)); } Debug.Assert(result, "Expected completion task to not yet be completed"); // We explicitly do not set the _activeTask to null here, as that would // allow for races where a producer calling OfferMessage could end up // seeing _activeTask as null and queueing a new consumer task even // though the block has completed. #if FEATURE_TRACING DataflowEtwProvider etwLog = DataflowEtwProvider.Log; if (etwLog.IsEnabled()) { etwLog.DataflowBlockCompleted(_owningTarget); } #endif } /// <include file='XmlDocs/CommonXmlDocComments.xml' path='CommonXmlDocComments/Blocks/Member[@name="Completion"]/*' /> internal Task Completion { get { return CompletionSource.Task; } } /// <summary>Gets the lazily-initialized completion source.</summary> private TaskCompletionSource<VoidResult> CompletionSource { get { return LazyInitializer.EnsureInitialized(ref _completionTask, () => new TaskCompletionSource<VoidResult>()); } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _dataflowBlockOptions; } } /// <summary>Gets information about this helper to be used for display in a debugger.</summary> /// <returns>Debugging information about this target.</returns> internal DebuggingInformation GetDebuggingInformation() { return new DebuggingInformation(this); } /// <summary>Gets the object to display in the debugger display attribute.</summary> [SuppressMessage("Microsoft.Globalization", "CA1305:SpecifyIFormatProvider")] private object DebuggerDisplayContent { get { var displayTarget = _owningTarget as IDebuggerDisplay; return string.Format("Block=\"{0}\"", displayTarget != null ? displayTarget.Content : _owningTarget); } } /// <summary>Provides a wrapper for commonly needed debugging information.</summary> internal sealed class DebuggingInformation { /// <summary>The target being viewed.</summary> private readonly SpscTargetCore<TInput> _target; /// <summary>Initializes the debugging helper.</summary> /// <param name="target">The target being viewed.</param> internal DebuggingInformation(SpscTargetCore<TInput> target) { _target = target; } /// <summary>Gets the messages waiting to be processed.</summary> internal IEnumerable<TInput> InputQueue { get { return _target._messages.ToList(); } } /// <summary>Gets the current number of outstanding input processing operations.</summary> internal int CurrentDegreeOfParallelism { get { return _target._activeConsumer != null && !_target.Completion.IsCompleted ? 1 : 0; } } /// <summary>Gets the DataflowBlockOptions used to configure this block.</summary> internal ExecutionDataflowBlockOptions DataflowBlockOptions { get { return _target._dataflowBlockOptions; } } /// <summary>Gets whether the block is declining further messages.</summary> internal bool IsDecliningPermanently { get { return _target._decliningPermanently; } } /// <summary>Gets whether the block is completed.</summary> internal bool IsCompleted { get { return _target.Completion.IsCompleted; } } } } }
// 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. #if !NET_NATIVE namespace System.Xml.Serialization { using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; using System.Xml.Extensions; internal class XmlSerializationILGen { private int _nextMethodNumber = 0; private readonly Dictionary<TypeMapping, string> _methodNames = new Dictionary<TypeMapping, string>(); // Lookup name->created Method private Dictionary<string, MethodBuilderInfo> _methodBuilders = new Dictionary<string, MethodBuilderInfo>(); // Lookup name->created Type internal Dictionary<string, Type> CreatedTypes = new Dictionary<string, Type>(); // Lookup name->class Member internal Dictionary<string, MemberInfo> memberInfos = new Dictionary<string, MemberInfo>(); private ReflectionAwareILGen _raCodeGen; private TypeScope[] _scopes; private TypeDesc _stringTypeDesc = null; private TypeDesc _qnameTypeDesc = null; private string _className; private TypeMapping[] _referencedMethods; private int _references = 0; private readonly HashSet<TypeMapping> _generatedMethods = new HashSet<TypeMapping>(); private ModuleBuilder _moduleBuilder; private TypeAttributes _typeAttributes; protected TypeBuilder typeBuilder; protected CodeGenerator ilg; internal XmlSerializationILGen(TypeScope[] scopes, string access, string className) { _scopes = scopes; if (scopes.Length > 0) { _stringTypeDesc = scopes[0].GetTypeDesc(typeof(string)); _qnameTypeDesc = scopes[0].GetTypeDesc(typeof(XmlQualifiedName)); } _raCodeGen = new ReflectionAwareILGen(); _className = className; System.Diagnostics.Debug.Assert(access == "public"); _typeAttributes = TypeAttributes.Public; } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } } internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Dictionary<TypeMapping, string> MethodNames { get { return _methodNames; } } internal HashSet<TypeMapping> GeneratedMethods { get { return _generatedMethods; } } internal ModuleBuilder ModuleBuilder { get { System.Diagnostics.Debug.Assert(_moduleBuilder != null); return _moduleBuilder; } set { System.Diagnostics.Debug.Assert(_moduleBuilder == null && value != null); _moduleBuilder = value; } } internal TypeAttributes TypeAttributes { get { return _typeAttributes; } } private static Dictionary<string, Regex> s_regexs = new Dictionary<string, Regex>(); static internal Regex NewRegex(string pattern) { Regex regex; lock (s_regexs) { if (!s_regexs.TryGetValue(pattern, out regex)) { regex = new Regex(pattern); s_regexs.Add(pattern, regex); } } return regex; } internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName, MethodAttributes attributes, Type returnType, Type[] parameterTypes) { MethodBuilderInfo methodBuilderInfo; if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo)) { MethodBuilder methodBuilder = typeBuilder.DefineMethod( methodName, attributes, returnType, parameterTypes); methodBuilderInfo = new MethodBuilderInfo(methodBuilder, parameterTypes); _methodBuilders.Add(methodName, methodBuilderInfo); } #if DEBUG else { methodBuilderInfo.Validate(returnType, parameterTypes, attributes); } #endif return methodBuilderInfo.MethodBuilder; } internal MethodBuilderInfo GetMethodBuilder(string methodName) { System.Diagnostics.Debug.Assert(_methodBuilders.ContainsKey(methodName)); return _methodBuilders[methodName]; } internal virtual void GenerateMethod(TypeMapping mapping) { } internal void GenerateReferencedMethods() { while (_references > 0) { TypeMapping mapping = _referencedMethods[--_references]; GenerateMethod(mapping); } } internal string ReferenceMapping(TypeMapping mapping) { if (!_generatedMethods.Contains(mapping)) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } string methodName; _methodNames.TryGetValue(mapping, out methodName); return methodName; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; TypeMapping[] b = new TypeMapping[a.Length + 32]; Array.Copy(a, 0, b, 0, index); return b; } internal string GetCSharpString(string value) { return ReflectionAwareILGen.GetCSharpString(value); } internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publicName, TypeBuilder serializerContractTypeBuilder) { FieldBuilder fieldBuilder = serializerContractTypeBuilder.DefineField( privateName, typeof(Hashtable), FieldAttributes.Private ); ilg = new CodeGenerator(serializerContractTypeBuilder); PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty( publicName, PropertyAttributes.None, CallingConventions.HasThis, typeof(Hashtable), null, null, null, null, null); ilg.BeginMethod( typeof(Hashtable), "get_" + publicName, Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); // this 'if' ends in GenerateHashtableGetEnd ilg.If(Cmp.EqualTo); ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp"); ilg.New(Hashtable_ctor); ilg.Stloc(_tmpLoc); return fieldBuilder; } internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder) { ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); { ilg.Ldarg(0); ilg.Ldloc(typeof(Hashtable), "_tmp"); ilg.StoreMember(fieldBuilder); } ilg.EndIf(); // 'endif' from GenerateHashtableGetBegin ilg.EndIf(); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.GotoMethodEnd(); ilg.EndMethod(); } internal FieldBuilder GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder) { FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, publicName, serializerContractTypeBuilder); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) { MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod( "set_Item", new Type[] { typeof(Object), typeof(Object) } ); for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; ilg.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(xmlMappings[i].Key)); ilg.Ldstr(GetCSharpString(methods[i])); ilg.Call(Hashtable_set_Item); } } GenerateHashtableGetEnd(fieldBuilder); return fieldBuilder; } internal void GenerateSupportedTypes(Type[] types, TypeBuilder serializerContractTypeBuilder) { ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(bool), "CanSerialize", new Type[] { typeof(Type) }, new string[] { "type" }, CodeGenerator.PublicOverrideMethodAttributes); var uniqueTypes = new HashSet<Type>(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type == null) continue; if (!type.GetTypeInfo().IsPublic && !type.GetTypeInfo().IsNestedPublic) continue; if (!uniqueTypes.Add(type)) continue; // DDB172141: Wrong generated CS for serializer of List<string> type if (type.GetTypeInfo().IsGenericType || type.GetTypeInfo().ContainsGenericParameters) continue; ilg.Ldarg("type"); ilg.Ldc(type); ilg.If(Cmp.EqualTo); { ilg.Ldc(true); ilg.GotoMethodEnd(); } ilg.EndIf(); } ilg.Ldc(false); ilg.GotoMethodEnd(); ilg.EndMethod(); } internal string GenerateBaseSerializer(string baseSerializer, string readerClass, string writerClass, CodeIdentifiers classes) { baseSerializer = CodeIdentifier.MakeValid(baseSerializer); baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder, CodeIdentifier.GetCSharpName(baseSerializer), TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit, typeof(XmlSerializer), Array.Empty<Type>()); ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg = new CodeGenerator(baseSerializerTypeBuilder); ilg.BeginMethod(typeof(XmlSerializationReader), "CreateReader", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(readerCtor); ilg.EndMethod(); ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.BeginMethod(typeof(XmlSerializationWriter), "CreateWriter", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.ProtectedOverrideMethodAttributes); ilg.New(writerCtor); ilg.EndMethod(); baseSerializerTypeBuilder.DefineDefaultConstructor( MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType(); CreatedTypes.Add(baseSerializerType.Name, baseSerializerType); return baseSerializer; } internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder, CodeIdentifier.GetCSharpName(serializerName), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, CreatedTypes[baseSerializer], Array.Empty<Type>() ); ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(Boolean), "CanDeserialize", new Type[] { typeof(XmlReader) }, new string[] { "xmlReader" }, CodeGenerator.PublicOverrideMethodAttributes ); if (mapping.Accessor.Any) { ilg.Ldc(true); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } else { MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(String), typeof(String) } ); ilg.Ldarg(ilg.GetArg("xmlReader")); ilg.Ldstr(GetCSharpString(mapping.Accessor.Name)); ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace)); ilg.Call(XmlReader_IsStartElement); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); if (writeMethod != null) { ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(void), "Serialize", new Type[] { typeof(object), typeof(XmlSerializationWriter) }, new string[] { "objectToSerialize", "writer" }, CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo writerType_writeMethod = CreatedTypes[writerClass].GetMethod( writeMethod, CodeGenerator.InstanceBindingFlags, new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) } ); ilg.Ldarg("writer"); ilg.Castclass(CreatedTypes[writerClass]); ilg.Ldarg("objectToSerialize"); if (mapping is XmlMembersMapping) { ilg.ConvertValue(typeof(object), typeof(object[])); } ilg.Call(writerType_writeMethod); ilg.EndMethod(); } if (readMethod != null) { ilg = new CodeGenerator(typedSerializerTypeBuilder); ilg.BeginMethod( typeof(object), "Deserialize", new Type[] { typeof(XmlSerializationReader) }, new string[] { "reader" }, CodeGenerator.ProtectedOverrideMethodAttributes); MethodInfo readerType_readMethod = CreatedTypes[readerClass].GetMethod( readMethod, CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.Ldarg("reader"); ilg.Castclass(CreatedTypes[readerClass]); ilg.Call(readerType_readMethod); ilg.EndMethod(); } typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes); Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType(); CreatedTypes.Add(typedSerializerType.Name, typedSerializerType); return typedSerializerType.Name; } private FieldBuilder GenerateTypedSerializers(Dictionary<string, string> serializers, TypeBuilder serializerContractTypeBuilder) { string privateName = "typedSerializers"; FieldBuilder fieldBuilder = GenerateHashtableGetBegin(privateName, "TypedSerializers", serializerContractTypeBuilder); MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Object), typeof(Object) } ); foreach (string key in serializers.Keys) { ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(key)); ilg.New(ctor); ilg.Call(Hashtable_Add); } GenerateHashtableGetEnd(fieldBuilder); return fieldBuilder; } //GenerateGetSerializer(serializers, xmlMappings); private void GenerateGetSerializer(Dictionary<string, string> serializers, XmlMapping[] xmlMappings, TypeBuilder serializerContractTypeBuilder) { ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(XmlSerializer), "GetSerializer", new Type[] { typeof(Type) }, new string[] { "type" }, CodeGenerator.PublicOverrideMethodAttributes); for (int i = 0; i < xmlMappings.Length; i++) { if (xmlMappings[i] is XmlTypeMapping) { Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; if (type == null) continue; if (!type.GetTypeInfo().IsPublic && !type.GetTypeInfo().IsNestedPublic) continue; // DDB172141: Wrong generated CS for serializer of List<string> type if (type.GetTypeInfo().IsGenericType || type.GetTypeInfo().ContainsGenericParameters) continue; ilg.Ldarg("type"); ilg.Ldc(type); ilg.If(Cmp.EqualTo); { ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.New(ctor); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); } ilg.EndIf(); } } ilg.Load(null); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); ilg.MarkLabel(ilg.ReturnLabel); ilg.Ldloc(ilg.ReturnLocal); ilg.EndMethod(); } internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary<string, string> serializers) { TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder( _moduleBuilder, "XmlSerializerContract", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(XmlSerializerImplementation), Array.Empty<Type>() ); ilg = new CodeGenerator(serializerContractTypeBuilder); PropertyBuilder propertyBuilder = serializerContractTypeBuilder.DefineProperty( "Reader", PropertyAttributes.None, typeof(XmlSerializationReader), null, null, null, null, null); ilg.BeginMethod( typeof(XmlSerializationReader), "get_Reader", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder); ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.New(ctor); ilg.EndMethod(); ilg = new CodeGenerator(serializerContractTypeBuilder); propertyBuilder = serializerContractTypeBuilder.DefineProperty( "Writer", PropertyAttributes.None, typeof(XmlSerializationWriter), null, null, null, null, null); ilg.BeginMethod( typeof(XmlSerializationWriter), "get_Writer", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); propertyBuilder.SetGetMethod(ilg.MethodBuilder); ctor = CreatedTypes[writerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg.New(ctor); ilg.EndMethod(); FieldBuilder readMethodsField = GeneratePublicMethods("readMethods", "ReadMethods", readMethods, xmlMappings, serializerContractTypeBuilder); FieldBuilder writeMethodsField = GeneratePublicMethods("writeMethods", "WriteMethods", writerMethods, xmlMappings, serializerContractTypeBuilder); FieldBuilder typedSerializersField = GenerateTypedSerializers(serializers, serializerContractTypeBuilder); GenerateSupportedTypes(types, serializerContractTypeBuilder); GenerateGetSerializer(serializers, xmlMappings, serializerContractTypeBuilder); // Default ctor ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty<Type>() ); ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(void), ".ctor", Array.Empty<Type>(), Array.Empty<string>(), CodeGenerator.PublicMethodAttributes | MethodAttributes.RTSpecialName | MethodAttributes.SpecialName ); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(readMethodsField); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(writeMethodsField); ilg.Ldarg(0); ilg.Load(null); ilg.StoreMember(typedSerializersField); ilg.Ldarg(0); ilg.Call(baseCtor); ilg.EndMethod(); // Instantiate type Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo().AsType(); CreatedTypes.Add(serializerContractType.Name, serializerContractType); } internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; return mapping.TypeDesc.CanBeElementValue; } internal void ILGenLoad(string source) { ILGenLoad(source, null); } internal void ILGenLoad(string source, Type type) { if (source.StartsWith("o.@", StringComparison.Ordinal)) { System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; ilg.LoadMember(ilg.GetVariable("o"), memInfo); if (type != null) { Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType; ilg.ConvertValue(memType, type); } } else { SourceInfo info = new SourceInfo(source, null, null, null, ilg); info.Load(type); } } } } #endif
using System; using System.Data; using System.Data.Common; using System.Data.Entity.Core.EntityClient; using System.Data.Entity.Core.Objects; using System.Linq; using System.Linq.Dynamic; using System.Linq.Expressions; using System.Text; using System.Text.RegularExpressions; using EntityFramework.Extensions; using EntityFramework.Mapping; using EntityFramework.Reflection; namespace EntityFramework.Batch { /// <summary> /// A batch execution runner for SQL Server. /// </summary> public class SqlServerBatchRunner : IBatchRunner { /// <summary> /// Create and run a batch delete statement. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param> /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param> /// <param name="query">The query to create the where clause from.</param> /// <returns> /// The number of rows deleted. /// </returns> public int Delete<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query) where TEntity : class { DbConnection deleteConnection = null; DbTransaction deleteTransaction = null; DbCommand deleteCommand = null; bool ownConnection = false; bool ownTransaction = false; try { // get store connection and transaction var store = GetStore(objectContext); deleteConnection = store.Item1; deleteTransaction = store.Item2; if (deleteConnection.State != ConnectionState.Open) { deleteConnection.Open(); ownConnection = true; } if (deleteTransaction == null) { deleteTransaction = deleteConnection.BeginTransaction(); ownTransaction = true; } deleteCommand = deleteConnection.CreateCommand(); deleteCommand.Transaction = deleteTransaction; if (objectContext.CommandTimeout.HasValue) deleteCommand.CommandTimeout = objectContext.CommandTimeout.Value; var innerSelect = GetSelectSql(query, entityMap, deleteCommand); var sqlBuilder = new StringBuilder(innerSelect.Length * 2); sqlBuilder.Append("DELETE "); sqlBuilder.Append(entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendLine(innerSelect); sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false; foreach (var keyMap in entityMap.KeyMaps) { if (wroteKey) sqlBuilder.Append(" AND "); sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName); wroteKey = true; } sqlBuilder.Append(")"); deleteCommand.CommandText = sqlBuilder.ToString(); int result = deleteCommand.ExecuteNonQuery(); // only commit if created transaction if (ownTransaction) deleteTransaction.Commit(); return result; } finally { if (deleteCommand != null) deleteCommand.Dispose(); if (deleteTransaction != null && ownTransaction) deleteTransaction.Dispose(); if (deleteConnection != null && ownConnection) deleteConnection.Close(); } } /// <summary> /// Create and run a batch update statement. /// </summary> /// <typeparam name="TEntity">The type of the entity.</typeparam> /// <param name="objectContext">The <see cref="ObjectContext"/> to get connection and metadata information from.</param> /// <param name="entityMap">The <see cref="EntityMap"/> for <typeparamref name="TEntity"/>.</param> /// <param name="query">The query to create the where clause from.</param> /// <param name="updateExpression">The update expression.</param> /// <returns> /// The number of rows updated. /// </returns> public int Update<TEntity>(ObjectContext objectContext, EntityMap entityMap, ObjectQuery<TEntity> query, Expression<Func<TEntity, TEntity>> updateExpression) where TEntity : class { DbConnection updateConnection = null; DbTransaction updateTransaction = null; DbCommand updateCommand = null; bool ownConnection = false; bool ownTransaction = false; try { // get store connection and transaction var store = GetStore(objectContext); updateConnection = store.Item1; updateTransaction = store.Item2; if (updateConnection.State != ConnectionState.Open) { updateConnection.Open(); ownConnection = true; } // use existing transaction or create new if (updateTransaction == null) { updateTransaction = updateConnection.BeginTransaction(); ownTransaction = true; } updateCommand = updateConnection.CreateCommand(); updateCommand.Transaction = updateTransaction; if (objectContext.CommandTimeout.HasValue) updateCommand.CommandTimeout = objectContext.CommandTimeout.Value; var innerSelect = GetSelectSql(query, entityMap, updateCommand); var sqlBuilder = new StringBuilder(innerSelect.Length * 2); sqlBuilder.Append("UPDATE "); sqlBuilder.Append(entityMap.TableName); sqlBuilder.AppendLine(" SET "); var memberInitExpression = updateExpression.Body as MemberInitExpression; if (memberInitExpression == null) throw new ArgumentException("The update expression must be of type MemberInitExpression.", "updateExpression"); int nameCount = 0; bool wroteSet = false; foreach (MemberBinding binding in memberInitExpression.Bindings) { if (wroteSet) sqlBuilder.AppendLine(", "); string propertyName = binding.Member.Name; string columnName = entityMap.PropertyMaps .Where(p => p.PropertyName == propertyName) .Select(p => p.ColumnName) .FirstOrDefault(); var memberAssignment = binding as MemberAssignment; if (memberAssignment == null) throw new ArgumentException("The update expression MemberBinding must only by type MemberAssignment.", "updateExpression"); Expression memberExpression = memberAssignment.Expression; ParameterExpression parameterExpression = null; memberExpression.Visit((ParameterExpression p) => { if (p.Type == entityMap.EntityType) parameterExpression = p; return p; }); if (parameterExpression == null) { object value; if (memberExpression.NodeType == ExpressionType.Constant) { var constantExpression = memberExpression as ConstantExpression; if (constantExpression == null) throw new ArgumentException( "The MemberAssignment expression is not a ConstantExpression.", "updateExpression"); value = constantExpression.Value; } else { LambdaExpression lambda = Expression.Lambda(memberExpression, null); value = lambda.Compile().DynamicInvoke(); } if (value != null) { string parameterName = "p__update__" + nameCount++; var parameter = updateCommand.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = value; updateCommand.Parameters.Add(parameter); sqlBuilder.AppendFormat("[{0}] = @{1}", columnName, parameterName); } else { sqlBuilder.AppendFormat("[{0}] = NULL", columnName); } } else { // create clean objectset to build query from var objectSet = objectContext.CreateObjectSet<TEntity>(); Type[] typeArguments = new[] { entityMap.EntityType, memberExpression.Type }; ConstantExpression constantExpression = Expression.Constant(objectSet); LambdaExpression lambdaExpression = Expression.Lambda(memberExpression, parameterExpression); MethodCallExpression selectExpression = Expression.Call( typeof(Queryable), "Select", typeArguments, constantExpression, lambdaExpression); // create query from expression var selectQuery = objectSet.CreateQuery(selectExpression, entityMap.EntityType); string sql = selectQuery.ToTraceString(); // parse select part of sql to use as update string regex = @"SELECT\s*\r\n(?<ColumnValue>.+)?\s*AS\s*(?<ColumnAlias>\[\w+\])\r\nFROM\s*(?<TableName>\[\w+\]\.\[\w+\]|\[\w+\])\s*AS\s*(?<TableAlias>\[\w+\])"; Match match = Regex.Match(sql, regex); if (!match.Success) throw new ArgumentException("The MemberAssignment expression could not be processed.", "updateExpression"); string value = match.Groups["ColumnValue"].Value; string alias = match.Groups["TableAlias"].Value; value = value.Replace(alias + ".", ""); foreach (ObjectParameter objectParameter in selectQuery.Parameters) { string parameterName = "p__update__" + nameCount++; var parameter = updateCommand.CreateParameter(); parameter.ParameterName = parameterName; parameter.Value = objectParameter.Value; updateCommand.Parameters.Add(parameter); value = value.Replace(objectParameter.Name, parameterName); } sqlBuilder.AppendFormat("[{0}] = {1}", columnName, value); } wroteSet = true; } sqlBuilder.AppendLine(" "); sqlBuilder.AppendFormat("FROM {0} AS j0 INNER JOIN (", entityMap.TableName); sqlBuilder.AppendLine(); sqlBuilder.AppendLine(innerSelect); sqlBuilder.Append(") AS j1 ON ("); bool wroteKey = false; foreach (var keyMap in entityMap.KeyMaps) { if (wroteKey) sqlBuilder.Append(" AND "); sqlBuilder.AppendFormat("j0.[{0}] = j1.[{0}]", keyMap.ColumnName); wroteKey = true; } sqlBuilder.Append(")"); updateCommand.CommandText = sqlBuilder.ToString(); int result = updateCommand.ExecuteNonQuery(); // only commit if created transaction if (ownTransaction) updateTransaction.Commit(); return result; } finally { if (updateCommand != null) updateCommand.Dispose(); if (updateTransaction != null && ownTransaction) updateTransaction.Dispose(); if (updateConnection != null && ownConnection) updateConnection.Close(); } } private static Tuple<DbConnection, DbTransaction> GetStore(ObjectContext objectContext) { DbConnection dbConnection = objectContext.Connection; var entityConnection = dbConnection as EntityConnection; // by-pass entity connection if (entityConnection == null) return new Tuple<DbConnection, DbTransaction>(dbConnection, null); DbConnection connection = entityConnection.StoreConnection; // get internal transaction dynamic connectionProxy = new DynamicProxy(entityConnection); dynamic entityTransaction = connectionProxy.CurrentTransaction; if (entityTransaction == null) return new Tuple<DbConnection, DbTransaction>(connection, null); DbTransaction transaction = entityTransaction.StoreTransaction; return new Tuple<DbConnection, DbTransaction>(connection, transaction); } private static string GetSelectSql<TEntity>(ObjectQuery<TEntity> query, EntityMap entityMap, DbCommand command) where TEntity : class { // changing query to only select keys var selector = new StringBuilder(50); selector.Append("new("); foreach (var propertyMap in entityMap.KeyMaps) { if (selector.Length > 4) selector.Append((", ")); selector.Append(propertyMap.PropertyName); } selector.Append(")"); var selectQuery = DynamicQueryable.Select(query, selector.ToString()); var objectQuery = selectQuery as ObjectQuery; if (objectQuery == null) throw new ArgumentException("The query must be of type ObjectQuery.", "query"); string innerJoinSql = objectQuery.ToTraceString(); // create parameters foreach (var objectParameter in objectQuery.Parameters) { var parameter = command.CreateParameter(); parameter.ParameterName = objectParameter.Name; parameter.Value = objectParameter.Value; command.Parameters.Add(parameter); } return innerJoinSql; } } }
//----------------------------------------------------------------------------- // Game.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using Microsoft.Phone.Notification; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; namespace PushNotificationClient { /// <summary> /// PushNotificationClient is a simple XNA Framework application that opens an HttpNotificationChannel /// and waits to receive notifications. Status messages are printed to an onscreen console as well /// as the debug output. In order to copy the notification channel URI to the companion sender app, /// this program should be run under a debugger so the output can be seen. /// </summary> public class Game : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; SpriteFont font; DebugConsole console; private HttpNotificationChannel httpChannel; const string channelName = "ExampleXNAPushChannel"; const string serviceName = "ExampleXNAPushService"; public Game() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; // Frame rate is 30 fps by default for Windows Phone. TargetElapsedTime = TimeSpan.FromTicks(333333); // Pre-autoscale settings. graphics.PreferredBackBufferWidth = 480; graphics.PreferredBackBufferHeight = 800; graphics.IsFullScreen = true; } /// <summary> /// Initialize the game and create the notification channel. /// </summary> protected override void Initialize() { base.Initialize(); // Create or open a notification channel. CreateNotificationChannel(); } /// <summary> /// Load UI resources and create the output console. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); font = Content.Load<SpriteFont>("font"); console = new DebugConsole(font, graphics.GraphicsDevice.Viewport.Bounds); } /// <summary> /// Check for player input (in this case, the back button is the only input that /// matters). /// </summary> protected override void Update(GameTime gameTime) { // Allows the game to exit. if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) this.Exit(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.CornflowerBlue); console.Draw(spriteBatch); base.Draw(gameTime); } /// <summary> /// Creates (or re-opens) the push channel, and subscribes to push notification events. /// </summary> private void CreateNotificationChannel() { //Try to find an existing channel. console.AddLine("Looking for notification channel"); httpChannel = HttpNotificationChannel.Find(channelName); // If no existing channel is found, create a new one. The device's URI will be in the // event args of the HttpNotificationChannel.ChannelUriUpdated event. if (null == httpChannel) { console.AddLine("Creating new channel"); httpChannel = new HttpNotificationChannel(channelName, serviceName); httpChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(httpChannel_ChannelUriUpdated); httpChannel.Open(); } else { console.AddLine("Got existing channel Uri:\n" + httpChannel.ChannelUri.ToString()); } console.AddLine("Subscribing to channel events."); // Add an event handler for raw push messages. httpChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(httpChannel_HttpNotificationReceived); // Add an event handler for toast push messages. httpChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(httpChannel_ShellToastNotificationReceived); // Tile notifications cannot be handled in-game. // Add an event handler for channel errors. httpChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(httpChannel_ErrorOccurred); } /// <summary> /// The callback for a channel update. The event args contain the URI that points to the device. /// </summary> private void httpChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e) { // This URI is used to send notifications to the device and would need to be // sent to a game server or other web service any time the URI gets updated. console.AddLine("Channel updated. Got Uri:\n" + httpChannel.ChannelUri.ToString()); // Bind to the shell so the phone knows the app wants to receive notifications. console.AddLine("Binding to shell."); httpChannel.BindToShellToast(); httpChannel.BindToShellTile(); } /// <summary> /// The callback for a channel error. /// </summary> private void httpChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e) { console.AddLine("Error occurred: " + e.Message); console.AddLine("Trying to reopen channel."); httpChannel.Close(); httpChannel.Open(); } /// <summary> /// The callback for receiving a raw notification. /// </summary> private void httpChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e) { console.AddLine("Got raw notification:"); // The client and server must agree on the format of this notification: it's just bytes // as far as the phone is concerned. If the game is not running, this notification will // be dropped. In this case, the payload is a string that was serialized with BinaryWriter. BinaryReader reader = new BinaryReader(e.Notification.Body, System.Text.Encoding.UTF8); string notificationText = reader.ReadString(); console.AddLine(notificationText); } /// <summary> /// The callback for receiving a toast notification. /// </summary> private void httpChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e) { console.AddLine("Got toast notification:"); if (e.Collection != null) { Dictionary<string, string> collection = (Dictionary<string, string>)e.Collection; foreach (string elementName in collection.Keys) { console.AddLine(elementName + " : " + collection[elementName]); } } } } }
/* Copyright (c) 2014, RMIT Training 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 CounterCompliance 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.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 CounterReports.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = String.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(String.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
// Copyright (c) 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; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Editor.UnitTests.TypeInferrer; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.TypeInferrer { public partial class TypeInferrerTests : TypeInferrerTestBase<CSharpTestWorkspaceFixture> { protected override void TestWorker(Document document, TextSpan textSpan, string expectedType, bool useNodeStartPosition) { var root = document.GetSyntaxTreeAsync().Result.GetRoot(); var node = FindExpressionSyntaxFromSpan(root, textSpan); var typeInference = document.GetLanguageService<ITypeInferenceService>(); var inferredType = useNodeStartPosition ? typeInference.InferType(document.GetSemanticModelForSpanAsync(new TextSpan(node?.SpanStart ?? textSpan.Start, 0), CancellationToken.None).Result, node?.SpanStart ?? textSpan.Start, objectAsDefault: true, cancellationToken: CancellationToken.None) : typeInference.InferType(document.GetSemanticModelForSpanAsync(node?.Span ?? textSpan, CancellationToken.None).Result, node, objectAsDefault: true, cancellationToken: CancellationToken.None); var typeSyntax = inferredType.GenerateTypeSyntax(); Assert.Equal(expectedType, typeSyntax.ToString()); } private void TestInClass(string text, string expectedType) { text = @"class C { $ }".Replace("$", text); Test(text, expectedType); } private void TestInMethod(string text, string expectedType, bool testNode = true, bool testPosition = true) { text = @"class C { void M() { $ } }".Replace("$", text); Test(text, expectedType, testNode: testNode, testPosition: testPosition); } private ExpressionSyntax FindExpressionSyntaxFromSpan(SyntaxNode root, TextSpan textSpan) { var token = root.FindToken(textSpan.Start); var currentNode = token.Parent; while (currentNode != null) { ExpressionSyntax result = currentNode as ExpressionSyntax; if (result != null && result.Span == textSpan) { return result; } currentNode = currentNode.Parent; } return null; } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConditional1() { // We do not support position inference here as we're before the ? and we only look // backwards to infer a type here. TestInMethod("var q = [|Foo()|] ? 1 : 2;", "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConditional2() { TestInMethod("var q = a ? [|Foo()|] : 2;", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConditional3() { TestInMethod(@"var q = a ? """" : [|Foo()|];", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestVariableDeclarator1() { TestInMethod("int q = [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestVariableDeclarator2() { TestInMethod("var q = [|Foo()|];", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce1() { TestInMethod("var q = [|Foo()|] ?? 1;", "System.Int32?", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce2() { TestInMethod(@"bool? b; var q = b ?? [|Foo()|];", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce3() { TestInMethod(@"string s; var q = s ?? [|Foo()|];", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCoalesce4() { TestInMethod("var q = [|Foo()|] ?? string.Empty;", "System.String", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryExpression1() { TestInMethod(@"string s; var q = s + [|Foo()|];", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryExpression2() { TestInMethod(@"var s; var q = s || [|Foo()|];", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryOperator1() { TestInMethod(@"var q = x << [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBinaryOperator2() { TestInMethod(@"var q = x >> [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestAssignmentOperator3() { TestInMethod(@"var q <<= [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestAssignmentOperator4() { TestInMethod(@"var q >>= [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestOverloadedConditionalLogicalOperatorsInferBool() { Test(@"using System; class C { public static C operator &(C c, C d) { return null; } public static bool operator true(C c) { return true; } public static bool operator false(C c) { return false; } static void Main(string[] args) { var c = new C() && [|Foo()|]; } }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestConditionalLogicalOrOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a || [|7|]; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestConditionalLogicalAndOperatorAlwaysInfersBool() { var text = @"using System; class C { static void Main(string[] args) { var x = a && [|7|]; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | true; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] | b | c || d; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a | b | [|c|] || d; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(Program p) { return p; } }"; Test(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] | b); } static object Foo(bool p) { return p; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] | y) != 0) {} } }"; Test(text, "System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] | y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & true; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] & b & c && d; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a & b & [|c|] && d; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(Program p) { return p; } }"; Test(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] & b); } static object Foo(bool p) { return p; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] & y) != 0) {} } }"; Test(text, "System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] & y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ true; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { var x = [|a|] ^ b ^ c && d; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference3() { var text = @"using System; class C { static void Main(string[] args) { var x = a ^ b ^ [|c|] && d; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference4() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(Program p) { return p; } }"; Test(text, "Program", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference5() { var text = @"using System; class C { static void Main(string[] args) { var x = Foo([|a|] ^ b); } static object Foo(bool p) { return p; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference6() { var text = @"using System; class C { static void Main(string[] args) { if (([|x|] ^ y) != 0) {} } }"; Test(text, "System.Int32", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorOperatorInference7() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^ y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] |= y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalOrEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] |= y; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] &= y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalAndEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] &= y; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorEqualsOperatorInference1() { var text = @"using System; class C { static void Main(string[] args) { if ([|x|] ^= y) {} } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617633)] public void TestLogicalXorEqualsOperatorInference2() { var text = @"using System; class C { static void Main(string[] args) { int z = [|x|] ^= y; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturn1() { TestInClass(@"int M() { return [|Foo()|]; }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturn2() { TestInMethod("return [|Foo()|];", "void"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturn3() { TestInClass(@"int Property { get { return [|Foo()|]; } }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897)] public void TestYieldReturn() { var markup = @"using System.Collections.Generic; class Program { IEnumerable<int> M() { yield return [|abc|] } }"; Test(markup, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestReturnInLambda() { TestInMethod("System.Func<string,int> f = s => { return [|Foo()|]; };", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestLambda() { TestInMethod("System.Func<string, int> f = s => [|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestThrow() { TestInMethod("throw [|Foo()|];", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCatch() { TestInMethod("try { } catch ([|Foo|] ex) { }", "global::System.Exception"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIf() { TestInMethod(@"if ([|Foo()|]) { }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestWhile() { TestInMethod(@"while ([|Foo()|]) { }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestDo() { TestInMethod(@"do { } while ([|Foo()|])", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestFor1() { TestInMethod(@"for (int i = 0; [|Foo()|]; i++) { }", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestFor2() { TestInMethod(@"for (string i = [|Foo()|]; ; ) { }", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestFor3() { TestInMethod(@"for (var i = [|Foo()|]; ; ) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestUsing1() { TestInMethod(@"using ([|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestUsing2() { TestInMethod(@"using (int i = [|Foo()|]) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestUsing3() { TestInMethod(@"using (var v = [|Foo()|]) { }", "global::System.IDisposable"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestForEach() { TestInMethod(@"foreach (int v in [|Foo()|]) { }", "global::System.Collections.Generic.IEnumerable<System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression1() { TestInMethod(@"var q = +[|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression2() { TestInMethod(@"var q = -[|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression3() { TestInMethod(@"var q = ~[|Foo()|];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPrefixExpression4() { TestInMethod(@"var q = ![|Foo()|];", "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayRankSpecifier() { TestInMethod(@"var q = new string[[|Foo()|]];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestSwitch1() { TestInMethod(@"switch ([|Foo()|]) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestSwitch2() { TestInMethod(@"switch ([|Foo()|]) { default: }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestSwitch3() { TestInMethod(@"switch ([|Foo()|]) { case ""a"": }", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall1() { TestInMethod(@"Bar([|Foo()|]);", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall2() { TestInClass(@"void M() { Bar([|Foo()|]); } void Bar(int i);", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall3() { TestInClass(@"void M() { Bar([|Foo()|]); } void Bar();", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall4() { TestInClass(@"void M() { Bar([|Foo()|]); } void Bar(int i, string s);", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestMethodCall5() { TestInClass(@"void M() { Bar(s: [|Foo()|]); } void Bar(int i, string s);", "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall1() { TestInMethod(@"new C([|Foo()|]);", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall2() { TestInClass(@"void M() { new C([|Foo()|]); } C(int i) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall3() { TestInClass(@"void M() { new C([|Foo()|]); } C() { }", "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall4() { TestInClass(@"void M() { new C([|Foo()|]); } C(int i, string s) { }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestConstructorCall5() { TestInClass(@"void M() { new C(s: [|Foo()|]); } C(int i, string s) { }", "System.String"); } [WorkItem(858112)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestThisConstructorInitializer1() { Test(@"class MyClass { public MyClass(int x) : this([|test|]) { } }", "System.Int32"); } [WorkItem(858112)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestThisConstructorInitializer2() { Test(@"class MyClass { public MyClass(int x, string y) : this(5, [|test|]) { } }", "System.String"); } [WorkItem(858112)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestBaseConstructorInitializer() { Test(@"class B { public B(int x) { } } class D : B { public D() : base([|test|]) { } }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexAccess1() { TestInMethod(@"string[] i; i[[|Foo()|]];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall1() { TestInMethod(@"this[[|Foo()|]];", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall2() { // Update this when binding of indexers is working. TestInClass(@"void M() { this[[|Foo()|]]; } int this [int i] { get; }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall3() { // Update this when binding of indexers is working. TestInClass(@"void M() { this[[|Foo()|]]; } int this [int i, string s] { get; }", "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestIndexerCall5() { TestInClass(@"void M() { this[s: [|Foo()|]]; } int this [int i, string s] { get; }", "System.String"); } [Fact] public void TestArrayInitializerInImplicitArrayCreationSimple() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { 1, [|2|] }; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInImplicitArrayCreation1() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } int Foo() { return 2; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInImplicitArrayCreation2() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInImplicitArrayCreation3() { var text = @"using System.Collections.Generic; class C { void M() { var a = new[] { Bar(), [|Foo()|] }; } }"; Test(text, "System.Object"); } [Fact] public void TestArrayInitializerInEqualsValueClauseSimple() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { 1, [|2|] }; } }"; Test(text, "System.Int32"); } [Fact] public void TestArrayInitializerInEqualsValueClause() { var text = @"using System.Collections.Generic; class C { void M() { int[] a = { Bar(), [|Foo()|] }; } int Bar() { return 1; } }"; Test(text, "System.Int32"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCollectionInitializer1() { var text = @"using System.Collections.Generic; class C { void M() { new List<int>() { [|Foo()|] }; } }"; Test(text, "System.Int32"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCollectionInitializer2() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { [|Foo()|], """" } }; } }"; Test(text, "System.Int32"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCollectionInitializer3() { var text = @" using System.Collections.Generic; class C { void M() { new Dictionary<int,string>() { { 0, [|Foo()|] } }; } }"; Test(text, "System.String"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCustomCollectionInitializerAddMethod1() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { [|a|] }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; Test(text, "System.Int32", testPosition: false); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCustomCollectionInitializerAddMethod2() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { ""test"", [|b|] } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; Test(text, "System.Boolean"); } [Fact] [WorkItem(529480)] [Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestCustomCollectionInitializerAddMethod3() { var text = @"class C : System.Collections.IEnumerable { void M() { var x = new C() { { [|s|], true } }; } void Add(int i) { } void Add(string s, bool b) { } public System.Collections.IEnumerator GetEnumerator() { throw new System.NotImplementedException(); } }"; Test(text, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference1() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; Test(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference1_Position() { var text = @" class A { void Foo() { A[] x = new [|C|][] { }; } }"; Test(text, "global::A[]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference2() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; Test(text, "global::A", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference2_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][][] { }; } }"; Test(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference3() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; Test(text, "global::A[]", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference3_Position() { var text = @" class A { void Foo() { A[][] x = new [|C|][] { }; } }"; Test(text, "global::A[][]", testNode: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestArrayInference4() { var text = @" using System; class A { void Foo() { Func<int, int>[] x = new Func<int, int>[] { [|Bar()|] }; } }"; Test(text, "global::System.Func<System.Int32,System.Int32>"); } [WorkItem(538993)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestInsideLambda2() { var text = @"using System; class C { void M() { Func<int,int> f = i => [|here|] } }"; Test(text, "System.Int32"); } [WorkItem(539813)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestPointer1() { var text = @"class C { void M(int* i) { var q = i[[|Foo()|]]; } }"; Test(text, "System.Int32"); } [WorkItem(539813)] [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestDynamic1() { var text = @"class C { void M(dynamic i) { var q = i[[|Foo()|]]; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] public void TestChecked1() { var text = @"class C { void M() { string q = checked([|Foo()|]); } }"; Test(text, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public void TestAwaitTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { int x = await [|Foo()|]; } }"; Test(text, "global::System.Threading.Tasks.Task<System.Int32>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public void TestAwaitTaskOfTaskOfT() { var text = @"using System.Threading.Tasks; class C { void M() { Task<int> x = await [|Foo()|]; } }"; Test(text, "global::System.Threading.Tasks.Task<global::System.Threading.Tasks.Task<System.Int32>>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(553584)] public void TestAwaitTask() { var text = @"using System.Threading.Tasks; class C { void M() { await [|Foo()|]; } }"; Test(text, "global::System.Threading.Tasks.Task"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622)] public void TestLockStatement() { var text = @"class C { void M() { lock([|Foo()|]) { } } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(617622)] public void TestAwaitExpressionInLockStatement() { var text = @"class C { async void M() { lock(await [|Foo()|]) { } } }"; Test(text, "global::System.Threading.Tasks.Task<System.Object>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(827897)] public void TestReturnFromAsyncTaskOfT() { var markup = @"using System.Threading.Tasks; class Program { async Task<int> M() { await Task.Delay(1); return [|ab|] } }"; Test(markup, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public void TestAttributeArguments1() { var markup = @"[A([|dd|], ee, Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; Test(markup, "global::System.DayOfWeek"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public void TestAttributeArguments2() { var markup = @"[A(dd, [|ee|], Y = ff)] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; Test(markup, "System.Double"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(853840)] public void TestAttributeArguments3() { var markup = @"[A(dd, ee, Y = [|ff|])] class AAttribute : System.Attribute { public int X; public string Y; public AAttribute(System.DayOfWeek a, double b) { } }"; Test(markup, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(757111)] public void TestReturnStatementWithinDelegateWithinAMethodCall() { var text = @"using System; class Program { delegate string A(int i); static void Main(string[] args) { B(delegate(int i) { return [|M()|]; }); } private static void B(A a) { } }"; Test(text, "System.String"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public void TestCatchFilterClause() { var text = @" try { } catch (Exception) if ([|M()|]) }"; TestInMethod(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public void TestCatchFilterClause1() { var text = @" try { } catch (Exception) if ([|M|]) }"; TestInMethod(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(994388)] public void TestCatchFilterClause2() { var text = @" try { } catch (Exception) if ([|M|].N) }"; TestInMethod(text, "System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public void TestAwaitExpressionWithChainingMethod() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M()|].ConfigureAwait(false); } }"; Test(text, "global::System.Threading.Tasks.Task<System.Boolean>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(643, "https://github.com/dotnet/roslyn/issues/643")] public void TestAwaitExpressionWithChainingMethod2() { var text = @"using System; using System.Threading.Tasks; class C { static async void T() { bool x = await [|M|].ContinueWith(a => { return true; }).ContinueWith(a => { return false; }); } }"; Test(text, "global::System.Threading.Tasks.Task<System.Boolean>"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public void TestAwaitExpressionWithGenericMethod1() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await X([|Test()|]); } private async Task<T> X<T>(T t) { return t; } }"; Test(text, "System.Boolean", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4233, "https://github.com/dotnet/roslyn/issues/4233")] public void TestAwaitExpressionWithGenericMethod2() { var text = @"using System.Threading.Tasks; public class C { private async void M() { bool merged = await Task.Run(() => [|Test()|]);; } private async Task<T> X<T>(T t) { return t; } }"; Test(text, "System.Boolean"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public void TestNullCoalescingOperator1() { var text = @"class C { void M() { object z = [|a|]?? null; } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public void TestNullCoalescingOperator2() { var text = @"class C { void M() { object z = [|a|] ?? b ?? c; } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4483, "https://github.com/dotnet/roslyn/issues/4483")] public void TestNullCoalescingOperator3() { var text = @"class C { void M() { object z = a ?? [|b|] ?? c; } }"; Test(text, "System.Object"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public void TestSelectLambda() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[||]) } }"; Test(text, "System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(5126, "https://github.com/dotnet/roslyn/issues/5126")] public void TestSelectLambda2() { var text = @"using System.Collections.Generic; using System.Linq; class C { void M(IEnumerable<string> args) { args = args.Select(a =>[|b|]) } }"; Test(text, "System.Object", testPosition: false); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public void TestReturnInAsyncLambda1() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async () => { return [|a|]; }; } }"; Test(text, "System.Int32"); } [Fact, Trait(Traits.Feature, Traits.Features.TypeInferenceService)] [WorkItem(4486, "https://github.com/dotnet/roslyn/issues/4486")] public void TestReturnInAsyncLambda2() { var text = @"using System; using System.IO; using System.Threading.Tasks; public class C { public async void M() { Func<Task<int>> t2 = async delegate () { return [|a|]; }; } }"; Test(text, "System.Int32"); } } }
using System; using System.Data; using System.Data.SqlClient; using System.Drawing.Printing; using bv.model.BLToolkit; using DevExpress.XtraPrinting; using DevExpress.XtraReports.UI; using eidss.model.Reports; using eidss.model.Reports.AZ; using eidss.model.Reports.Common; using EIDSS.Reports.BaseControls; using EIDSS.Reports.BaseControls.Report; namespace EIDSS.Reports.Parameterized.Human.AJ.Reports { [CanWorkWithArchive] public sealed partial class VetCaseReport : BaseReport { private bool m_IsFirstRow = true; private bool m_IsPrintGroup = true; private int m_DiagnosisCounter; private class Totals { public int NumberCases { get; set; } public int NumberSamples { get; set; } public int NumberSpecies { get; set; } } public VetCaseReport() { InitializeComponent(); } public void SetParameters(DbManagerProxy manager, VetCasesSurrogateModel model) { SetLanguage(manager, model); ReportRebinder rebinder = ReportRebinder.GetDateRebinder(model.Language, this); DateTimeLabel.Text = rebinder.ToDateTimeString(DateTime.Now); periodCell.Text = GetPeriodText(model); organizationCell.Text = model.OrganizationEnteredByName; locationCell.Text = AddressModel.GetLocation(model.Language, m_BaseDataSet.sprepGetBaseParameters[0].CountryName, model.RegionId, model.RegionName, model.RayonId, model.RayonName); m_DiagnosisCounter = 1; Action<SqlConnection> action = (connection => { m_DataAdapter.Connection = connection; m_DataAdapter.Transaction = (SqlTransaction) manager.Transaction; m_DataAdapter.CommandTimeout = CommandTimeout; m_DataSet.EnforceConstraints = false; m_DataAdapter.Fill(m_DataSet.spRepVetCaseReportAZ, model.Language, model.StartYear, model.EndYear, model.StartMonth, model.EndMonth, model.RegionId, model.RayonId, model.OrganizationEnteredById); }); FillDataTableWithArchive(action, (SqlConnection) manager.Connection, m_DataSet.spRepVetCaseReportAZ, model.Mode, new[] {"strDiagnosisSpeciesKey", "strOIECode", "idfsDiagnosis", "DiagnosisOrderColumn", "SpeciesOrderColumn"}); DataView defaultView = m_DataSet.spRepVetCaseReportAZ.DefaultView; FillNumberOfCasesAndSamples(model, defaultView); Totals totals = GetTotals(defaultView); NumberCasesTotalCell.Text = totals.NumberCases.ToString(); NumberSamplesTotalCell.Text = totals.NumberSamples.ToString(); NumberSpeciesTotalCell.Text = totals.NumberSpecies.ToString(); defaultView.Sort = "DiagnosisOrderColumn, strDiagnosisName, SpeciesOrderColumn, strSpecies"; } private static void FillNumberOfCasesAndSamples(VetCasesSurrogateModel model, DataView defaultView) { defaultView.Sort = "idfsDiagnosis, SpeciesOrderColumn desc"; if (model.UseArchive) { long diagnosisId = -1; int numberCases = 0; int numberSamples = 0; foreach (DataRowView row in defaultView) { var currentDiagnosisId = (long) row["idfsDiagnosis"]; if (currentDiagnosisId != diagnosisId) { diagnosisId = currentDiagnosisId; numberCases = (int) row["intNumberCases"]; numberSamples = (int) row["intNumberSamples"]; } else { row["intNumberCases"] = numberCases; row["intNumberSamples"] = numberSamples; } } } } private static Totals GetTotals(DataView defaultView) { defaultView.Sort = "idfsDiagnosis, SpeciesOrderColumn desc"; long diagnosisId = -1; var totals = new Totals(); foreach (DataRowView row in defaultView) { var currentDiagnosisId = (long) row["idfsDiagnosis"]; if (currentDiagnosisId != diagnosisId) { diagnosisId = currentDiagnosisId; totals.NumberCases += (int) row["intNumberCases"]; totals.NumberSamples += (int) row["intNumberSamples"]; totals.NumberSpecies += (int) row["intNumberSpecies"]; } } return totals; } private void GroupFooterDiagnosis_BeforePrint(object sender, PrintEventArgs e) { m_IsPrintGroup = true; m_DiagnosisCounter++; RowNumberCell.Text = m_DiagnosisCounter.ToString(); } private void RowNumberCell_BeforePrint(object sender, PrintEventArgs e) { AjustGroupBorders(RowNumberCell, m_IsPrintGroup, m_DiagnosisCounter > 1); AjustGroupBorders(DiseaseCell, m_IsPrintGroup, m_DiagnosisCounter > 1); AjustGroupBorders(OIECell, m_IsPrintGroup, m_DiagnosisCounter > 1); AjustGroupBorders(NumberCasesCell, m_IsPrintGroup, m_DiagnosisCounter > 1); AjustGroupBorders(NumberSamplesCell, m_IsPrintGroup, m_DiagnosisCounter > 1); m_IsPrintGroup = false; } private void SpeciesCell_BeforePrint(object sender, PrintEventArgs e) { if (!m_IsFirstRow) { SpeciesCell.Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right; NumberSpeciesCell.Borders = BorderSide.Left | BorderSide.Top | BorderSide.Right; } m_IsFirstRow = false; } private void TotalNumberCell_BeforePrint(object sender, PrintEventArgs e) { TotalNumberCell.Text = m_DiagnosisCounter.ToString(); } public static void AjustGroupBorders(XRTableCell cell, bool isPrinted, bool notFirstDiagnosis) { if (!isPrinted) { cell.Text = string.Empty; cell.Borders = BorderSide.Left | BorderSide.Right; } else { cell.Borders = notFirstDiagnosis ? BorderSide.Left | BorderSide.Top | BorderSide.Right : BorderSide.Left | BorderSide.Right; } } #region helper methods public static string GetPeriodText(VetCasesSurrogateModel model) { string period; if (model.StartYear == model.EndYear) { if (model.StartMonth == model.EndMonth) { period = model.StartMonth.HasValue ? string.Format("{0} {1}", FilterHelper.GetMonthName(model.StartMonth.Value), model.StartYear) : model.StartYear.ToString(); } else { period = model.StartMonth.HasValue && model.EndMonth.HasValue ? string.Format("{0} - {1} {2}", FilterHelper.GetMonthName(model.StartMonth.Value), FilterHelper.GetMonthName(model.EndMonth.Value), model.StartYear) : model.StartYear.ToString(); } } else { period = model.StartMonth.HasValue && model.EndMonth.HasValue ? string.Format("{0} {1} - {2} {3}", FilterHelper.GetMonthName(model.StartMonth.Value), model.StartYear, FilterHelper.GetMonthName(model.EndMonth.Value), model.EndYear) : string.Format("{0} - {1}", model.StartYear, model.EndYear); } return period; } #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. /*============================================================ ** ** ** ** Purpose: Provides some basic access to some environment ** functionality. ** ** ============================================================*/ namespace System { using System.IO; using System.Security; using System.Resources; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Text; using System.Configuration.Assemblies; using System.Runtime.InteropServices; using System.Reflection; using System.Diagnostics; using Microsoft.Win32; using System.Runtime.CompilerServices; using System.Threading; using System.Runtime.ConstrainedExecution; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public enum EnvironmentVariableTarget { Process = 0, User = 1, Machine = 2, } internal static partial class Environment { // Assume the following constants include the terminating '\0' - use <, not <= private const int MaxEnvVariableValueLength = 32767; // maximum length for environment variable name and value // System environment variables are stored in the registry, and have // a size restriction that is separate from both normal environment // variables and registry value name lengths, according to MSDN. // MSDN doesn't detail whether the name is limited to 1024, or whether // that includes the contents of the environment variable. private const int MaxSystemEnvVariableLength = 1024; private const int MaxUserEnvVariableLength = 255; private const int MaxMachineNameLength = 256; // Looks up the resource string value for key. // // if you change this method's signature then you must change the code that calls it // in excep.cpp and probably you will have to visit mscorlib.h to add the new signature // as well as metasig.h to create the new signature type internal static String GetResourceStringLocal(String key) { return SR.GetResourceString(key); } // Private object for locking instead of locking on a public type for SQL reliability work. private static Object s_InternalSyncObject; private static Object InternalSyncObject { get { if (s_InternalSyncObject == null) { Object o = new Object(); Interlocked.CompareExchange<Object>(ref s_InternalSyncObject, o, null); } return s_InternalSyncObject; } } /*==================================TickCount=================================== **Action: Gets the number of ticks since the system was started. **Returns: The number of ticks since the system was started. **Arguments: None **Exceptions: None ==============================================================================*/ public static extern int TickCount { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } // Terminates this process with the given exit code. [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void _Exit(int exitCode); public static void Exit(int exitCode) { _Exit(exitCode); } public static extern int ExitCode { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; [MethodImplAttribute(MethodImplOptions.InternalCall)] set; } // Note: The CLR's Watson bucketization code looks at the caller of the FCALL method // to assign blame for crashes. Don't mess with this, such as by making it call // another managed helper method, unless you consult with some CLR Watson experts. [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message); // This overload of FailFast will allow you to specify the exception object // whose bucket details *could* be used when undergoing the failfast process. // To be specific: // // 1) When invoked from within a managed EH clause (fault/finally/catch), // if the exception object is preallocated, the runtime will try to find its buckets // and use them. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). // // 2) When invoked from outside the managed EH clauses (fault/finally/catch), // if the exception object is preallocated, the runtime will use the callsite's // IP for bucketing. If the exception object is not preallocated, it will use the bucket // details contained in the object (if any). [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void FailFast(String message, Exception exception); // Returns the system directory (ie, C:\WinNT\System32). internal static String SystemDirectory { get { StringBuilder sb = new StringBuilder(Path.MaxPath); int r = Win32Native.GetSystemDirectory(sb, Path.MaxPath); Debug.Assert(r < Path.MaxPath, "r < Path.MaxPath"); if (r == 0) __Error.WinIOError(); String path = sb.ToString(); return path; } } public static String ExpandEnvironmentVariables(String name) { if (name == null) throw new ArgumentNullException(nameof(name)); Contract.EndContractBlock(); if (name.Length == 0) { return name; } int currentSize = 100; StringBuilder blob = new StringBuilder(currentSize); // A somewhat reasonable default size #if PLATFORM_UNIX // Win32Native.ExpandEnvironmentStrings isn't available int lastPos = 0, pos; while (lastPos < name.Length && (pos = name.IndexOf('%', lastPos + 1)) >= 0) { if (name[lastPos] == '%') { string key = name.Substring(lastPos + 1, pos - lastPos - 1); string value = Environment.GetEnvironmentVariable(key); if (value != null) { blob.Append(value); lastPos = pos + 1; continue; } } blob.Append(name.Substring(lastPos, pos - lastPos)); lastPos = pos; } blob.Append(name.Substring(lastPos)); #else int size; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); while (size > currentSize) { currentSize = size; blob.Capacity = currentSize; blob.Length = 0; size = Win32Native.ExpandEnvironmentStrings(name, blob, currentSize); if (size == 0) Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } #endif // PLATFORM_UNIX return blob.ToString(); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private static extern Int32 GetProcessorCount(); public static int ProcessorCount { get { return GetProcessorCount(); } } /*==============================GetCommandLineArgs============================== **Action: Gets the command line and splits it appropriately to deal with whitespace, ** quotes, and escape characters. **Returns: A string array containing your command line arguments. **Arguments: None **Exceptions: None. ==============================================================================*/ public static String[] GetCommandLineArgs() { /* * There are multiple entry points to a hosted app. * The host could use ::ExecuteAssembly() or ::CreateDelegate option * ::ExecuteAssembly() -> In this particular case, the runtime invokes the main method based on the arguments set by the host, and we return those arguments * * ::CreateDelegate() -> In this particular case, the host is asked to create a * delegate based on the appDomain, assembly and methodDesc passed to it. * which the caller uses to invoke the method. In this particular case we do not have * any information on what arguments would be passed to the delegate. * So our best bet is to simply use the commandLine that was used to invoke the process. * in case it is present. */ if (s_CommandLineArgs != null) return (string[])s_CommandLineArgs.Clone(); return GetCommandLineArgsNative(); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern String[] GetCommandLineArgsNative(); private static string[] s_CommandLineArgs = null; private static void SetCommandLineArgs(string[] cmdLineArgs) { s_CommandLineArgs = cmdLineArgs; } private unsafe static char[] GetEnvironmentCharArray() { char[] block = null; // Make sure pStrings is not leaked with async exceptions RuntimeHelpers.PrepareConstrainedRegions(); try { } finally { char* pStrings = null; try { pStrings = Win32Native.GetEnvironmentStrings(); if (pStrings == null) { throw new OutOfMemoryException(); } // Format for GetEnvironmentStrings is: // [=HiddenVar=value\0]* [Variable=value\0]* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Search for terminating \0\0 (two unicode \0's). char* p = pStrings; while (!(*p == '\0' && *(p + 1) == '\0')) p++; int len = (int)(p - pStrings + 1); block = new char[len]; fixed (char* pBlock = block) string.wstrcpy(pBlock, pStrings, len); } finally { if (pStrings != null) Win32Native.FreeEnvironmentStrings(pStrings); } } return block; } /*===================================NewLine==================================== **Action: A property which returns the appropriate newline string for the given ** platform. **Returns: \r\n on Win32. **Arguments: None. **Exceptions: None. ==============================================================================*/ public static String NewLine { get { Contract.Ensures(Contract.Result<String>() != null); #if PLATFORM_WINDOWS return "\r\n"; #else return "\n"; #endif // PLATFORM_WINDOWS } } /*===================================Version==================================== **Action: Returns the COM+ version struct, describing the build number. **Returns: **Arguments: **Exceptions: ==============================================================================*/ public static Version Version { get { // Previously this represented the File version of mscorlib.dll. Many other libraries in the framework and outside took dependencies on the first three parts of this version // remaining constant throughout 4.x. From 4.0 to 4.5.2 this was fine since the file version only incremented the last part.Starting with 4.6 we switched to a file versioning // scheme that matched the product version. In order to preserve compatibility with existing libraries, this needs to be hard-coded. return new Version(4, 0, 30319, 42000); } } #if !FEATURE_PAL private static Lazy<bool> s_IsWindows8OrAbove = new Lazy<bool>(() => { ulong conditionMask = Win32Native.VerSetConditionMask(0, Win32Native.VER_MAJORVERSION, Win32Native.VER_GREATER_EQUAL); conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_MINORVERSION, Win32Native.VER_GREATER_EQUAL); conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMAJOR, Win32Native.VER_GREATER_EQUAL); conditionMask = Win32Native.VerSetConditionMask(conditionMask, Win32Native.VER_SERVICEPACKMINOR, Win32Native.VER_GREATER_EQUAL); // Windows 8 version is 6.2 var version = new Win32Native.OSVERSIONINFOEX { MajorVersion = 6, MinorVersion = 2, ServicePackMajor = 0, ServicePackMinor = 0 }; return Win32Native.VerifyVersionInfoW(version, Win32Native.VER_MAJORVERSION | Win32Native.VER_MINORVERSION | Win32Native.VER_SERVICEPACKMAJOR | Win32Native.VER_SERVICEPACKMINOR, conditionMask); }); internal static bool IsWindows8OrAbove => s_IsWindows8OrAbove.Value; #endif #if FEATURE_COMINTEROP // Does the current version of Windows have Windows Runtime suppport? private static Lazy<bool> s_IsWinRTSupported = new Lazy<bool>(() => { return WinRTSupported(); }); internal static bool IsWinRTSupported => s_IsWinRTSupported.Value; [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool WinRTSupported(); #endif // FEATURE_COMINTEROP /*==================================StackTrace================================== **Action: **Returns: **Arguments: **Exceptions: ==============================================================================*/ public static String StackTrace { [MethodImpl(MethodImplOptions.NoInlining)] // Prevent inlining from affecting where the stacktrace starts get { Contract.Ensures(Contract.Result<String>() != null); return Internal.Runtime.Augments.EnvironmentAugments.StackTrace; } } internal static String GetStackTrace(Exception e, bool needFileInfo) { // Note: Setting needFileInfo to true will start up COM and set our // apartment state. Try to not call this when passing "true" // before the EE's ExecuteMainMethod has had a chance to set up the // apartment state. -- StackTrace st; if (e == null) st = new StackTrace(needFileInfo); else st = new StackTrace(e, needFileInfo); // Do no include a trailing newline for backwards compatibility return st.ToString(System.Diagnostics.StackTrace.TraceFormat.Normal); } public static extern bool HasShutdownStarted { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } internal static bool UserInteractive { get { return true; } } public static int CurrentManagedThreadId { get { return Thread.CurrentThread.ManagedThreadId; } } internal static extern int CurrentProcessorNumber { [MethodImplAttribute(MethodImplOptions.InternalCall)] get; } // The upper bits of t_executionIdCache are the executionId. The lower bits of // the t_executionIdCache are counting down to get it periodically refreshed. // TODO: Consider flushing the executionIdCache on Wait operations or similar // actions that are likely to result in changing the executing core [ThreadStatic] private static int t_executionIdCache; private const int ExecutionIdCacheShift = 16; private const int ExecutionIdCacheCountDownMask = (1 << ExecutionIdCacheShift) - 1; private const int ExecutionIdRefreshRate = 5000; private static int RefreshExecutionId() { int executionId = CurrentProcessorNumber; // On Unix, CurrentProcessorNumber is implemented in terms of sched_getcpu, which // doesn't exist on all platforms. On those it doesn't exist on, GetCurrentProcessorNumber // returns -1. As a fallback in that case and to spread the threads across the buckets // by default, we use the current managed thread ID as a proxy. if (executionId < 0) executionId = Environment.CurrentManagedThreadId; Debug.Assert(ExecutionIdRefreshRate <= ExecutionIdCacheCountDownMask); // Mask with Int32.MaxValue to ensure the execution Id is not negative t_executionIdCache = ((executionId << ExecutionIdCacheShift) & Int32.MaxValue) | ExecutionIdRefreshRate; return executionId; } // Cached processor number used as a hint for which per-core stack to access. It is periodically // refreshed to trail the actual thread core affinity. internal static int CurrentExecutionId { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { int executionIdCache = t_executionIdCache--; if ((executionIdCache & ExecutionIdCacheCountDownMask) == 0) return RefreshExecutionId(); return (executionIdCache >> ExecutionIdCacheShift); } } public static string GetEnvironmentVariable(string variable) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case return GetEnvironmentVariableCore(variable); } internal static string GetEnvironmentVariable(string variable, EnvironmentVariableTarget target) { if (variable == null) { throw new ArgumentNullException(nameof(variable)); } ValidateTarget(target); return GetEnvironmentVariableCore(variable, target); } public static void SetEnvironmentVariable(string variable, string value) { ValidateVariableAndValue(variable, ref value); // separated from the EnvironmentVariableTarget overload to help with tree shaking in common case SetEnvironmentVariableCore(variable, value); } internal static void SetEnvironmentVariable(string variable, string value, EnvironmentVariableTarget target) { ValidateVariableAndValue(variable, ref value); ValidateTarget(target); SetEnvironmentVariableCore(variable, value, target); } private static void ValidateVariableAndValue(string variable, ref string value) { const int MaxEnvVariableValueLength = 32767; if (variable == null) { throw new ArgumentNullException(nameof(variable)); } if (variable.Length == 0) { throw new ArgumentException(SR.Argument_StringZeroLength, nameof(variable)); } if (variable[0] == '\0') { throw new ArgumentException(SR.Argument_StringFirstCharIsZero, nameof(variable)); } if (variable.Length >= MaxEnvVariableValueLength) { throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable)); } if (variable.IndexOf('=') != -1) { throw new ArgumentException(SR.Argument_IllegalEnvVarName, nameof(variable)); } if (string.IsNullOrEmpty(value) || value[0] == '\0') { // Explicitly null out value if it's empty value = null; } else if (value.Length >= MaxEnvVariableValueLength) { throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(value)); } } private static void ValidateTarget(EnvironmentVariableTarget target) { if (target != EnvironmentVariableTarget.Process && target != EnvironmentVariableTarget.Machine && target != EnvironmentVariableTarget.User) { throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target)); } } private static string GetEnvironmentVariableCore(string variable) { StringBuilder sb = StringBuilderCache.Acquire(128); // A somewhat reasonable default size int requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity); if (requiredSize == 0 && Marshal.GetLastWin32Error() == Win32Native.ERROR_ENVVAR_NOT_FOUND) { StringBuilderCache.Release(sb); return null; } while (requiredSize > sb.Capacity) { sb.Capacity = requiredSize; sb.Length = 0; requiredSize = Win32Native.GetEnvironmentVariable(variable, sb, sb.Capacity); } return StringBuilderCache.GetStringAndRelease(sb); } private static string GetEnvironmentVariableCore(string variable, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return GetEnvironmentVariableCore(variable); #if !FEATURE_WIN32_REGISTRY return null; #else RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false)) { return environmentKey?.GetValue(variable) as string; } #endif } internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables() { // Format for GetEnvironmentStrings is: // (=HiddenVar=value\0 | Variable=value\0)* \0 // See the description of Environment Blocks in MSDN's // CreateProcess page (null-terminated array of null-terminated strings). // Note the =HiddenVar's aren't always at the beginning. // Copy strings out, parsing into pairs and inserting into the table. // The first few environment variable entries start with an '='. // The current working directory of every drive (except for those drives // you haven't cd'ed into in your DOS window) are stored in the // environment block (as =C:=pwd) and the program's exit code is // as well (=ExitCode=00000000). char[] block = GetEnvironmentCharArray(); for (int i = 0; i < block.Length; i++) { int startKey = i; // Skip to key. On some old OS, the environment block can be corrupted. // Some will not have '=', so we need to check for '\0'. while (block[i] != '=' && block[i] != '\0') i++; if (block[i] == '\0') continue; // Skip over environment variables starting with '=' if (i - startKey == 0) { while (block[i] != 0) i++; continue; } string key = new string(block, startKey, i - startKey); i++; // skip over '=' int startValue = i; while (block[i] != 0) i++; // Read to end of this entry string value = new string(block, startValue, i - startValue); // skip over 0 handled by for loop's i++ yield return new KeyValuePair<string, string>(key, value); } } internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariables(EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) return EnumerateEnvironmentVariables(); return EnumerateEnvironmentVariablesFromRegistry(target); } internal static IEnumerable<KeyValuePair<string, string>> EnumerateEnvironmentVariablesFromRegistry(EnvironmentVariableTarget target) { #if !FEATURE_WIN32_REGISTRY // Without registry support we have nothing to return ValidateTarget(target); yield break; #else RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); baseKey = Registry.CurrentUser; keyName = @"Environment"; } else { throw new ArgumentOutOfRangeException(nameof(target), target, SR.Format(SR.Arg_EnumIllegalVal, target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: false)) { if (environmentKey != null) { foreach (string name in environmentKey.GetValueNames()) { string value = environmentKey.GetValue(name, "").ToString(); yield return new KeyValuePair<string, string>(name, value); } } } #endif // FEATURE_WIN32_REGISTRY } private static void SetEnvironmentVariableCore(string variable, string value) { // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') value = null; if (!Win32Native.SetEnvironmentVariable(variable, value)) { int errorCode = Marshal.GetLastWin32Error(); switch (errorCode) { case Win32Native.ERROR_ENVVAR_NOT_FOUND: // Allow user to try to clear a environment variable return; case Win32Native.ERROR_FILENAME_EXCED_RANGE: // The error message from Win32 is "The filename or extension is too long", // which is not accurate. throw new ArgumentException(SR.Format(SR.Argument_LongEnvVarValue)); default: throw new ArgumentException(Win32Native.GetMessage(errorCode)); } } } private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariableCore(variable, value); return; } #if !FEATURE_WIN32_REGISTRY // other targets ignored return; #else // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') value = null; RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { Debug.Assert(target == EnvironmentVariableTarget.User); // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name. const int MaxUserEnvVariableLength = 255; if (variable.Length >= MaxUserEnvVariableLength) { throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable)); } baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true)) { if (environmentKey != null) { if (value == null) { environmentKey.DeleteValue(variable, throwOnMissingValue: false); } else { environmentKey.SetValue(variable, value); } } } // send a WM_SETTINGCHANGE message to all windows IntPtr r = Win32Native.SendMessageTimeout(new IntPtr(Win32Native.HWND_BROADCAST), Win32Native.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero); if (r == IntPtr.Zero) Debug.Assert(false, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error()); #endif // FEATURE_WIN32_REGISTRY } } }
using GeckoUBL.Ubl21.Cac; using GeckoUBL.Ubl21.Cec; using GeckoUBL.Ubl21.Udt; namespace GeckoUBL.Ubl21.Documents { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:OrderResponse-2")] [System.Xml.Serialization.XmlRootAttribute("OrderResponse", Namespace="urn:oasis:names:specification:ubl:schema:xsd:OrderResponse-2", IsNullable=false)] public class OrderResponseType { /// <remarks/> [System.Xml.Serialization.XmlArrayAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonExtensionComponents-2")] [System.Xml.Serialization.XmlArrayItemAttribute("UBLExtension", IsNullable=false)] public UBLExtensionType[] UBLExtensions { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType UBLVersionID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType CustomizationID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType ProfileID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType ProfileExecutionID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType ID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType SalesOrderID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IndicatorType CopyIndicator { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public IdentifierType UUID { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public DateType IssueDate { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TimeType IssueTime { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType OrderResponseCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Note", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType[] Note { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType DocumentCurrencyCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType PricingCurrencyCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType TaxCurrencyCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public QuantityType TotalPackagesQuantity { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType GrossWeightMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType NetWeightMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType NetNetWeightMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType GrossVolumeMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public MeasureType NetVolumeMeasure { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType CustomerReference { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public CodeType AccountingCostCode { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public TextType AccountingCost { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")] public NumericType LineCountNumeric { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ValidityPeriod", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public PeriodType[] ValidityPeriod { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("OrderReference", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public OrderReferenceType[] OrderReference { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("OrderDocumentReference", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public DocumentReferenceType[] OrderDocumentReference { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public DocumentReferenceType OriginatorDocumentReference { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AdditionalDocumentReference", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public DocumentReferenceType[] AdditionalDocumentReference { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Contract", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public ContractType[] Contract { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Signature", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public SignatureType[] Signature { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public SupplierPartyType SellerSupplierParty { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public CustomerPartyType BuyerCustomerParty { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public CustomerPartyType OriginatorCustomerParty { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public PartyType FreightForwarderParty { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public SupplierPartyType AccountingSupplierParty { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public CustomerPartyType AccountingCustomerParty { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("Delivery", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public DeliveryType[] Delivery { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public DeliveryTermsType DeliveryTerms { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PaymentMeans", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public PaymentMeansType[] PaymentMeans { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("PaymentTerms", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public PaymentTermsType[] PaymentTerms { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("AllowanceCharge", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public AllowanceChargeType[] AllowanceCharge { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public TransactionConditionsType TransactionConditions { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public ExchangeRateType TaxExchangeRate { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public ExchangeRateType PricingExchangeRate { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public ExchangeRateType PaymentExchangeRate { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public CountryType DestinationCountry { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("TaxTotal", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public TaxTotalType[] TaxTotal { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public MonetaryTotalType LegalMonetaryTotal { get; set; } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("OrderLine", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")] public OrderLineType[] OrderLine { get; set; } } }
// 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; using Microsoft.CSharp.RuntimeBinder.Errors; using Microsoft.CSharp.RuntimeBinder.Syntax; namespace Microsoft.CSharp.RuntimeBinder.Semantics { // enum identifying all predefined methods used in the C# compiler // // Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Method> // if methods can only be disambiguated by signature, then follow the // above with _ <argument types> // // Keep this list sorted by containing type and name. internal enum PREDEFMETH { PM_FIRST = 0, PM_ARRAY_GETLENGTH, PM_DECIMAL_OPDECREMENT, PM_DECIMAL_OPDIVISION, PM_DECIMAL_OPEQUALITY, PM_DECIMAL_OPGREATERTHAN, PM_DECIMAL_OPGREATERTHANOREQUAL, PM_DECIMAL_OPINCREMENT, PM_DECIMAL_OPINEQUALITY, PM_DECIMAL_OPLESSTHAN, PM_DECIMAL_OPLESSTHANOREQUAL, PM_DECIMAL_OPMINUS, PM_DECIMAL_OPMODULUS, PM_DECIMAL_OPMULTIPLY, PM_DECIMAL_OPPLUS, PM_DECIMAL_OPUNARYMINUS, PM_DECIMAL_OPUNARYPLUS, PM_DELEGATE_COMBINE, PM_DELEGATE_OPEQUALITY, PM_DELEGATE_OPINEQUALITY, PM_DELEGATE_REMOVE, PM_EXPRESSION_ADD, PM_EXPRESSION_ADD_USER_DEFINED, PM_EXPRESSION_ADDCHECKED, PM_EXPRESSION_ADDCHECKED_USER_DEFINED, PM_EXPRESSION_AND, PM_EXPRESSION_AND_USER_DEFINED, PM_EXPRESSION_ANDALSO, PM_EXPRESSION_ANDALSO_USER_DEFINED, PM_EXPRESSION_ARRAYINDEX, PM_EXPRESSION_ARRAYINDEX2, PM_EXPRESSION_ASSIGN, PM_EXPRESSION_CONDITION, PM_EXPRESSION_CONSTANT_OBJECT_TYPE, PM_EXPRESSION_CONVERT, PM_EXPRESSION_CONVERT_USER_DEFINED, PM_EXPRESSION_CONVERTCHECKED, PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, PM_EXPRESSION_DIVIDE, PM_EXPRESSION_DIVIDE_USER_DEFINED, PM_EXPRESSION_EQUAL, PM_EXPRESSION_EQUAL_USER_DEFINED, PM_EXPRESSION_EXCLUSIVEOR, PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, PM_EXPRESSION_FIELD, PM_EXPRESSION_GREATERTHAN, PM_EXPRESSION_GREATERTHAN_USER_DEFINED, PM_EXPRESSION_GREATERTHANOREQUAL, PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, PM_EXPRESSION_LAMBDA, PM_EXPRESSION_LEFTSHIFT, PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, PM_EXPRESSION_LESSTHAN, PM_EXPRESSION_LESSTHAN_USER_DEFINED, PM_EXPRESSION_LESSTHANOREQUAL, PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, PM_EXPRESSION_MODULO, PM_EXPRESSION_MODULO_USER_DEFINED, PM_EXPRESSION_MULTIPLY, PM_EXPRESSION_MULTIPLY_USER_DEFINED, PM_EXPRESSION_MULTIPLYCHECKED, PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, PM_EXPRESSION_NOTEQUAL, PM_EXPRESSION_NOTEQUAL_USER_DEFINED, PM_EXPRESSION_OR, PM_EXPRESSION_OR_USER_DEFINED, PM_EXPRESSION_ORELSE, PM_EXPRESSION_ORELSE_USER_DEFINED, PM_EXPRESSION_PARAMETER, PM_EXPRESSION_RIGHTSHIFT, PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, PM_EXPRESSION_SUBTRACT, PM_EXPRESSION_SUBTRACT_USER_DEFINED, PM_EXPRESSION_SUBTRACTCHECKED, PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, PM_EXPRESSION_UNARYPLUS_USER_DEFINED, PM_EXPRESSION_NEGATE, PM_EXPRESSION_NEGATE_USER_DEFINED, PM_EXPRESSION_NEGATECHECKED, PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, PM_EXPRESSION_CALL, PM_EXPRESSION_NEW, PM_EXPRESSION_NEW_MEMBERS, PM_EXPRESSION_NEW_TYPE, PM_EXPRESSION_QUOTE, PM_EXPRESSION_ARRAYLENGTH, PM_EXPRESSION_NOT, PM_EXPRESSION_NOT_USER_DEFINED, PM_EXPRESSION_NEWARRAYINIT, PM_EXPRESSION_PROPERTY, PM_EXPRESSION_INVOKE, PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, PM_G_OPTIONAL_CTOR, PM_G_OPTIONAL_GETHASVALUE, PM_G_OPTIONAL_GETVALUE, PM_G_OPTIONAL_GET_VALUE_OR_DEF, PM_STRING_CONCAT_OBJECT_1, // NOTE: these 3 must be sequential. See RealizeConcats PM_STRING_CONCAT_OBJECT_2, PM_STRING_CONCAT_OBJECT_3, PM_STRING_CONCAT_STRING_1, // NOTE: these 4 must be sequential. See RealizeConcats PM_STRING_CONCAT_STRING_2, PM_STRING_CONCAT_STRING_3, PM_STRING_CONCAT_STRING_4, PM_STRING_CONCAT_SZ_OBJECT, PM_STRING_CONCAT_SZ_STRING, PM_STRING_GETCHARS, PM_STRING_GETLENGTH, PM_STRING_OPEQUALITY, PM_STRING_OPINEQUALITY, PM_COUNT } // enum identifying all predefined properties used in the C# compiler // Naming convention is PREDEFMETH.PM_ <Predefined CType> _ < Predefined Name of Property> // Keep this list sorted by containing type and name. internal enum PREDEFPROP { PP_FIRST = 0, PP_ARRAY_LENGTH, PP_G_OPTIONAL_VALUE, PP_COUNT, }; internal enum MethodRequiredEnum { Required, Optional } internal enum MethodCallingConventionEnum { Static, Virtual, Instance } // Enum used to encode a method signature // A signature is encoded as a sequence of int values. // The grammar for signatures is: // // signature // return_type count_of_parameters parameter_types // // type // any predefined type (ex: PredefinedType.PT_OBJECT, PredefinedType.PT_VOID) type_args // MethodSignatureEnum.SIG_CLASS_TYVAR index_of_class_tyvar // MethodSignatureEnum.SIG_METH_TYVAR index_of_method_tyvar // MethodSignatureEnum.SIG_SZ_ARRAY type // MethodSignatureEnum.SIG_REF type // MethodSignatureEnum.SIG_OUT type // internal enum MethodSignatureEnum { // Values 0 to PredefinedType.PT_VOID are reserved for predefined types in signatures // start next value at PredefinedType.PT_VOID + 1, SIG_CLASS_TYVAR = (int)PredefinedType.PT_VOID + 1, // next element in signature is index of class tyvar SIG_METH_TYVAR, // next element in signature is index of method tyvar SIG_SZ_ARRAY, // must be followed by signature type of array elements SIG_REF, // must be followed by signature of ref type SIG_OUT, // must be followed by signature of out type } // A description of a method the compiler uses while compiling. internal class PredefinedMethodInfo { public PREDEFMETH method; public PredefinedType type; public PredefinedName name; public MethodCallingConventionEnum callingConvention; public ACCESS access; // ACCESS.ACC_UNKNOWN means any accessibility is ok public int cTypeVars; public int[] signature; // Size 8. expand this if a new method has a signature which doesn't fit in the current space public PredefinedMethodInfo(PREDEFMETH method, MethodRequiredEnum required, PredefinedType type, PredefinedName name, MethodCallingConventionEnum callingConvention, ACCESS access, int cTypeVars, int[] signature) { this.method = method; this.type = type; this.name = name; this.callingConvention = callingConvention; this.access = access; this.cTypeVars = cTypeVars; this.signature = signature; } } // A description of a method the compiler uses while compiling. internal class PredefinedPropertyInfo { public PREDEFPROP property; public PredefinedName name; public PREDEFMETH getter; public PREDEFMETH setter; public PredefinedPropertyInfo(PREDEFPROP property, MethodRequiredEnum required, PredefinedName name, PREDEFMETH getter, PREDEFMETH setter) { this.property = property; this.name = name; this.getter = getter; this.setter = setter; } }; // Loads and caches predefined members. // Also finds constructors on delegate types. internal class PredefinedMembers { protected static void RETAILVERIFY(bool f) { if (!f) Debug.Assert(false, "panic!"); } private SymbolLoader _loader; internal SymbolTable RuntimeBinderSymbolTable; private MethodSymbol[] _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; private PropertySymbol[] _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; private Name GetMethName(PREDEFMETH method) { return GetPredefName(GetMethPredefName(method)); } private AggregateSymbol GetMethParent(PREDEFMETH method) { return GetOptPredefAgg(GetMethPredefType(method)); } // delegate specific helpers private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, int[] signature) { Debug.Assert(delegateType != null && delegateType.IsDelegate()); Debug.Assert(signature != null); return LoadMethod( delegateType, signature, 0, // meth ty vars GetPredefName(PredefinedName.PN_CTOR), ACCESS.ACC_PUBLIC, false, // MethodCallingConventionEnum.Static false); // MethodCallingConventionEnum.Virtual } private MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType) { Debug.Assert(delegateType != null && delegateType.IsDelegate()); MethodSymbol ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature1); if (ctor == null) { ctor = FindDelegateConstructor(delegateType, s_DelegateCtorSignature2); } return ctor; } public MethodSymbol FindDelegateConstructor(AggregateSymbol delegateType, bool fReportErrors) { MethodSymbol ctor = FindDelegateConstructor(delegateType); if (ctor == null && fReportErrors) { GetErrorContext().Error(ErrorCode.ERR_BadDelegateConstructor, delegateType); } return ctor; throw Error.InternalCompilerError(); } // property specific helpers private PropertySymbol EnsureProperty(PREDEFPROP property) { RETAILVERIFY((int)property > (int)PREDEFMETH.PM_FIRST && (int)property < (int)PREDEFMETH.PM_COUNT); if (_properties[(int)property] == null) { _properties[(int)property] = LoadProperty(property); } return _properties[(int)property]; } private PropertySymbol LoadProperty(PREDEFPROP property) { return LoadProperty( property, GetPropName(property), GetPropGetter(property), GetPropSetter(property)); } private Name GetPropName(PREDEFPROP property) { return GetPredefName(GetPropPredefName(property)); } private PropertySymbol LoadProperty( PREDEFPROP predefProp, Name propertyName, PREDEFMETH propertyGetter, PREDEFMETH propertySetter) { Debug.Assert(propertyName != null); Debug.Assert(propertyGetter > PREDEFMETH.PM_FIRST && propertyGetter < PREDEFMETH.PM_COUNT); Debug.Assert(propertySetter > PREDEFMETH.PM_FIRST && propertySetter <= PREDEFMETH.PM_COUNT); MethodSymbol getter = GetOptionalMethod(propertyGetter); MethodSymbol setter = null; if (propertySetter != PREDEFMETH.PM_COUNT) { setter = GetOptionalMethod(propertySetter); } if (getter == null && setter == null) { RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName); getter = GetOptionalMethod(propertyGetter); if (propertySetter != PREDEFMETH.PM_COUNT) { setter = GetOptionalMethod(propertySetter); } } if (setter != null) { setter.SetMethKind(MethodKindEnum.PropAccessor); } PropertySymbol property = null; if (getter != null) { getter.SetMethKind(MethodKindEnum.PropAccessor); property = getter.getProperty(); // Didn't find it, so load it. if (property == null) { RuntimeBinderSymbolTable.AddPredefinedPropertyToSymbolTable(GetOptPredefAgg(GetPropPredefType(predefProp)), propertyName); } property = getter.getProperty(); Debug.Assert(property != null); if (property.name != propertyName || (propertySetter != PREDEFMETH.PM_COUNT && (setter == null || !setter.isPropertyAccessor() || setter.getProperty() != property)) || property.getBogus()) { property = null; } } return property; } private SymbolLoader GetSymbolLoader() { Debug.Assert(_loader != null); return _loader; } private ErrorHandling GetErrorContext() { return GetSymbolLoader().GetErrorContext(); } private NameManager GetNameManager() { return GetSymbolLoader().GetNameManager(); } private TypeManager GetTypeManager() { return GetSymbolLoader().GetTypeManager(); } private BSYMMGR getBSymmgr() { return GetSymbolLoader().getBSymmgr(); } private Name GetPredefName(PredefinedName pn) { return GetNameManager().GetPredefName(pn); } private AggregateSymbol GetOptPredefAgg(PredefinedType pt) { return GetSymbolLoader().GetOptPredefAgg(pt); } private CType LoadTypeFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); MethodSignatureEnum current = (MethodSignatureEnum)signature[indexIntoSignatures]; indexIntoSignatures++; switch (current) { case MethodSignatureEnum.SIG_REF: { CType refType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (refType == null) { return null; } return GetTypeManager().GetParameterModifier(refType, false); } case MethodSignatureEnum.SIG_OUT: { CType outType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (outType == null) { return null; } return GetTypeManager().GetParameterModifier(outType, true); } case MethodSignatureEnum.SIG_SZ_ARRAY: { CType elementType = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (elementType == null) { return null; } return GetTypeManager().GetArray(elementType, 1); } case MethodSignatureEnum.SIG_METH_TYVAR: { int index = signature[indexIntoSignatures]; indexIntoSignatures++; return GetTypeManager().GetStdMethTypeVar(index); } case MethodSignatureEnum.SIG_CLASS_TYVAR: { int index = signature[indexIntoSignatures]; indexIntoSignatures++; return classTyVars.Item(index); } case (MethodSignatureEnum)PredefinedType.PT_VOID: return GetTypeManager().GetVoid(); default: { Debug.Assert(current >= 0 && (int)current < (int)PredefinedType.PT_COUNT); AggregateSymbol agg = GetOptPredefAgg((PredefinedType)current); if (agg != null) { CType[] typeArgs = new CType[agg.GetTypeVars().size]; for (int iTypeArg = 0; iTypeArg < agg.GetTypeVars().size; iTypeArg++) { typeArgs[iTypeArg] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (typeArgs[iTypeArg] == null) { return null; } } AggregateType type = GetTypeManager().GetAggregate(agg, getBSymmgr().AllocParams(agg.GetTypeVars().size, typeArgs)); if (type.isPredefType(PredefinedType.PT_G_OPTIONAL)) { return GetTypeManager().GetNubFromNullable(type); } return type; } } break; } return null; } private TypeArray LoadTypeArrayFromSignature(int[] signature, ref int indexIntoSignatures, TypeArray classTyVars) { Debug.Assert(signature != null); int count = signature[indexIntoSignatures]; indexIntoSignatures++; Debug.Assert(count >= 0); CType[] ptypes = new CType[count]; for (int i = 0; i < count; i++) { ptypes[i] = LoadTypeFromSignature(signature, ref indexIntoSignatures, classTyVars); if (ptypes[i] == null) { return null; } } return getBSymmgr().AllocParams(count, ptypes); } public PredefinedMembers(SymbolLoader loader) { _loader = loader; Debug.Assert(_loader != null); _methods = new MethodSymbol[(int)PREDEFMETH.PM_COUNT]; _properties = new PropertySymbol[(int)PREDEFPROP.PP_COUNT]; #if DEBUG // validate the tables for (int i = (int)PREDEFMETH.PM_FIRST + 1; i < (int)PREDEFMETH.PM_COUNT; i++) { Debug.Assert((int)GetMethInfo((PREDEFMETH)i).method == i); } for (int i = (int)PREDEFPROP.PP_FIRST + 1; i < (int)PREDEFPROP.PP_COUNT; i++) { Debug.Assert((int)GetPropInfo((PREDEFPROP)i).property == i); } #endif } public PropertySymbol GetProperty(PREDEFPROP property) // Reports an error if the property is not found. { PropertySymbol result = EnsureProperty(property); if (result == null) { ReportError(property); } return result; } public MethodSymbol GetMethod(PREDEFMETH method) { MethodSymbol result = EnsureMethod(method); if (result == null) { ReportError(method); } return result; } public MethodSymbol GetOptionalMethod(PREDEFMETH method) { return EnsureMethod(method); } private MethodSymbol EnsureMethod(PREDEFMETH method) { RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT); if (_methods[(int)method] == null) { _methods[(int)method] = LoadMethod(method); } return _methods[(int)method]; } private MethodSymbol LoadMethod( AggregateSymbol type, int[] signature, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual ) { Debug.Assert(signature != null); Debug.Assert(cMethodTyVars >= 0); Debug.Assert(methodName != null); if (type == null) { return null; } TypeArray classTyVars = type.GetTypeVarsAll(); int index = 0; CType returnType = LoadTypeFromSignature(signature, ref index, classTyVars); if (returnType == null) { return null; } TypeArray argumentTypes = LoadTypeArrayFromSignature(signature, ref index, classTyVars); if (argumentTypes == null) { return null; } TypeArray standardMethodTyVars = GetTypeManager().GetStdMethTyVarArray(cMethodTyVars); MethodSymbol ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); if (ret == null) { RuntimeBinderSymbolTable.AddPredefinedMethodToSymbolTable(type, methodName); ret = LookupMethodWhileLoading(type, cMethodTyVars, methodName, methodAccess, isStatic, isVirtual, returnType, argumentTypes); } return ret; } private MethodSymbol LookupMethodWhileLoading(AggregateSymbol type, int cMethodTyVars, Name methodName, ACCESS methodAccess, bool isStatic, bool isVirtual, CType returnType, TypeArray argumentTypes) { for (Symbol sym = GetSymbolLoader().LookupAggMember(methodName, type, symbmask_t.MASK_ALL); sym != null; sym = GetSymbolLoader().LookupNextSym(sym, type, symbmask_t.MASK_ALL)) { if (sym.IsMethodSymbol()) { MethodSymbol methsym = sym.AsMethodSymbol(); if ((methsym.GetAccess() == methodAccess || methodAccess == ACCESS.ACC_UNKNOWN) && methsym.isStatic == isStatic && methsym.isVirtual == isVirtual && methsym.typeVars.size == cMethodTyVars && GetTypeManager().SubstEqualTypes(methsym.RetType, returnType, null, methsym.typeVars, SubstTypeFlags.DenormMeth) && GetTypeManager().SubstEqualTypeArrays(methsym.Params, argumentTypes, (TypeArray)null, methsym.typeVars, SubstTypeFlags.DenormMeth) && !methsym.getBogus()) { return methsym; } } } return null; } private MethodSymbol LoadMethod(PREDEFMETH method) { return LoadMethod( GetMethParent(method), GetMethSignature(method), GetMethTyVars(method), GetMethName(method), GetMethAccess(method), IsMethStatic(method), IsMethVirtual(method)); } private void ReportError(PREDEFMETH method) { ReportError(GetMethPredefType(method), GetMethPredefName(method)); } private void ReportError(PredefinedType type, PredefinedName name) { GetErrorContext().Error(ErrorCode.ERR_MissingPredefinedMember, PredefinedTypes.GetFullName(type), GetPredefName(name)); } private static int[] s_DelegateCtorSignature1 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_INTPTR }; private static int[] s_DelegateCtorSignature2 = { (int)PredefinedType.PT_VOID, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_UINTPTR }; private static PredefinedName GetPropPredefName(PREDEFPROP property) { return GetPropInfo(property).name; } private static PREDEFMETH GetPropGetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).getter; // getters are MethodRequiredEnum.Required Debug.Assert(result > PREDEFMETH.PM_FIRST && result < PREDEFMETH.PM_COUNT); return result; } private static PredefinedType GetPropPredefType(PREDEFPROP property) { return GetMethInfo(GetPropGetter(property)).type; } private static PREDEFMETH GetPropSetter(PREDEFPROP property) { PREDEFMETH result = GetPropInfo(property).setter; // setters are not MethodRequiredEnum.Required Debug.Assert(result > PREDEFMETH.PM_FIRST && result <= PREDEFMETH.PM_COUNT); return GetPropInfo(property).setter; } private void ReportError(PREDEFPROP property) { ReportError(GetPropPredefType(property), GetPropPredefName(property)); } // the list of predefined property definitions. // This list must be in the same order as the PREDEFPROP enum. private static PredefinedPropertyInfo[] s_predefinedProperties = { new PredefinedPropertyInfo( PREDEFPROP.PP_FIRST, MethodRequiredEnum.Optional, PredefinedName.PN_COUNT, PREDEFMETH.PM_COUNT, PREDEFMETH.PM_COUNT ), new PredefinedPropertyInfo( PREDEFPROP.PP_ARRAY_LENGTH, MethodRequiredEnum.Optional, PredefinedName.PN_LENGTH, PREDEFMETH.PM_ARRAY_GETLENGTH, PREDEFMETH.PM_COUNT ), new PredefinedPropertyInfo( PREDEFPROP.PP_G_OPTIONAL_VALUE, MethodRequiredEnum.Optional, PredefinedName.PN_CAP_VALUE, PREDEFMETH.PM_G_OPTIONAL_GETVALUE, PREDEFMETH.PM_COUNT ), }; public static PredefinedPropertyInfo GetPropInfo(PREDEFPROP property) { RETAILVERIFY(property > PREDEFPROP.PP_FIRST && property < PREDEFPROP.PP_COUNT); RETAILVERIFY(s_predefinedProperties[(int)property].property == property); return s_predefinedProperties[(int)property]; } public static PredefinedMethodInfo GetMethInfo(PREDEFMETH method) { RETAILVERIFY(method > PREDEFMETH.PM_FIRST && method < PREDEFMETH.PM_COUNT); RETAILVERIFY(s_predefinedMethods[(int)method].method == method); return s_predefinedMethods[(int)method]; } private static PredefinedName GetMethPredefName(PREDEFMETH method) { return GetMethInfo(method).name; } private static PredefinedType GetMethPredefType(PREDEFMETH method) { return GetMethInfo(method).type; } private static bool IsMethStatic(PREDEFMETH method) { return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Static; } private static bool IsMethVirtual(PREDEFMETH method) { return GetMethInfo(method).callingConvention == MethodCallingConventionEnum.Virtual; } private static ACCESS GetMethAccess(PREDEFMETH method) { return GetMethInfo(method).access; } private static int GetMethTyVars(PREDEFMETH method) { return GetMethInfo(method).cTypeVars; } private static int[] GetMethSignature(PREDEFMETH method) { return GetMethInfo(method).signature; } // the list of predefined method definitions. // This list must be in the same order as the PREDEFMETH enum. private static PredefinedMethodInfo[] s_predefinedMethods = new PredefinedMethodInfo[(int)PREDEFMETH.PM_COUNT] { new PredefinedMethodInfo( PREDEFMETH.PM_FIRST, MethodRequiredEnum.Optional, PredefinedType.PT_COUNT, PredefinedName.PN_COUNT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_ARRAY_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_ARRAY, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDECREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDECREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPDIVISION, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPDIVISION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPGREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPGREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINCREMENT, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINCREMENT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPLESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPLESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMODULUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMODULUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPMULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPMULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 2, (int)PredefinedType.PT_DECIMAL, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYMINUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYMINUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DECIMAL_OPUNARYPLUS, MethodRequiredEnum.Optional, PredefinedType.PT_DECIMAL, PredefinedName.PN_OPUNARYPLUS, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DECIMAL, 1, (int)PredefinedType.PT_DECIMAL }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_COMBINE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_COMBINE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_DELEGATE_REMOVE, MethodRequiredEnum.Optional, PredefinedType.PT_DELEGATE, PredefinedName.PN_REMOVE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_DELEGATE, (int)PredefinedType.PT_DELEGATE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADD_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ADDCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ADDCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_AND_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_AND, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ANDALSO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ANDALSO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYINDEX2, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYINDEX, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ASSIGN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ASSIGN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONDITION, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONDITION, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONDITIONALEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONSTANT_OBJECT_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONSTANT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CONSTANTEXPRESSION, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CONVERTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CONVERTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_DIVIDE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_DIVIDE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_EXCLUSIVEOR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXCLUSIVEOR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_FIELD, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CAP_FIELD, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_FIELDINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_GREATERTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_GREATERTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LAMBDA, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LAMBDA, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 1, new int[] { (int)PredefinedType.PT_G_EXPRESSION, (int)MethodSignatureEnum.SIG_METH_TYVAR, 0, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_PARAMETEREXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LEFTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LEFTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHAN_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHAN, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_LESSTHANOREQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_LESSTHANOREQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MODULO_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MODULO, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLY_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_MULTIPLYCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_MULTIPLYCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOTEQUAL_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOTEQUAL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 4, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_BOOL, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_OR_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_OR, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ORELSE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ORELSE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PARAMETER, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PARAMETER, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_PARAMETEREXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_RIGHTSHIFT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_RIGHTSHIFT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_SUBTRACTCHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_SUBTRACTCHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BINARYEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_UNARYPLUS_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_PLUS , MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATE_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEGATECHECKED_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEGATECHECKED, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_CALL, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_CALL, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_METHODCALLEXPRESSION, 3, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 2, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_MEMBERS, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 3, (int)PredefinedType.PT_CONSTRUCTORINFO, (int)PredefinedType.PT_G_IENUMERABLE, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_MEMBERINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEW_TYPE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEW, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWEXPRESSION, 1, (int)PredefinedType.PT_TYPE }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_QUOTE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_QUOTE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_ARRAYLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_ARRAYLENGTH, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 1, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NOT_USER_DEFINED, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NOT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_UNARYEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_METHODINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_NEWARRAYINIT, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_NEWARRAYINIT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_NEWARRAYEXPRESSION, 2, (int)PredefinedType.PT_TYPE, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_PROPERTY, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_EXPRESSION_PROPERTY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_MEMBEREXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)PredefinedType.PT_PROPERTYINFO }), new PredefinedMethodInfo( PREDEFMETH.PM_EXPRESSION_INVOKE, MethodRequiredEnum.Optional, PredefinedType.PT_EXPRESSION, PredefinedName.PN_INVOKE, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INVOCATIONEXPRESSION, 2, (int)PredefinedType.PT_EXPRESSION, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_EXPRESSION }), new PredefinedMethodInfo( PREDEFMETH.PM_METHODINFO_CREATEDELEGATE_TYPE_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_METHODINFO, PredefinedName.PN_CREATEDELEGATE, MethodCallingConventionEnum.Virtual, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_DELEGATE, 2, (int)PredefinedType.PT_TYPE, (int)PredefinedType.PT_OBJECT}), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_CTOR, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_CTOR, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_VOID, 1, (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETHASVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETHASVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GETVALUE, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GETVALUE, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_G_OPTIONAL_GET_VALUE_OR_DEF, MethodRequiredEnum.Optional, PredefinedType.PT_G_OPTIONAL, PredefinedName.PN_GET_VALUE_OR_DEF, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)MethodSignatureEnum.SIG_CLASS_TYVAR, 0, 0 }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_OBJECT_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_1, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_2, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_3, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 3, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_STRING_4, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 4, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_OBJECT, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_OBJECT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_CONCAT_SZ_STRING, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_CONCAT, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_STRING, 1, (int)MethodSignatureEnum.SIG_SZ_ARRAY, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETCHARS, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETCHARS, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_CHAR, 1, (int)PredefinedType.PT_INT }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_GETLENGTH, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_GETLENGTH, MethodCallingConventionEnum.Instance, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_INT, 0, }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), new PredefinedMethodInfo( PREDEFMETH.PM_STRING_OPINEQUALITY, MethodRequiredEnum.Optional, PredefinedType.PT_STRING, PredefinedName.PN_OPINEQUALITY, MethodCallingConventionEnum.Static, ACCESS.ACC_PUBLIC, 0, new int[] { (int)PredefinedType.PT_BOOL, 2, (int)PredefinedType.PT_STRING, (int)PredefinedType.PT_STRING }), }; } }
using System; using TidyNet.Dom; namespace TidyNet { /// <summary> /// Attribute/Value linked list node /// /// (c) 1998-2000 (W3C) MIT, INRIA, Keio University /// See Tidy.cs for the copyright notice. /// Derived from <a href="http://www.w3.org/People/Raggett/tidy"> /// HTML Tidy Release 4 Aug 2000</a> /// /// </summary> /// <author>Dave Raggett &lt;dsr@w3.org&gt;</author> /// <author>Andy Quick &lt;ac.quick@sympatico.ca&gt; (translation to Java)</author> /// <author>Seth Yates &lt;seth_yates@hotmail.com&gt; (translation to C#)</author> /// <version>1.0, 1999/05/22</version> /// <version>1.0.1, 1999/05/29</version> /// <version>1.1, 1999/06/18 Java Bean</version> /// <version>1.2, 1999/07/10 Tidy Release 7 Jul 1999</version> /// <version>1.3, 1999/07/30 Tidy Release 26 Jul 1999</version> /// <version>1.4, 1999/09/04 DOM support</version> /// <version>1.5, 1999/10/23 Tidy Release 27 Sep 1999</version> /// <version>1.6, 1999/11/01 Tidy Release 22 Oct 1999</version> /// <version>1.7, 1999/12/06 Tidy Release 30 Nov 1999</version> /// <version>1.8, 2000/01/22 Tidy Release 13 Jan 2000</version> /// <version>1.9, 2000/06/03 Tidy Release 30 Apr 2000</version> /// <version>1.10, 2000/07/22 Tidy Release 8 Jul 2000</version> /// <version>1.11, 2000/08/16 Tidy Release 4 Aug 2000</version> internal class AttVal : ICloneable { public AttVal() { _next = null; _dict = null; _asp = null; _php = null; _delim = 0; _attribute = null; _val = null; } public AttVal(AttVal next, Attribute dict, int delim, string attribute, string val) { _next = next; _dict = dict; _asp = null; _php = null; _delim = delim; _attribute = attribute; _val = val; } public AttVal(AttVal next, Attribute dict, Node asp, Node php, int delim, string attribute, string val) { _next = next; _dict = dict; _asp = asp; _php = php; _delim = delim; _attribute = attribute; _val = val; } virtual public bool BoolAttribute { get { Attribute attribute = _dict; if (attribute != null) { if (attribute.AttrCheck == AttrCheckImpl.CheckBool) { return true; } } return false; } } public AttVal Next { get { return _next; } set { _next = value; } } public Attribute Dict { get { return _dict; } set { _dict = value; } } public Node Asp { get { return _asp; } set { _asp = value; } } public Node Php { get { return _php; } set { _php = value; } } public int Delim { get { return _delim; } set { _delim = value; } } public string Attribute { get { return _attribute; } set { _attribute = value; } } public string Val { get { return _val; } set { _val = value; } } public object Clone() { AttVal av = new AttVal(); if (Next != null) { av.Next = (AttVal)Next.Clone(); } if (Attribute != null) { av.Attribute = Attribute; } if (Val != null) { av.Val = Val; } av.Delim = Delim; if (Asp != null) { av.Asp = (Node) Asp.Clone(); } if (Php != null) { av.Php = (Node) Php.Clone(); } av.Dict = AttributeTable.DefaultAttributeTable.FindAttribute(this); return av; } /* ignore unknown attributes for proprietary elements */ public virtual Attribute CheckAttribute(Lexer lexer, Node node) { TagTable tt = lexer.Options.tt; if (Asp == null && Php == null) { CheckUniqueAttribute(lexer, node); } Attribute attribute = Dict; if (attribute != null) { /* title is vers 2.0 for A and LINK otherwise vers 4.0 */ if (attribute == AttributeTable.AttrTitle && (node.Tag == tt.TagA || node.Tag == tt.TagLink)) { lexer.versions &= HtmlVersion.All; } else if ((attribute.Versions & HtmlVersion.Xml) != 0) { if (!(lexer.Options.XmlTags || lexer.Options.XmlOut)) { Report.AttrError(lexer, node, Attribute, Report.XML_ATTRIBUTE_VALUE); } } else { lexer.versions &= attribute.Versions; } if (attribute.AttrCheck != null) { attribute.AttrCheck.Check(lexer, node, this); } } else if (!lexer.Options.XmlTags && !(node.Tag == null) && _asp == null && !(node.Tag != null && ((node.Tag.Versions & HtmlVersion.Proprietary) != HtmlVersion.Unknown))) { Report.AttrError(lexer, node, Attribute, Report.UNKNOWN_ATTRIBUTE); } return attribute; } /* the same attribute name can't be used more than once in each element */ public virtual void CheckUniqueAttribute(Lexer lexer, Node node) { AttVal attr; int count = 0; for (attr = Next; attr != null; attr = attr.Next) { if (Attribute != null && attr.Attribute != null && attr.Asp == null && attr.Php == null && String.Compare(Attribute, attr.Attribute) == 0) { ++count; } } if (count > 0) { Report.AttrError(lexer, node, Attribute, Report.REPEATED_ATTRIBUTE); } } protected virtual internal IAttr Adapter { get { if (_adapter == null) { _adapter = new DomAttrImpl(this); } return _adapter; } set { _adapter = value; } } private IAttr _adapter = null; private AttVal _next; private Attribute _dict; private Node _asp; private Node _php; private int _delim; private string _attribute; private string _val; } }
// Copyright (c) 2011 Smarkets Limited // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, copy, // modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS // BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.IO; using ProtoBuf; using Seto = IronSmarkets.Proto.Seto; namespace IronSmarkets.Tests.Mocks { public class MockDocument<T> : IMockHttpDocument<T> { private readonly string _url; private readonly T _payload; public string Url { get { return _url; } } public T Payload { get { return _payload; } } internal MockDocument(string url, string base64) { _url = url; var ms = new MemoryStream(Convert.FromBase64String(base64)); _payload = Serializer.Deserialize<T>(ms); } } public static class MockUrls { public static readonly IMockHttpDocument<Seto.Events> Football20120221 = new MockDocument<Seto.Events>( "http://mock/api/events/sport/football/20120221/2.pb", "Cr8aCgQI2YkPEAEYASIdYm9sb2duYS1maW9yZW50aW5hLTIwMTItMDItMjEqFkJvbG9nbmEgdnMu" + "IEZpb3JlbnRpbmEyBAip4g06BwjcDxACGBVCBAgREB5KBwjcDxACGBVaCAoECPylAxAMWggKBAjk" + "8AcQA1oICgQI5vAHEAticwoECNisExIQCgQIwI4lEAUaAm5vIgJObxISCgQIv44lEAUaA3llcyID" + "WWVzGhZmaW9yZW50aW5hX2NsZWFuX3NoZWV0IiBGaW9yZW50aW5hIHRvIGtlZXAgYSBjbGVhbiBz" + "aGVldFILQk9MIHZzLiBGSU9itAEKBAjXrBMSLQoECL6OJRAFGgJubyIbRklPIHdvbid0IHNjb3Jl" + "IGJvdGggaGFsdmVzMgJObxIuCgQIvY4lEAUaA3llcyIaRklPIHdpbGwgc2NvcmUgYm90aCBoYWx2" + "ZXMyA1llcxocZmlvcmVudGluYV9zY29yZV9ib3RoX2hhbHZlcyIiRmlvcmVudGluYSB0byBzY29y" + "ZSBpbiBib3RoIGhhbHZlc1ILQk9MIHZzLiBGSU9ibQoECNasExIQCgQIvI4lEAUaAm5vIgJObxIS" + "CgQIu44lEAUaA3llcyIDWWVzGhNib2xvZ25hX2NsZWFuX3NoZWV0Ih1Cb2xvZ25hIHRvIGtlZXAg" + "YSBjbGVhbiBzaGVldFILQk9MIHZzLiBGSU9irgEKBAjVrBMSLQoECLqOJRAFGgJubyIbQk9MIHdv" + "bid0IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQIuY4lEAUaA3llcyIaQk9MIHdpbGwgc2NvcmUg" + "Ym90aCBoYWx2ZXMyA1llcxoZYm9sb2duYV9zY29yZV9ib3RoX2hhbHZlcyIfQm9sb2duYSB0byBz" + "Y29yZSBpbiBib3RoIGhhbHZlc1ILQk9MIHZzLiBGSU9ipQEKBAjUrBMSKAoECLiOJRAGGgRvdmVy" + "Ig5PdmVyIDYuNSBnb2FsczIIT3ZlciA2LjUSKwoECLeOJRAGGgV1bmRlciIPVW5kZXIgNi41IGdv" + "YWxzMglVbmRlciA2LjUaDm92ZXJfdW5kZXJfNl81IilPdmVyL3VuZGVyIDYuNSBmb3IgQm9sb2du" + "YSB2cy4gRmlvcmVudGluYVILQk9MIHZzLiBGSU9ipQEKBAjTrBMSKAoECLaOJRAGGgRvdmVyIg5P" + "dmVyIDUuNSBnb2FsczIIT3ZlciA1LjUSKwoECLWOJRAGGgV1bmRlciIPVW5kZXIgNS41IGdvYWxz" + "MglVbmRlciA1LjUaDm92ZXJfdW5kZXJfNV81IilPdmVyL3VuZGVyIDUuNSBmb3IgQm9sb2duYSB2" + "cy4gRmlvcmVudGluYVILQk9MIHZzLiBGSU9ipQEKBAjSrBMSKAoECLSOJRAGGgRvdmVyIg5PdmVy" + "IDQuNSBnb2FsczIIT3ZlciA0LjUSKwoECLOOJRAGGgV1bmRlciIPVW5kZXIgNC41IGdvYWxzMglV" + "bmRlciA0LjUaDm92ZXJfdW5kZXJfNF81IilPdmVyL3VuZGVyIDQuNSBmb3IgQm9sb2duYSB2cy4g" + "RmlvcmVudGluYVILQk9MIHZzLiBGSU9ipQEKBAjRrBMSKAoECLKOJRAGGgRvdmVyIg5PdmVyIDMu" + "NSBnb2FsczIIT3ZlciAzLjUSKwoECLGOJRAGGgV1bmRlciIPVW5kZXIgMy41IGdvYWxzMglVbmRl" + "ciAzLjUaDm92ZXJfdW5kZXJfM181IilPdmVyL3VuZGVyIDMuNSBmb3IgQm9sb2duYSB2cy4gRmlv" + "cmVudGluYVILQk9MIHZzLiBGSU9ipQEKBAjQrBMSKAoECLCOJRAGGgRvdmVyIg5PdmVyIDIuNSBn" + "b2FsczIIT3ZlciAyLjUSKwoECK+OJRAGGgV1bmRlciIPVW5kZXIgMi41IGdvYWxzMglVbmRlciAy" + "LjUaDm92ZXJfdW5kZXJfMl81IilPdmVyL3VuZGVyIDIuNSBmb3IgQm9sb2duYSB2cy4gRmlvcmVu" + "dGluYVILQk9MIHZzLiBGSU9ipQEKBAjPrBMSKAoECK6OJRAGGgRvdmVyIg5PdmVyIDEuNSBnb2Fs" + "czIIT3ZlciAxLjUSKwoECK2OJRAGGgV1bmRlciIPVW5kZXIgMS41IGdvYWxzMglVbmRlciAxLjUa" + "Dm92ZXJfdW5kZXJfMV81IilPdmVyL3VuZGVyIDEuNSBmb3IgQm9sb2duYSB2cy4gRmlvcmVudGlu" + "YVILQk9MIHZzLiBGSU9iwgIKBAjOrBMSKgoECKyOJRACGg9hbnktb3RoZXItc2NvcmUiD0FueSBv" + "dGhlciBzY29yZRIUCgQIq44lEAIaAzItMiIFMiAtIDISFAoECKqOJRACGgMyLTEiBTIgLSAxEhQK" + "BAipjiUQAhoDMi0wIgUyIC0gMBIUCgQIqI4lEAIaAzEtMiIFMSAtIDISFAoECKeOJRACGgMxLTEi" + "BTEgLSAxEhQKBAimjiUQAhoDMS0wIgUxIC0gMBIUCgQIpY4lEAIaAzAtMiIFMCAtIDISFAoECKSO" + "JRACGgMwLTEiBTAgLSAxEhQKBAijjiUQAhoDMC0wIgUwIC0gMBoPaGFsZl90aW1lX3Njb3JlIipI" + "YWxmIHRpbWUgc2NvcmUgZm9yIEJvbG9nbmEgdnMuIEZpb3JlbnRpbmFSC0JPTCB2cy4gRklPYp0B" + "CgQIzawTEhQKBAiijiUQBBoEZHJhdyIERHJhdxIaCgQIoY4lEAQaBGF3YXkiCkZpb3JlbnRpbmES" + "FwoECKCOJRAEGgRob21lIgdCb2xvZ25hGhBoYWxmX3RpbWVfcmVzdWx0IitIYWxmIHRpbWUgd2lu" + "bmVyIGZvciBCb2xvZ25hIHZzLiBGaW9yZW50aW5hUgtCT0wgdnMuIEZJT2JvCgQIzKwTEhAKBAif" + "jiUQBRoCbm8iAk5vEhIKBAiejiUQBRoDeWVzIgNZZXMaEGJvdGhfdGVhbXNfc2NvcmUiIkJvbG9n" + "bmEgdnMuIEZpb3JlbnRpbmE6IGJvdGggc2NvcmVSC0JPTCB2cy4gRklPYtgDCgQIy6wTEioKBAid" + "jiUQAhoPYW55LW90aGVyLXNjb3JlIg9Bbnkgb3RoZXIgc2NvcmUSFAoECJyOJRACGgMzLTMiBTMg" + "LSAzEhQKBAibjiUQAhoDMy0yIgUzIC0gMhIUCgQImo4lEAIaAzMtMSIFMyAtIDESFAoECJmOJRAC" + "GgMzLTAiBTMgLSAwEhQKBAiYjiUQAhoDMi0zIgUyIC0gMxIUCgQIl44lEAIaAzItMiIFMiAtIDIS" + "FAoECJaOJRACGgMyLTEiBTIgLSAxEhQKBAiVjiUQAhoDMi0wIgUyIC0gMBIUCgQIlI4lEAIaAzEt" + "MyIFMSAtIDMSFAoECJOOJRACGgMxLTIiBTEgLSAyEhQKBAiSjiUQAhoDMS0xIgUxIC0gMRIUCgQI" + "kY4lEAIaAzEtMCIFMSAtIDASFAoECJCOJRACGgMwLTMiBTAgLSAzEhQKBAiPjiUQAhoDMC0yIgUw" + "IC0gMhIUCgQIjo4lEAIaAzAtMSIFMCAtIDESFAoECI2OJRACGgMwLTAiBTAgLSAwGg1jb3JyZWN0" + "X3Njb3JlIihDb3JyZWN0IFNjb3JlIGZvciBCb2xvZ25hIHZzLiBGaW9yZW50aW5hUgtCT0wgdnMu" + "IEZJT2K+AwoECMqsExIgCgQIjI4lEAEaCWRyYXctZHJhdyILRHJhdyAvIERyYXcSJgoECIuOJRAB" + "GglkcmF3LWF3YXkiEURyYXcgLyBGaW9yZW50aW5hEiMKBAiKjiUQARoJZHJhdy1ob21lIg5EcmF3" + "IC8gQm9sb2duYRImCgQIiY4lEAEaCWF3YXktZHJhdyIRRmlvcmVudGluYSAvIERyYXcSLAoECIiO" + "JRABGglhd2F5LWF3YXkiF0Zpb3JlbnRpbmEgLyBGaW9yZW50aW5hEikKBAiHjiUQARoJYXdheS1o" + "b21lIhRGaW9yZW50aW5hIC8gQm9sb2duYRIjCgQIho4lEAEaCWhvbWUtZHJhdyIOQm9sb2duYSAv" + "IERyYXcSKQoECIWOJRABGglob21lLWF3YXkiFEJvbG9nbmEgLyBGaW9yZW50aW5hEiYKBAiEjiUQ" + "ARoJaG9tZS1ob21lIhFCb2xvZ25hIC8gQm9sb2duYRoJaGFsZl9mdWxsIjZIYWxmLXRpbWUvZnVs" + "bC10aW1lIHdpbm5lcnMgZm9yIEJvbG9nbmEgdnMuIEZpb3JlbnRpbmFSC0JPTCB2cy4gRklPYpEB" + "CgQIyawTEhQKBAiDjiUQBBoEZHJhdyIERHJhdxIgCgQIgo4lEAIaCmZpb3JlbnRpbmEiCkZpb3Jl" + "bnRpbmESGgoECIGOJRACGgdib2xvZ25hIgdCb2xvZ25hGgZ3aW5uZXIiIFdpbm5lciBvZiBCb2xv" + "Z25hIHZzLiBGaW9yZW50aW5hUgtCT0wgdnMuIEZJTxIeCgQIrbEHEAMYASIIZm9vdGJhbGwqCEZv" + "b3RiYWxsElQKBAip4g0QAhgBIhdpdGFseS1zZXJpZS1hLTIwMTEtMjAxMioXSXRhbHkgU2VyaWUg" + "QSAyMDExLTIwMTIyBAitsQc6BwjbDxAIGBtKBwjcDxAFGA0="); public static readonly IMockHttpDocument<Seto.Events> Football20120224 = new MockDocument<Seto.Events>( "http://mock/api/events/sport/football/20120224/2.pb", "CvUaCgQIwpEPEAEYASIfcmtjLXdhYWx3aWprLXZpdGVzc2UtMjAxMi0wMi0yNCoYUktDIFdhYWx3" + "aWprIHZzLiBWaXRlc3NlMgQIkOINOgcI3A8QAhgYQgQIExAASgcI3A8QAhgYWggKBAi+8AcQA1oI" + "CgQIzPAHEAtaCAoECM/wBxAMYm0KBAjorBMSEAoECICPJRAFGgJubyICTm8SEgoECP+OJRAFGgN5" + "ZXMiA1llcxoTdml0ZXNzZV9jbGVhbl9zaGVldCIdVml0ZXNzZSB0byBrZWVwIGEgY2xlYW4gc2hl" + "ZXRSC1JLQyB2cy4gVklUYq4BCgQI56wTEi0KBAj+jiUQBRoCbm8iG1ZJVCB3b24ndCBzY29yZSBi" + "b3RoIGhhbHZlczICTm8SLgoECP2OJRAFGgN5ZXMiGlZJVCB3aWxsIHNjb3JlIGJvdGggaGFsdmVz" + "MgNZZXMaGXZpdGVzc2Vfc2NvcmVfYm90aF9oYWx2ZXMiH1ZpdGVzc2UgdG8gc2NvcmUgaW4gYm90" + "aCBoYWx2ZXNSC1JLQyB2cy4gVklUYncKBAjmrBMSEAoECPyOJRAFGgJubyICTm8SEgoECPuOJRAF" + "GgN5ZXMiA1llcxoYcmtjLXdhYWx3aWprX2NsZWFuX3NoZWV0IiJSS0MgV2FhbHdpamsgdG8ga2Vl" + "cCBhIGNsZWFuIHNoZWV0UgtSS0MgdnMuIFZJVGK4AQoECOWsExItCgQI+o4lEAUaAm5vIhtSS0Mg" + "d29uJ3Qgc2NvcmUgYm90aCBoYWx2ZXMyAk5vEi4KBAj5jiUQBRoDeWVzIhpSS0Mgd2lsbCBzY29y" + "ZSBib3RoIGhhbHZlczIDWWVzGh5ya2Mtd2FhbHdpamtfc2NvcmVfYm90aF9oYWx2ZXMiJFJLQyBX" + "YWFsd2lqayB0byBzY29yZSBpbiBib3RoIGhhbHZlc1ILUktDIHZzLiBWSVRipwEKBAjkrBMSKAoE" + "CPiOJRAGGgRvdmVyIg5PdmVyIDYuNSBnb2FsczIIT3ZlciA2LjUSKwoECPeOJRAGGgV1bmRlciIP" + "VW5kZXIgNi41IGdvYWxzMglVbmRlciA2LjUaDm92ZXJfdW5kZXJfNl81IitPdmVyL3VuZGVyIDYu" + "NSBmb3IgUktDIFdhYWx3aWprIHZzLiBWaXRlc3NlUgtSS0MgdnMuIFZJVGKnAQoECOOsExIoCgQI" + "9o4lEAYaBG92ZXIiDk92ZXIgNS41IGdvYWxzMghPdmVyIDUuNRIrCgQI9Y4lEAYaBXVuZGVyIg9V" + "bmRlciA1LjUgZ29hbHMyCVVuZGVyIDUuNRoOb3Zlcl91bmRlcl81XzUiK092ZXIvdW5kZXIgNS41" + "IGZvciBSS0MgV2FhbHdpamsgdnMuIFZpdGVzc2VSC1JLQyB2cy4gVklUYqcBCgQI4qwTEigKBAj0" + "jiUQBhoEb3ZlciIOT3ZlciA0LjUgZ29hbHMyCE92ZXIgNC41EisKBAjzjiUQBhoFdW5kZXIiD1Vu" + "ZGVyIDQuNSBnb2FsczIJVW5kZXIgNC41Gg5vdmVyX3VuZGVyXzRfNSIrT3Zlci91bmRlciA0LjUg" + "Zm9yIFJLQyBXYWFsd2lqayB2cy4gVml0ZXNzZVILUktDIHZzLiBWSVRipwEKBAjhrBMSKAoECPKO" + "JRAGGgRvdmVyIg5PdmVyIDMuNSBnb2FsczIIT3ZlciAzLjUSKwoECPGOJRAGGgV1bmRlciIPVW5k" + "ZXIgMy41IGdvYWxzMglVbmRlciAzLjUaDm92ZXJfdW5kZXJfM181IitPdmVyL3VuZGVyIDMuNSBm" + "b3IgUktDIFdhYWx3aWprIHZzLiBWaXRlc3NlUgtSS0MgdnMuIFZJVGKnAQoECOCsExIoCgQI8I4l" + "EAYaBG92ZXIiDk92ZXIgMi41IGdvYWxzMghPdmVyIDIuNRIrCgQI744lEAYaBXVuZGVyIg9VbmRl" + "ciAyLjUgZ29hbHMyCVVuZGVyIDIuNRoOb3Zlcl91bmRlcl8yXzUiK092ZXIvdW5kZXIgMi41IGZv" + "ciBSS0MgV2FhbHdpamsgdnMuIFZpdGVzc2VSC1JLQyB2cy4gVklUYqcBCgQI36wTEigKBAjujiUQ" + "BhoEb3ZlciIOT3ZlciAxLjUgZ29hbHMyCE92ZXIgMS41EisKBAjtjiUQBhoFdW5kZXIiD1VuZGVy" + "IDEuNSBnb2FsczIJVW5kZXIgMS41Gg5vdmVyX3VuZGVyXzFfNSIrT3Zlci91bmRlciAxLjUgZm9y" + "IFJLQyBXYWFsd2lqayB2cy4gVml0ZXNzZVILUktDIHZzLiBWSVRixAIKBAjerBMSKgoECOyOJRAC" + "Gg9hbnktb3RoZXItc2NvcmUiD0FueSBvdGhlciBzY29yZRIUCgQI644lEAIaAzItMiIFMiAtIDIS" + "FAoECOqOJRACGgMyLTEiBTIgLSAxEhQKBAjpjiUQAhoDMi0wIgUyIC0gMBIUCgQI6I4lEAIaAzEt" + "MiIFMSAtIDISFAoECOeOJRACGgMxLTEiBTEgLSAxEhQKBAjmjiUQAhoDMS0wIgUxIC0gMBIUCgQI" + "5Y4lEAIaAzAtMiIFMCAtIDISFAoECOSOJRACGgMwLTEiBTAgLSAxEhQKBAjjjiUQAhoDMC0wIgUw" + "IC0gMBoPaGFsZl90aW1lX3Njb3JlIixIYWxmIHRpbWUgc2NvcmUgZm9yIFJLQyBXYWFsd2lqayB2" + "cy4gVml0ZXNzZVILUktDIHZzLiBWSVRioQEKBAjdrBMSFAoECOKOJRAEGgRkcmF3IgREcmF3EhcK" + "BAjhjiUQBBoEYXdheSIHVml0ZXNzZRIcCgQI4I4lEAQaBGhvbWUiDFJLQyBXYWFsd2lqaxoQaGFs" + "Zl90aW1lX3Jlc3VsdCItSGFsZiB0aW1lIHdpbm5lciBmb3IgUktDIFdhYWx3aWprIHZzLiBWaXRl" + "c3NlUgtSS0MgdnMuIFZJVGJxCgQI3KwTEhAKBAjfjiUQBRoCbm8iAk5vEhIKBAjejiUQBRoDeWVz" + "IgNZZXMaEGJvdGhfdGVhbXNfc2NvcmUiJFJLQyBXYWFsd2lqayB2cy4gVml0ZXNzZTogYm90aCBz" + "Y29yZVILUktDIHZzLiBWSVRi2gMKBAjbrBMSKgoECN2OJRACGg9hbnktb3RoZXItc2NvcmUiD0Fu" + "eSBvdGhlciBzY29yZRIUCgQI3I4lEAIaAzMtMyIFMyAtIDMSFAoECNuOJRACGgMzLTIiBTMgLSAy" + "EhQKBAjajiUQAhoDMy0xIgUzIC0gMRIUCgQI2Y4lEAIaAzMtMCIFMyAtIDASFAoECNiOJRACGgMy" + "LTMiBTIgLSAzEhQKBAjXjiUQAhoDMi0yIgUyIC0gMhIUCgQI1o4lEAIaAzItMSIFMiAtIDESFAoE" + "CNWOJRACGgMyLTAiBTIgLSAwEhQKBAjUjiUQAhoDMS0zIgUxIC0gMxIUCgQI044lEAIaAzEtMiIF" + "MSAtIDISFAoECNKOJRACGgMxLTEiBTEgLSAxEhQKBAjRjiUQAhoDMS0wIgUxIC0gMBIUCgQI0I4l" + "EAIaAzAtMyIFMCAtIDMSFAoECM+OJRACGgMwLTIiBTAgLSAyEhQKBAjOjiUQAhoDMC0xIgUwIC0g" + "MRIUCgQIzY4lEAIaAzAtMCIFMCAtIDAaDWNvcnJlY3Rfc2NvcmUiKkNvcnJlY3QgU2NvcmUgZm9y" + "IFJLQyBXYWFsd2lqayB2cy4gVml0ZXNzZVILUktDIHZzLiBWSVRizAMKBAjarBMSIAoECMyOJRAB" + "GglkcmF3LWRyYXciC0RyYXcgLyBEcmF3EiMKBAjLjiUQARoJZHJhdy1hd2F5Ig5EcmF3IC8gVml0" + "ZXNzZRIoCgQIyo4lEAEaCWRyYXctaG9tZSITRHJhdyAvIFJLQyBXYWFsd2lqaxIjCgQIyY4lEAEa" + "CWF3YXktZHJhdyIOVml0ZXNzZSAvIERyYXcSJgoECMiOJRABGglhd2F5LWF3YXkiEVZpdGVzc2Ug" + "LyBWaXRlc3NlEisKBAjHjiUQARoJYXdheS1ob21lIhZWaXRlc3NlIC8gUktDIFdhYWx3aWprEigK" + "BAjGjiUQARoJaG9tZS1kcmF3IhNSS0MgV2FhbHdpamsgLyBEcmF3EisKBAjFjiUQARoJaG9tZS1h" + "d2F5IhZSS0MgV2FhbHdpamsgLyBWaXRlc3NlEjAKBAjEjiUQARoJaG9tZS1ob21lIhtSS0MgV2Fh" + "bHdpamsgLyBSS0MgV2FhbHdpamsaCWhhbGZfZnVsbCI4SGFsZi10aW1lL2Z1bGwtdGltZSB3aW5u" + "ZXJzIGZvciBSS0MgV2FhbHdpamsgdnMuIFZpdGVzc2VSC1JLQyB2cy4gVklUYpcBCgQI2awTEhQK" + "BAjDjiUQBBoEZHJhdyIERHJhdxIaCgQIwo4lEAIaB3ZpdGVzc2UiB1ZpdGVzc2USJAoECMGOJRAC" + "Ggxya2Mtd2FhbHdpamsiDFJLQyBXYWFsd2lqaxoGd2lubmVyIiJXaW5uZXIgb2YgUktDIFdhYWx3" + "aWprIHZzLiBWaXRlc3NlUgtSS0MgdnMuIFZJVBIeCgQIrbEHEAMYASIIZm9vdGJhbGwqCEZvb3Ri" + "YWxsEmYKBAiQ4g0QAhgBIiBuZXRoZXJsYW5kcy1lcmVkaXZpc2llLTIwMTEtMjAxMiogTmV0aGVy" + "bGFuZHMgRXJlZGl2aXNpZSAyMDExLTIwMTIyBAitsQc6BwjbDxAIGAVKBwjcDxAFGB4="); public static readonly IMockHttpDocument<Seto.Events> Football20120225 = new MockDocument<Seto.Events>( "http://mock/api/events/sport/football/20120225/2.pb", "CqsbCgQIw5EPEAEYASIhbmFjLWJyZWRhLWFkby1kZW4taGFhZy0yMDEyLTAyLTI1KhpOQUMgQnJl" + "ZGEgdnMuIEFETyBEZW4gSGFhZzIECJDiDToHCNwPEAIYGUIECBEQLUoHCNwPEAIYGVoICgQIvvAH" + "EANaCAoECMLwBxAMWggKBAjL8AcQC2J3CgQI+KwTEhAKBAjAjyUQBRoCbm8iAk5vEhIKBAi/jyUQ" + "BRoDeWVzIgNZZXMaGGFkby1kZW4taGFhZ19jbGVhbl9zaGVldCIiQURPIERlbiBIYWFnIHRvIGtl" + "ZXAgYSBjbGVhbiBzaGVldFILTkFDIHZzLiBBRE9iuAEKBAj3rBMSLQoECL6PJRAFGgJubyIbQURP" + "IHdvbid0IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQIvY8lEAUaA3llcyIaQURPIHdpbGwgc2Nv" + "cmUgYm90aCBoYWx2ZXMyA1llcxoeYWRvLWRlbi1oYWFnX3Njb3JlX2JvdGhfaGFsdmVzIiRBRE8g" + "RGVuIEhhYWcgdG8gc2NvcmUgaW4gYm90aCBoYWx2ZXNSC05BQyB2cy4gQURPYnEKBAj2rBMSEAoE" + "CLyPJRAFGgJubyICTm8SEgoECLuPJRAFGgN5ZXMiA1llcxoVbmFjLWJyZWRhX2NsZWFuX3NoZWV0" + "Ih9OQUMgQnJlZGEgdG8ga2VlcCBhIGNsZWFuIHNoZWV0UgtOQUMgdnMuIEFET2KyAQoECPWsExIt" + "CgQIuo8lEAUaAm5vIhtOQUMgd29uJ3Qgc2NvcmUgYm90aCBoYWx2ZXMyAk5vEi4KBAi5jyUQBRoD" + "eWVzIhpOQUMgd2lsbCBzY29yZSBib3RoIGhhbHZlczIDWWVzGhtuYWMtYnJlZGFfc2NvcmVfYm90" + "aF9oYWx2ZXMiIU5BQyBCcmVkYSB0byBzY29yZSBpbiBib3RoIGhhbHZlc1ILTkFDIHZzLiBBRE9i" + "qQEKBAj0rBMSKAoECLiPJRAGGgRvdmVyIg5PdmVyIDYuNSBnb2FsczIIT3ZlciA2LjUSKwoECLeP" + "JRAGGgV1bmRlciIPVW5kZXIgNi41IGdvYWxzMglVbmRlciA2LjUaDm92ZXJfdW5kZXJfNl81Ii1P" + "dmVyL3VuZGVyIDYuNSBmb3IgTkFDIEJyZWRhIHZzLiBBRE8gRGVuIEhhYWdSC05BQyB2cy4gQURP" + "YqkBCgQI86wTEigKBAi2jyUQBhoEb3ZlciIOT3ZlciA1LjUgZ29hbHMyCE92ZXIgNS41EisKBAi1" + "jyUQBhoFdW5kZXIiD1VuZGVyIDUuNSBnb2FsczIJVW5kZXIgNS41Gg5vdmVyX3VuZGVyXzVfNSIt" + "T3Zlci91bmRlciA1LjUgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMuIEFE" + "T2KpAQoECPKsExIoCgQItI8lEAYaBG92ZXIiDk92ZXIgNC41IGdvYWxzMghPdmVyIDQuNRIrCgQI" + "s48lEAYaBXVuZGVyIg9VbmRlciA0LjUgZ29hbHMyCVVuZGVyIDQuNRoOb3Zlcl91bmRlcl80XzUi" + "LU92ZXIvdW5kZXIgNC41IGZvciBOQUMgQnJlZGEgdnMuIEFETyBEZW4gSGFhZ1ILTkFDIHZzLiBB" + "RE9iqQEKBAjxrBMSKAoECLKPJRAGGgRvdmVyIg5PdmVyIDMuNSBnb2FsczIIT3ZlciAzLjUSKwoE" + "CLGPJRAGGgV1bmRlciIPVW5kZXIgMy41IGdvYWxzMglVbmRlciAzLjUaDm92ZXJfdW5kZXJfM181" + "Ii1PdmVyL3VuZGVyIDMuNSBmb3IgTkFDIEJyZWRhIHZzLiBBRE8gRGVuIEhhYWdSC05BQyB2cy4g" + "QURPYqkBCgQI8KwTEigKBAiwjyUQBhoEb3ZlciIOT3ZlciAyLjUgZ29hbHMyCE92ZXIgMi41EisK" + "BAivjyUQBhoFdW5kZXIiD1VuZGVyIDIuNSBnb2FsczIJVW5kZXIgMi41Gg5vdmVyX3VuZGVyXzJf" + "NSItT3Zlci91bmRlciAyLjUgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMu" + "IEFET2KpAQoECO+sExIoCgQIro8lEAYaBG92ZXIiDk92ZXIgMS41IGdvYWxzMghPdmVyIDEuNRIr" + "CgQIrY8lEAYaBXVuZGVyIg9VbmRlciAxLjUgZ29hbHMyCVVuZGVyIDEuNRoOb3Zlcl91bmRlcl8x" + "XzUiLU92ZXIvdW5kZXIgMS41IGZvciBOQUMgQnJlZGEgdnMuIEFETyBEZW4gSGFhZ1ILTkFDIHZz" + "LiBBRE9ixgIKBAjurBMSKgoECKyPJRACGg9hbnktb3RoZXItc2NvcmUiD0FueSBvdGhlciBzY29y" + "ZRIUCgQIq48lEAIaAzItMiIFMiAtIDISFAoECKqPJRACGgMyLTEiBTIgLSAxEhQKBAipjyUQAhoD" + "Mi0wIgUyIC0gMBIUCgQIqI8lEAIaAzEtMiIFMSAtIDISFAoECKePJRACGgMxLTEiBTEgLSAxEhQK" + "BAimjyUQAhoDMS0wIgUxIC0gMBIUCgQIpY8lEAIaAzAtMiIFMCAtIDISFAoECKSPJRACGgMwLTEi" + "BTAgLSAxEhQKBAijjyUQAhoDMC0wIgUwIC0gMBoPaGFsZl90aW1lX3Njb3JlIi5IYWxmIHRpbWUg" + "c2NvcmUgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMuIEFET2KlAQoECO2s" + "ExIUCgQIoo8lEAQaBGRyYXciBERyYXcSHAoECKGPJRAEGgRhd2F5IgxBRE8gRGVuIEhhYWcSGQoE" + "CKCPJRAEGgRob21lIglOQUMgQnJlZGEaEGhhbGZfdGltZV9yZXN1bHQiL0hhbGYgdGltZSB3aW5u" + "ZXIgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMuIEFET2JzCgQI7KwTEhAK" + "BAifjyUQBRoCbm8iAk5vEhIKBAiejyUQBRoDeWVzIgNZZXMaEGJvdGhfdGVhbXNfc2NvcmUiJk5B" + "QyBCcmVkYSB2cy4gQURPIERlbiBIYWFnOiBib3RoIHNjb3JlUgtOQUMgdnMuIEFET2LcAwoECOus" + "ExIqCgQInY8lEAIaD2FueS1vdGhlci1zY29yZSIPQW55IG90aGVyIHNjb3JlEhQKBAicjyUQAhoD" + "My0zIgUzIC0gMxIUCgQIm48lEAIaAzMtMiIFMyAtIDISFAoECJqPJRACGgMzLTEiBTMgLSAxEhQK" + "BAiZjyUQAhoDMy0wIgUzIC0gMBIUCgQImI8lEAIaAzItMyIFMiAtIDMSFAoECJePJRACGgMyLTIi" + "BTIgLSAyEhQKBAiWjyUQAhoDMi0xIgUyIC0gMRIUCgQIlY8lEAIaAzItMCIFMiAtIDASFAoECJSP" + "JRACGgMxLTMiBTEgLSAzEhQKBAiTjyUQAhoDMS0yIgUxIC0gMhIUCgQIko8lEAIaAzEtMSIFMSAt" + "IDESFAoECJGPJRACGgMxLTAiBTEgLSAwEhQKBAiQjyUQAhoDMC0zIgUwIC0gMxIUCgQIj48lEAIa" + "AzAtMiIFMCAtIDISFAoECI6PJRACGgMwLTEiBTAgLSAxEhQKBAiNjyUQAhoDMC0wIgUwIC0gMBoN" + "Y29ycmVjdF9zY29yZSIsQ29ycmVjdCBTY29yZSBmb3IgTkFDIEJyZWRhIHZzLiBBRE8gRGVuIEhh" + "YWdSC05BQyB2cy4gQURPYtoDCgQI6qwTEiAKBAiMjyUQARoJZHJhdy1kcmF3IgtEcmF3IC8gRHJh" + "dxIoCgQIi48lEAEaCWRyYXctYXdheSITRHJhdyAvIEFETyBEZW4gSGFhZxIlCgQIio8lEAEaCWRy" + "YXctaG9tZSIQRHJhdyAvIE5BQyBCcmVkYRIoCgQIiY8lEAEaCWF3YXktZHJhdyITQURPIERlbiBI" + "YWFnIC8gRHJhdxIwCgQIiI8lEAEaCWF3YXktYXdheSIbQURPIERlbiBIYWFnIC8gQURPIERlbiBI" + "YWFnEi0KBAiHjyUQARoJYXdheS1ob21lIhhBRE8gRGVuIEhhYWcgLyBOQUMgQnJlZGESJQoECIaP" + "JRABGglob21lLWRyYXciEE5BQyBCcmVkYSAvIERyYXcSLQoECIWPJRABGglob21lLWF3YXkiGE5B" + "QyBCcmVkYSAvIEFETyBEZW4gSGFhZxIqCgQIhI8lEAEaCWhvbWUtaG9tZSIVTkFDIEJyZWRhIC8g" + "TkFDIEJyZWRhGgloYWxmX2Z1bGwiOkhhbGYtdGltZS9mdWxsLXRpbWUgd2lubmVycyBmb3IgTkFD" + "IEJyZWRhIHZzLiBBRE8gRGVuIEhhYWdSC05BQyB2cy4gQURPYp0BCgQI6awTEhQKBAiDjyUQBBoE" + "ZHJhdyIERHJhdxIkCgQIgo8lEAIaDGFkby1kZW4taGFhZyIMQURPIERlbiBIYWFnEh4KBAiBjyUQ" + "AhoJbmFjLWJyZWRhIglOQUMgQnJlZGEaBndpbm5lciIkV2lubmVyIG9mIE5BQyBCcmVkYSB2cy4g" + "QURPIERlbiBIYWFnUgtOQUMgdnMuIEFETwqcGQoECMSRDxABGAEiF3Z2di1oZXJhY2xlcy0yMDEy" + "LTAyLTI1KhBWVlYgdnMuIEhlcmFjbGVzMgQIkOINOgcI3A8QAhgZQgQIEhAtSgcI3A8QAhgZWggK" + "BAi+8AcQA1oICgQIv/AHEAxaCAoECMHwBxALYm8KBAiIrRMSEAoECICQJRAFGgJubyICTm8SEgoE" + "CP+PJRAFGgN5ZXMiA1llcxoUaGVyYWNsZXNfY2xlYW5fc2hlZXQiHkhlcmFjbGVzIHRvIGtlZXAg" + "YSBjbGVhbiBzaGVldFILVlZWIHZzLiBIRVJisAEKBAiHrRMSLQoECP6PJRAFGgJubyIbSEVSIHdv" + "bid0IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQI/Y8lEAUaA3llcyIaSEVSIHdpbGwgc2NvcmUg" + "Ym90aCBoYWx2ZXMyA1llcxoaaGVyYWNsZXNfc2NvcmVfYm90aF9oYWx2ZXMiIEhlcmFjbGVzIHRv" + "IHNjb3JlIGluIGJvdGggaGFsdmVzUgtWVlYgdnMuIEhFUmJlCgQIhq0TEhAKBAj8jyUQBRoCbm8i" + "Ak5vEhIKBAj7jyUQBRoDeWVzIgNZZXMaD3Z2dl9jbGVhbl9zaGVldCIZVlZWIHRvIGtlZXAgYSBj" + "bGVhbiBzaGVldFILVlZWIHZzLiBIRVJipgEKBAiFrRMSLQoECPqPJRAFGgJubyIbVlZWIHdvbid0" + "IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQI+Y8lEAUaA3llcyIaVlZWIHdpbGwgc2NvcmUgYm90" + "aCBoYWx2ZXMyA1llcxoVdnZ2X3Njb3JlX2JvdGhfaGFsdmVzIhtWVlYgdG8gc2NvcmUgaW4gYm90" + "aCBoYWx2ZXNSC1ZWViB2cy4gSEVSYp8BCgQIhK0TEigKBAj4jyUQBhoEb3ZlciIOT3ZlciA2LjUg" + "Z29hbHMyCE92ZXIgNi41EisKBAj3jyUQBhoFdW5kZXIiD1VuZGVyIDYuNSBnb2FsczIJVW5kZXIg" + "Ni41Gg5vdmVyX3VuZGVyXzZfNSIjT3Zlci91bmRlciA2LjUgZm9yIFZWViB2cy4gSGVyYWNsZXNS" + "C1ZWViB2cy4gSEVSYp8BCgQIg60TEigKBAj2jyUQBhoEb3ZlciIOT3ZlciA1LjUgZ29hbHMyCE92" + "ZXIgNS41EisKBAj1jyUQBhoFdW5kZXIiD1VuZGVyIDUuNSBnb2FsczIJVW5kZXIgNS41Gg5vdmVy" + "X3VuZGVyXzVfNSIjT3Zlci91bmRlciA1LjUgZm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4g" + "SEVSYp8BCgQIgq0TEigKBAj0jyUQBhoEb3ZlciIOT3ZlciA0LjUgZ29hbHMyCE92ZXIgNC41EisK" + "BAjzjyUQBhoFdW5kZXIiD1VuZGVyIDQuNSBnb2FsczIJVW5kZXIgNC41Gg5vdmVyX3VuZGVyXzRf" + "NSIjT3Zlci91bmRlciA0LjUgZm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYp8BCgQI" + "ga0TEigKBAjyjyUQBhoEb3ZlciIOT3ZlciAzLjUgZ29hbHMyCE92ZXIgMy41EisKBAjxjyUQBhoF" + "dW5kZXIiD1VuZGVyIDMuNSBnb2FsczIJVW5kZXIgMy41Gg5vdmVyX3VuZGVyXzNfNSIjT3Zlci91" + "bmRlciAzLjUgZm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYp8BCgQIgK0TEigKBAjw" + "jyUQBhoEb3ZlciIOT3ZlciAyLjUgZ29hbHMyCE92ZXIgMi41EisKBAjvjyUQBhoFdW5kZXIiD1Vu" + "ZGVyIDIuNSBnb2FsczIJVW5kZXIgMi41Gg5vdmVyX3VuZGVyXzJfNSIjT3Zlci91bmRlciAyLjUg" + "Zm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYp8BCgQI/6wTEigKBAjujyUQBhoEb3Zl" + "ciIOT3ZlciAxLjUgZ29hbHMyCE92ZXIgMS41EisKBAjtjyUQBhoFdW5kZXIiD1VuZGVyIDEuNSBn" + "b2FsczIJVW5kZXIgMS41Gg5vdmVyX3VuZGVyXzFfNSIjT3Zlci91bmRlciAxLjUgZm9yIFZWViB2" + "cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYrwCCgQI/qwTEioKBAjsjyUQAhoPYW55LW90aGVyLXNj" + "b3JlIg9Bbnkgb3RoZXIgc2NvcmUSFAoECOuPJRACGgMyLTIiBTIgLSAyEhQKBAjqjyUQAhoDMi0x" + "IgUyIC0gMRIUCgQI6Y8lEAIaAzItMCIFMiAtIDASFAoECOiPJRACGgMxLTIiBTEgLSAyEhQKBAjn" + "jyUQAhoDMS0xIgUxIC0gMRIUCgQI5o8lEAIaAzEtMCIFMSAtIDASFAoECOWPJRACGgMwLTIiBTAg" + "LSAyEhQKBAjkjyUQAhoDMC0xIgUwIC0gMRIUCgQI448lEAIaAzAtMCIFMCAtIDAaD2hhbGZfdGlt" + "ZV9zY29yZSIkSGFsZiB0aW1lIHNjb3JlIGZvciBWVlYgdnMuIEhlcmFjbGVzUgtWVlYgdnMuIEhF" + "UmKRAQoECP2sExIUCgQI4o8lEAQaBGRyYXciBERyYXcSGAoECOGPJRAEGgRhd2F5IghIZXJhY2xl" + "cxITCgQI4I8lEAQaBGhvbWUiA1ZWVhoQaGFsZl90aW1lX3Jlc3VsdCIlSGFsZiB0aW1lIHdpbm5l" + "ciBmb3IgVlZWIHZzLiBIZXJhY2xlc1ILVlZWIHZzLiBIRVJiaQoECPysExIQCgQI348lEAUaAm5v" + "IgJObxISCgQI3o8lEAUaA3llcyIDWWVzGhBib3RoX3RlYW1zX3Njb3JlIhxWVlYgdnMuIEhlcmFj" + "bGVzOiBib3RoIHNjb3JlUgtWVlYgdnMuIEhFUmLSAwoECPusExIqCgQI3Y8lEAIaD2FueS1vdGhl" + "ci1zY29yZSIPQW55IG90aGVyIHNjb3JlEhQKBAjcjyUQAhoDMy0zIgUzIC0gMxIUCgQI248lEAIa" + "AzMtMiIFMyAtIDISFAoECNqPJRACGgMzLTEiBTMgLSAxEhQKBAjZjyUQAhoDMy0wIgUzIC0gMBIU" + "CgQI2I8lEAIaAzItMyIFMiAtIDMSFAoECNePJRACGgMyLTIiBTIgLSAyEhQKBAjWjyUQAhoDMi0x" + "IgUyIC0gMRIUCgQI1Y8lEAIaAzItMCIFMiAtIDASFAoECNSPJRACGgMxLTMiBTEgLSAzEhQKBAjT" + "jyUQAhoDMS0yIgUxIC0gMhIUCgQI0o8lEAIaAzEtMSIFMSAtIDESFAoECNGPJRACGgMxLTAiBTEg" + "LSAwEhQKBAjQjyUQAhoDMC0zIgUwIC0gMxIUCgQIz48lEAIaAzAtMiIFMCAtIDISFAoECM6PJRAC" + "GgMwLTEiBTAgLSAxEhQKBAjNjyUQAhoDMC0wIgUwIC0gMBoNY29ycmVjdF9zY29yZSIiQ29ycmVj" + "dCBTY29yZSBmb3IgVlZWIHZzLiBIZXJhY2xlc1ILVlZWIHZzLiBIRVJilAMKBAj6rBMSIAoECMyP" + "JRABGglkcmF3LWRyYXciC0RyYXcgLyBEcmF3EiQKBAjLjyUQARoJZHJhdy1hd2F5Ig9EcmF3IC8g" + "SGVyYWNsZXMSHwoECMqPJRABGglkcmF3LWhvbWUiCkRyYXcgLyBWVlYSJAoECMmPJRABGglhd2F5" + "LWRyYXciD0hlcmFjbGVzIC8gRHJhdxIoCgQIyI8lEAEaCWF3YXktYXdheSITSGVyYWNsZXMgLyBI" + "ZXJhY2xlcxIjCgQIx48lEAEaCWF3YXktaG9tZSIOSGVyYWNsZXMgLyBWVlYSHwoECMaPJRABGglo" + "b21lLWRyYXciClZWViAvIERyYXcSIwoECMWPJRABGglob21lLWF3YXkiDlZWViAvIEhlcmFjbGVz" + "Eh4KBAjEjyUQARoJaG9tZS1ob21lIglWVlYgLyBWVlYaCWhhbGZfZnVsbCIwSGFsZi10aW1lL2Z1" + "bGwtdGltZSB3aW5uZXJzIGZvciBWVlYgdnMuIEhlcmFjbGVzUgtWVlYgdnMuIEhFUmJ/CgQI+awT" + "EhQKBAjDjyUQBBoEZHJhdyIERHJhdxIcCgQIwo8lEAIaCGhlcmFjbGVzIghIZXJhY2xlcxISCgQI" + "wY8lEAIaA3Z2diIDVlZWGgZ3aW5uZXIiGldpbm5lciBvZiBWVlYgdnMuIEhlcmFjbGVzUgtWVlYg" + "dnMuIEhFUhIeCgQIrbEHEAMYASIIZm9vdGJhbGwqCEZvb3RiYWxsEmYKBAiQ4g0QAhgBIiBuZXRo" + "ZXJsYW5kcy1lcmVkaXZpc2llLTIwMTEtMjAxMiogTmV0aGVybGFuZHMgRXJlZGl2aXNpZSAyMDEx" + "LTIwMTIyBAitsQc6BwjbDxAIGAVKBwjcDxAFGB4="); public static readonly IMockHttpDocument<Seto.Events> Football20120226 = new MockDocument<Seto.Events>( "http://mock/api/events/sport/football/20120226/1.pb", "CqsbCgQIw5EPEAEYASIhbmFjLWJyZWRhLWFkby1kZW4taGFhZy0yMDEyLTAyLTI1KhpOQUMgQnJl" + "ZGEgdnMuIEFETyBEZW4gSGFhZzIECJDiDToHCNwPEAIYGUIECBEQLUoHCNwPEAIYGVoICgQIvvAH" + "EANaCAoECMLwBxAMWggKBAjL8AcQC2J3CgQI+KwTEhAKBAjAjyUQBRoCbm8iAk5vEhIKBAi/jyUQ" + "BRoDeWVzIgNZZXMaGGFkby1kZW4taGFhZ19jbGVhbl9zaGVldCIiQURPIERlbiBIYWFnIHRvIGtl" + "ZXAgYSBjbGVhbiBzaGVldFILTkFDIHZzLiBBRE9iuAEKBAj3rBMSLQoECL6PJRAFGgJubyIbQURP" + "IHdvbid0IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQIvY8lEAUaA3llcyIaQURPIHdpbGwgc2Nv" + "cmUgYm90aCBoYWx2ZXMyA1llcxoeYWRvLWRlbi1oYWFnX3Njb3JlX2JvdGhfaGFsdmVzIiRBRE8g" + "RGVuIEhhYWcgdG8gc2NvcmUgaW4gYm90aCBoYWx2ZXNSC05BQyB2cy4gQURPYnEKBAj2rBMSEAoE" + "CLyPJRAFGgJubyICTm8SEgoECLuPJRAFGgN5ZXMiA1llcxoVbmFjLWJyZWRhX2NsZWFuX3NoZWV0" + "Ih9OQUMgQnJlZGEgdG8ga2VlcCBhIGNsZWFuIHNoZWV0UgtOQUMgdnMuIEFET2KyAQoECPWsExIt" + "CgQIuo8lEAUaAm5vIhtOQUMgd29uJ3Qgc2NvcmUgYm90aCBoYWx2ZXMyAk5vEi4KBAi5jyUQBRoD" + "eWVzIhpOQUMgd2lsbCBzY29yZSBib3RoIGhhbHZlczIDWWVzGhtuYWMtYnJlZGFfc2NvcmVfYm90" + "aF9oYWx2ZXMiIU5BQyBCcmVkYSB0byBzY29yZSBpbiBib3RoIGhhbHZlc1ILTkFDIHZzLiBBRE9i" + "qQEKBAj0rBMSKAoECLiPJRAGGgRvdmVyIg5PdmVyIDYuNSBnb2FsczIIT3ZlciA2LjUSKwoECLeP" + "JRAGGgV1bmRlciIPVW5kZXIgNi41IGdvYWxzMglVbmRlciA2LjUaDm92ZXJfdW5kZXJfNl81Ii1P" + "dmVyL3VuZGVyIDYuNSBmb3IgTkFDIEJyZWRhIHZzLiBBRE8gRGVuIEhhYWdSC05BQyB2cy4gQURP" + "YqkBCgQI86wTEigKBAi2jyUQBhoEb3ZlciIOT3ZlciA1LjUgZ29hbHMyCE92ZXIgNS41EisKBAi1" + "jyUQBhoFdW5kZXIiD1VuZGVyIDUuNSBnb2FsczIJVW5kZXIgNS41Gg5vdmVyX3VuZGVyXzVfNSIt" + "T3Zlci91bmRlciA1LjUgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMuIEFE" + "T2KpAQoECPKsExIoCgQItI8lEAYaBG92ZXIiDk92ZXIgNC41IGdvYWxzMghPdmVyIDQuNRIrCgQI" + "s48lEAYaBXVuZGVyIg9VbmRlciA0LjUgZ29hbHMyCVVuZGVyIDQuNRoOb3Zlcl91bmRlcl80XzUi" + "LU92ZXIvdW5kZXIgNC41IGZvciBOQUMgQnJlZGEgdnMuIEFETyBEZW4gSGFhZ1ILTkFDIHZzLiBB" + "RE9iqQEKBAjxrBMSKAoECLKPJRAGGgRvdmVyIg5PdmVyIDMuNSBnb2FsczIIT3ZlciAzLjUSKwoE" + "CLGPJRAGGgV1bmRlciIPVW5kZXIgMy41IGdvYWxzMglVbmRlciAzLjUaDm92ZXJfdW5kZXJfM181" + "Ii1PdmVyL3VuZGVyIDMuNSBmb3IgTkFDIEJyZWRhIHZzLiBBRE8gRGVuIEhhYWdSC05BQyB2cy4g" + "QURPYqkBCgQI8KwTEigKBAiwjyUQBhoEb3ZlciIOT3ZlciAyLjUgZ29hbHMyCE92ZXIgMi41EisK" + "BAivjyUQBhoFdW5kZXIiD1VuZGVyIDIuNSBnb2FsczIJVW5kZXIgMi41Gg5vdmVyX3VuZGVyXzJf" + "NSItT3Zlci91bmRlciAyLjUgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMu" + "IEFET2KpAQoECO+sExIoCgQIro8lEAYaBG92ZXIiDk92ZXIgMS41IGdvYWxzMghPdmVyIDEuNRIr" + "CgQIrY8lEAYaBXVuZGVyIg9VbmRlciAxLjUgZ29hbHMyCVVuZGVyIDEuNRoOb3Zlcl91bmRlcl8x" + "XzUiLU92ZXIvdW5kZXIgMS41IGZvciBOQUMgQnJlZGEgdnMuIEFETyBEZW4gSGFhZ1ILTkFDIHZz" + "LiBBRE9ixgIKBAjurBMSKgoECKyPJRACGg9hbnktb3RoZXItc2NvcmUiD0FueSBvdGhlciBzY29y" + "ZRIUCgQIq48lEAIaAzItMiIFMiAtIDISFAoECKqPJRACGgMyLTEiBTIgLSAxEhQKBAipjyUQAhoD" + "Mi0wIgUyIC0gMBIUCgQIqI8lEAIaAzEtMiIFMSAtIDISFAoECKePJRACGgMxLTEiBTEgLSAxEhQK" + "BAimjyUQAhoDMS0wIgUxIC0gMBIUCgQIpY8lEAIaAzAtMiIFMCAtIDISFAoECKSPJRACGgMwLTEi" + "BTAgLSAxEhQKBAijjyUQAhoDMC0wIgUwIC0gMBoPaGFsZl90aW1lX3Njb3JlIi5IYWxmIHRpbWUg" + "c2NvcmUgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMuIEFET2KlAQoECO2s" + "ExIUCgQIoo8lEAQaBGRyYXciBERyYXcSHAoECKGPJRAEGgRhd2F5IgxBRE8gRGVuIEhhYWcSGQoE" + "CKCPJRAEGgRob21lIglOQUMgQnJlZGEaEGhhbGZfdGltZV9yZXN1bHQiL0hhbGYgdGltZSB3aW5u" + "ZXIgZm9yIE5BQyBCcmVkYSB2cy4gQURPIERlbiBIYWFnUgtOQUMgdnMuIEFET2JzCgQI7KwTEhAK" + "BAifjyUQBRoCbm8iAk5vEhIKBAiejyUQBRoDeWVzIgNZZXMaEGJvdGhfdGVhbXNfc2NvcmUiJk5B" + "QyBCcmVkYSB2cy4gQURPIERlbiBIYWFnOiBib3RoIHNjb3JlUgtOQUMgdnMuIEFET2LcAwoECOus" + "ExIqCgQInY8lEAIaD2FueS1vdGhlci1zY29yZSIPQW55IG90aGVyIHNjb3JlEhQKBAicjyUQAhoD" + "My0zIgUzIC0gMxIUCgQIm48lEAIaAzMtMiIFMyAtIDISFAoECJqPJRACGgMzLTEiBTMgLSAxEhQK" + "BAiZjyUQAhoDMy0wIgUzIC0gMBIUCgQImI8lEAIaAzItMyIFMiAtIDMSFAoECJePJRACGgMyLTIi" + "BTIgLSAyEhQKBAiWjyUQAhoDMi0xIgUyIC0gMRIUCgQIlY8lEAIaAzItMCIFMiAtIDASFAoECJSP" + "JRACGgMxLTMiBTEgLSAzEhQKBAiTjyUQAhoDMS0yIgUxIC0gMhIUCgQIko8lEAIaAzEtMSIFMSAt" + "IDESFAoECJGPJRACGgMxLTAiBTEgLSAwEhQKBAiQjyUQAhoDMC0zIgUwIC0gMxIUCgQIj48lEAIa" + "AzAtMiIFMCAtIDISFAoECI6PJRACGgMwLTEiBTAgLSAxEhQKBAiNjyUQAhoDMC0wIgUwIC0gMBoN" + "Y29ycmVjdF9zY29yZSIsQ29ycmVjdCBTY29yZSBmb3IgTkFDIEJyZWRhIHZzLiBBRE8gRGVuIEhh" + "YWdSC05BQyB2cy4gQURPYtoDCgQI6qwTEiAKBAiMjyUQARoJZHJhdy1kcmF3IgtEcmF3IC8gRHJh" + "dxIoCgQIi48lEAEaCWRyYXctYXdheSITRHJhdyAvIEFETyBEZW4gSGFhZxIlCgQIio8lEAEaCWRy" + "YXctaG9tZSIQRHJhdyAvIE5BQyBCcmVkYRIoCgQIiY8lEAEaCWF3YXktZHJhdyITQURPIERlbiBI" + "YWFnIC8gRHJhdxIwCgQIiI8lEAEaCWF3YXktYXdheSIbQURPIERlbiBIYWFnIC8gQURPIERlbiBI" + "YWFnEi0KBAiHjyUQARoJYXdheS1ob21lIhhBRE8gRGVuIEhhYWcgLyBOQUMgQnJlZGESJQoECIaP" + "JRABGglob21lLWRyYXciEE5BQyBCcmVkYSAvIERyYXcSLQoECIWPJRABGglob21lLWF3YXkiGE5B" + "QyBCcmVkYSAvIEFETyBEZW4gSGFhZxIqCgQIhI8lEAEaCWhvbWUtaG9tZSIVTkFDIEJyZWRhIC8g" + "TkFDIEJyZWRhGgloYWxmX2Z1bGwiOkhhbGYtdGltZS9mdWxsLXRpbWUgd2lubmVycyBmb3IgTkFD" + "IEJyZWRhIHZzLiBBRE8gRGVuIEhhYWdSC05BQyB2cy4gQURPYp0BCgQI6awTEhQKBAiDjyUQBBoE" + "ZHJhdyIERHJhdxIkCgQIgo8lEAIaDGFkby1kZW4taGFhZyIMQURPIERlbiBIYWFnEh4KBAiBjyUQ" + "AhoJbmFjLWJyZWRhIglOQUMgQnJlZGEaBndpbm5lciIkV2lubmVyIG9mIE5BQyBCcmVkYSB2cy4g" + "QURPIERlbiBIYWFnUgtOQUMgdnMuIEFETwqcGQoECMSRDxABGAEiF3Z2di1oZXJhY2xlcy0yMDEy" + "LTAyLTI1KhBWVlYgdnMuIEhlcmFjbGVzMgQIkOINOgcI3A8QAhgZQgQIEhAtSgcI3A8QAhgZWggK" + "BAi+8AcQA1oICgQIv/AHEAxaCAoECMHwBxALYm8KBAiIrRMSEAoECICQJRAFGgJubyICTm8SEgoE" + "CP+PJRAFGgN5ZXMiA1llcxoUaGVyYWNsZXNfY2xlYW5fc2hlZXQiHkhlcmFjbGVzIHRvIGtlZXAg" + "YSBjbGVhbiBzaGVldFILVlZWIHZzLiBIRVJisAEKBAiHrRMSLQoECP6PJRAFGgJubyIbSEVSIHdv" + "bid0IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQI/Y8lEAUaA3llcyIaSEVSIHdpbGwgc2NvcmUg" + "Ym90aCBoYWx2ZXMyA1llcxoaaGVyYWNsZXNfc2NvcmVfYm90aF9oYWx2ZXMiIEhlcmFjbGVzIHRv" + "IHNjb3JlIGluIGJvdGggaGFsdmVzUgtWVlYgdnMuIEhFUmJlCgQIhq0TEhAKBAj8jyUQBRoCbm8i" + "Ak5vEhIKBAj7jyUQBRoDeWVzIgNZZXMaD3Z2dl9jbGVhbl9zaGVldCIZVlZWIHRvIGtlZXAgYSBj" + "bGVhbiBzaGVldFILVlZWIHZzLiBIRVJipgEKBAiFrRMSLQoECPqPJRAFGgJubyIbVlZWIHdvbid0" + "IHNjb3JlIGJvdGggaGFsdmVzMgJObxIuCgQI+Y8lEAUaA3llcyIaVlZWIHdpbGwgc2NvcmUgYm90" + "aCBoYWx2ZXMyA1llcxoVdnZ2X3Njb3JlX2JvdGhfaGFsdmVzIhtWVlYgdG8gc2NvcmUgaW4gYm90" + "aCBoYWx2ZXNSC1ZWViB2cy4gSEVSYp8BCgQIhK0TEigKBAj4jyUQBhoEb3ZlciIOT3ZlciA2LjUg" + "Z29hbHMyCE92ZXIgNi41EisKBAj3jyUQBhoFdW5kZXIiD1VuZGVyIDYuNSBnb2FsczIJVW5kZXIg" + "Ni41Gg5vdmVyX3VuZGVyXzZfNSIjT3Zlci91bmRlciA2LjUgZm9yIFZWViB2cy4gSGVyYWNsZXNS" + "C1ZWViB2cy4gSEVSYp8BCgQIg60TEigKBAj2jyUQBhoEb3ZlciIOT3ZlciA1LjUgZ29hbHMyCE92" + "ZXIgNS41EisKBAj1jyUQBhoFdW5kZXIiD1VuZGVyIDUuNSBnb2FsczIJVW5kZXIgNS41Gg5vdmVy" + "X3VuZGVyXzVfNSIjT3Zlci91bmRlciA1LjUgZm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4g" + "SEVSYp8BCgQIgq0TEigKBAj0jyUQBhoEb3ZlciIOT3ZlciA0LjUgZ29hbHMyCE92ZXIgNC41EisK" + "BAjzjyUQBhoFdW5kZXIiD1VuZGVyIDQuNSBnb2FsczIJVW5kZXIgNC41Gg5vdmVyX3VuZGVyXzRf" + "NSIjT3Zlci91bmRlciA0LjUgZm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYp8BCgQI" + "ga0TEigKBAjyjyUQBhoEb3ZlciIOT3ZlciAzLjUgZ29hbHMyCE92ZXIgMy41EisKBAjxjyUQBhoF" + "dW5kZXIiD1VuZGVyIDMuNSBnb2FsczIJVW5kZXIgMy41Gg5vdmVyX3VuZGVyXzNfNSIjT3Zlci91" + "bmRlciAzLjUgZm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYp8BCgQIgK0TEigKBAjw" + "jyUQBhoEb3ZlciIOT3ZlciAyLjUgZ29hbHMyCE92ZXIgMi41EisKBAjvjyUQBhoFdW5kZXIiD1Vu" + "ZGVyIDIuNSBnb2FsczIJVW5kZXIgMi41Gg5vdmVyX3VuZGVyXzJfNSIjT3Zlci91bmRlciAyLjUg" + "Zm9yIFZWViB2cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYp8BCgQI/6wTEigKBAjujyUQBhoEb3Zl" + "ciIOT3ZlciAxLjUgZ29hbHMyCE92ZXIgMS41EisKBAjtjyUQBhoFdW5kZXIiD1VuZGVyIDEuNSBn" + "b2FsczIJVW5kZXIgMS41Gg5vdmVyX3VuZGVyXzFfNSIjT3Zlci91bmRlciAxLjUgZm9yIFZWViB2" + "cy4gSGVyYWNsZXNSC1ZWViB2cy4gSEVSYrwCCgQI/qwTEioKBAjsjyUQAhoPYW55LW90aGVyLXNj" + "b3JlIg9Bbnkgb3RoZXIgc2NvcmUSFAoECOuPJRACGgMyLTIiBTIgLSAyEhQKBAjqjyUQAhoDMi0x" + "IgUyIC0gMRIUCgQI6Y8lEAIaAzItMCIFMiAtIDASFAoECOiPJRACGgMxLTIiBTEgLSAyEhQKBAjn" + "jyUQAhoDMS0xIgUxIC0gMRIUCgQI5o8lEAIaAzEtMCIFMSAtIDASFAoECOWPJRACGgMwLTIiBTAg" + "LSAyEhQKBAjkjyUQAhoDMC0xIgUwIC0gMRIUCgQI448lEAIaAzAtMCIFMCAtIDAaD2hhbGZfdGlt" + "ZV9zY29yZSIkSGFsZiB0aW1lIHNjb3JlIGZvciBWVlYgdnMuIEhlcmFjbGVzUgtWVlYgdnMuIEhF" + "UmKRAQoECP2sExIUCgQI4o8lEAQaBGRyYXciBERyYXcSGAoECOGPJRAEGgRhd2F5IghIZXJhY2xl" + "cxITCgQI4I8lEAQaBGhvbWUiA1ZWVhoQaGFsZl90aW1lX3Jlc3VsdCIlSGFsZiB0aW1lIHdpbm5l" + "ciBmb3IgVlZWIHZzLiBIZXJhY2xlc1ILVlZWIHZzLiBIRVJiaQoECPysExIQCgQI348lEAUaAm5v" + "IgJObxISCgQI3o8lEAUaA3llcyIDWWVzGhBib3RoX3RlYW1zX3Njb3JlIhxWVlYgdnMuIEhlcmFj" + "bGVzOiBib3RoIHNjb3JlUgtWVlYgdnMuIEhFUmLSAwoECPusExIqCgQI3Y8lEAIaD2FueS1vdGhl" + "ci1zY29yZSIPQW55IG90aGVyIHNjb3JlEhQKBAjcjyUQAhoDMy0zIgUzIC0gMxIUCgQI248lEAIa" + "AzMtMiIFMyAtIDISFAoECNqPJRACGgMzLTEiBTMgLSAxEhQKBAjZjyUQAhoDMy0wIgUzIC0gMBIU" + "CgQI2I8lEAIaAzItMyIFMiAtIDMSFAoECNePJRACGgMyLTIiBTIgLSAyEhQKBAjWjyUQAhoDMi0x" + "IgUyIC0gMRIUCgQI1Y8lEAIaAzItMCIFMiAtIDASFAoECNSPJRACGgMxLTMiBTEgLSAzEhQKBAjT" + "jyUQAhoDMS0yIgUxIC0gMhIUCgQI0o8lEAIaAzEtMSIFMSAtIDESFAoECNGPJRACGgMxLTAiBTEg" + "LSAwEhQKBAjQjyUQAhoDMC0zIgUwIC0gMxIUCgQIz48lEAIaAzAtMiIFMCAtIDISFAoECM6PJRAC" + "GgMwLTEiBTAgLSAxEhQKBAjNjyUQAhoDMC0wIgUwIC0gMBoNY29ycmVjdF9zY29yZSIiQ29ycmVj" + "dCBTY29yZSBmb3IgVlZWIHZzLiBIZXJhY2xlc1ILVlZWIHZzLiBIRVJilAMKBAj6rBMSIAoECMyP" + "JRABGglkcmF3LWRyYXciC0RyYXcgLyBEcmF3EiQKBAjLjyUQARoJZHJhdy1hd2F5Ig9EcmF3IC8g" + "SGVyYWNsZXMSHwoECMqPJRABGglkcmF3LWhvbWUiCkRyYXcgLyBWVlYSJAoECMmPJRABGglhd2F5" + "LWRyYXciD0hlcmFjbGVzIC8gRHJhdxIoCgQIyI8lEAEaCWF3YXktYXdheSITSGVyYWNsZXMgLyBI" + "ZXJhY2xlcxIjCgQIx48lEAEaCWF3YXktaG9tZSIOSGVyYWNsZXMgLyBWVlYSHwoECMaPJRABGglo" + "b21lLWRyYXciClZWViAvIERyYXcSIwoECMWPJRABGglob21lLWF3YXkiDlZWViAvIEhlcmFjbGVz" + "Eh4KBAjEjyUQARoJaG9tZS1ob21lIglWVlYgLyBWVlYaCWhhbGZfZnVsbCIwSGFsZi10aW1lL2Z1" + "bGwtdGltZSB3aW5uZXJzIGZvciBWVlYgdnMuIEhlcmFjbGVzUgtWVlYgdnMuIEhFUmJ/CgQI+awT" + "EhQKBAjDjyUQBBoEZHJhdyIERHJhdxIcCgQIwo8lEAIaCGhlcmFjbGVzIghIZXJhY2xlcxISCgQI" + "wY8lEAIaA3Z2diIDVlZWGgZ3aW5uZXIiGldpbm5lciBvZiBWVlYgdnMuIEhlcmFjbGVzUgtWVlYg" + "dnMuIEhFUhIeCgQIrbEHEAMYASIIZm9vdGJhbGwqCEZvb3RiYWxsEmYKBAiQ4g0QAhgBIiBuZXRo" + "ZXJsYW5kcy1lcmVkaXZpc2llLTIwMTEtMjAxMiogTmV0aGVybGFuZHMgRXJlZGl2aXNpZSAyMDEx" + "LTIwMTIyBAitsQc6BwjbDxAIGAVKBwjcDxAFGB4="); } }
// 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 OLEDB.Test.ModuleCore; namespace System.Xml.Tests { internal class VerifyNameTests4 : CTestCase { public override void AddChildren() { AddChild(new CVariation(TFS_469847) { Attribute = new Variation("Test for VerifyNMTOKEN(foo\U00010000bar)") { Param = 1 } }); AddChild(new CVariation(TFS_469847) { Attribute = new Variation("Test for VerifyNCName(foo\U00010000bar)") { Param = 3 } }); AddChild(new CVariation(TFS_469847) { Attribute = new Variation("Test for VerifyTOKEN(foo\U00010000bar)") { Param = 4 } }); AddChild(new CVariation(TFS_469847) { Attribute = new Variation("Test for VerifyXmlChars(foo\U00010000bar)") { Param = 5 } }); AddChild(new CVariation(TFS_469847) { Attribute = new Variation("Test for VerifyName(foo\U00010000bar)") { Param = 2 } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("9.Test for VerifyXmlChars(a\udfff\udbffb)") { Params = new object[] { 9, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("5.Test for VerifyXmlChars(a\udbff\udfffb)") { Params = new object[] { 5, null } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("8.Test for VerifyXmlChars(abcddcba\udbff\udfff)") { Params = new object[] { 8, null } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("1.Test for VerifyXmlChars(null)") { Params = new object[] { 1, typeof(ArgumentNullException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("10.Test for VerifyXmlChars(a\udfffb)") { Params = new object[] { 10, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("11.Test for VerifyXmlChars(a\udbffb)") { Params = new object[] { 11, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("12.Test for VerifyXmlChars(abcd\udbff \udfffdcba)") { Params = new object[] { 12, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("13.Test for VerifyXmlChars(\uffffabcd\ud801\udc01dcba)") { Params = new object[] { 13, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("14.Test for VerifyXmlChars(abcd\uffff\ud801\udc01dcba)") { Params = new object[] { 14, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("15.Test for VerifyXmlChars(abcd\ud801\udc01dcba\uffff)") { Params = new object[] { 15, typeof(XmlException) } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("6.Test for VerifyXmlChars(abcd\udbff\udfffdcba)") { Params = new object[] { 6, null } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("7.Test for VerifyXmlChars(\udbff\udfffabcddcba)") { Params = new object[] { 7, null } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("2.Test for VerifyXmlChars(string.Empty)") { Params = new object[] { 2, null } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("3.Test for VerifyXmlChars(a)") { Params = new object[] { 3, null } } }); AddChild(new CVariation(VerifyXmlCharsTests) { Attribute = new Variation("4.Test for VerifyXmlChars(ab)") { Params = new object[] { 4, null } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (null)") { Params = new object[] { null, typeof(ArgumentNullException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (string.Empty)") { Params = new object[] { "", null } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (!)") { Params = new object[] { "!", null } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (ab)") { Params = new object[] { "ab", null } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (+,./)") { Params = new object[] { "+,./", null } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (a-zA-Z0-9-'( )+,./:=?;!*#\n@$_%\\r)") { Params = new object[] { "a-zA-Z0-9-'( )+,./:=?;!*#\n@$_%\r", null } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (\\udb01\\udc01abc)") { Params = new object[] { "\udb01\udc01abc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (a\\udb01\\udc01bc)") { Params = new object[] { "a\udb01\udc01bc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (abc\\udb01\\udc01)") { Params = new object[] { "abc\udb01\udc01", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (\\udb01abc)") { Params = new object[] { "\udb01abc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (a\\udb01abc)") { Params = new object[] { "a\udb01abc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (abc\\udb01)") { Params = new object[] { "abc\udb01", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (\\udf01abc)") { Params = new object[] { "\udf01abc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (a\\udf01abc)") { Params = new object[] { "a\udf01abc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (abc\\udf01)") { Params = new object[] { "abc\udf01", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (\\uffffabc)") { Params = new object[] { "\uffffabc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (a\\uffffabc)") { Params = new object[] { "a\uffffabc", typeof(XmlException) } } }); AddChild(new CVariation(VerifyPublicId) { Attribute = new Variation("Test for VerifyPublicId (abc\\uffff)") { Params = new object[] { "abc\uffff", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\t\t)") { Params = new object[] { "\t\t", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace( )") { Params = new object[] { " ", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\n)") { Params = new object[] { "\n\n", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\r\r)") { Params = new object[] { "\r\r", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(null)") { Params = new object[] { null, typeof(ArgumentNullException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace( )") { Params = new object[] { " ", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\n\n)") { Params = new object[] { "\n\n\n", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\r\r\r)") { Params = new object[] { "\r\r\r", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\t\t\t)") { Params = new object[] { "\t\t\t", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace( )") { Params = new object[] { " ", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\n\n\n)") { Params = new object[] { "\n\n\n\n", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\r\r\r\r)") { Params = new object[] { "\r\r\r\r", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\t\t\t\t)") { Params = new object[] { "\t\t\t\t", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t\n)") { Params = new object[] { "\n\r\t\n", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t )") { Params = new object[] { "\n\r\t ", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(a\n\r\t\n)") { Params = new object[] { "a\n\r\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t\na)") { Params = new object[] { "\n\r\t\na", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\rb\t\n)") { Params = new object[] { "\n\rb\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\ud801\udc01\n\r\t\n)") { Params = new object[] { "\ud801\udc01\n\r\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t\n\ud801\udc01)") { Params = new object[] { "\n\r\t\n\ud801\udc01", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\\n\\r\\ud801\\udc01\\t\\n)") { Params = new object[] { "\n\r\ud801\udc01\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\\udc01\\ud801\\n\\r\\t\\n)") { Params = new object[] { "\ufffd\ufffd\ufffd\ufffd\n\r\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\\n\\r\\t\\n\\udc01\\ud801)") { Params = new object[] { "\n\r\t\n\ufffd\ufffd\ufffd\ufffd", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\\n\\r\\udc01\\ud801\\t\n)") { Params = new object[] { "\n\r\ufffd\ufffd\ufffd\ufffd\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\ud801\n\r\t\n)") { Params = new object[] { "\ufffd\ufffd\n\r\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t\n\udc01)") { Params = new object[] { "\n\r\t\n\ufffd\ufffd", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\ud801\t\n)") { Params = new object[] { "\n\r\ufffd\ufffd\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\t)") { Params = new object[] { "\t", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t\n\udc01)") { Params = new object[] { "\n\r\t\n\ufffd\ufffd", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\udc01\t\n)") { Params = new object[] { "\n\r\ufffd\ufffd\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\uffff\n\r\t\n)") { Params = new object[] { "\uffff\n\r\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\t\n\uffff)") { Params = new object[] { "\n\r\t\n\uffff", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n\r\uffff\t\n)") { Params = new object[] { "\n\r\uffff\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(string.Empty)") { Params = new object[] { "", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\udc01\n\r\t\n)") { Params = new object[] { "\ufffd\ufffd\n\r\t\n", typeof(XmlException) } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace( )") { Params = new object[] { " ", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\n)") { Params = new object[] { "\n", null } } }); AddChild(new CVariation(VerifyWhitespace) { Attribute = new Variation("Test for VerifyWhitespace(\r)") { Params = new object[] { "\r", null } } }); } private int TFS_469847() { var param = (int)CurVariation.Param; try { switch (param) { case 1: XmlConvert.VerifyNMTOKEN("foo\ud800\udc00bar"); break; case 2: XmlConvert.VerifyName("foo\ud800\udc00bar"); break; case 3: XmlConvert.VerifyNCName("foo\ud800\udc00bar"); break; case 5: XmlConvert.VerifyXmlChars("foo\ud800\udc00bar"); break; } } catch (XmlException e) { CError.WriteLine(e.Message); return TEST_PASS; } return (param == 4 || param == 5) ? TEST_PASS : TEST_FAIL; } private int VerifyPublicId() { var inputString = (string)CurVariation.Params[0]; var exceptionType = (Type)CurVariation.Params[1]; try { string outString = XmlConvert.VerifyPublicId(inputString); CError.Compare(inputString, outString, "Content"); } catch (ArgumentNullException e) { return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } catch (XmlException e) { CError.WriteLine(e.LineNumber); CError.WriteLine(e.LinePosition); return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } return exceptionType == null ? TEST_PASS : TEST_FAIL; } /// <summary> /// Params[] = { inputString, shouldThrow } /// </summary> private int VerifyWhitespace() { var inputString = (string)CurVariation.Params[0]; var exceptionType = (Type)CurVariation.Params[1]; try { string outString = XmlConvert.VerifyWhitespace(inputString); CError.Compare(inputString, outString, "Content"); } catch (ArgumentNullException e) { return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } catch (XmlException e) { CError.WriteLine(e.LineNumber); CError.WriteLine(e.LinePosition); return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } return exceptionType == null ? TEST_PASS : TEST_FAIL; } private int VerifyXmlCharsTests() { var param = (int)CurVariation.Params[0]; var exceptionType = (Type)CurVariation.Params[1]; string inputString = String.Empty; switch (param) { case 1: inputString = null; break; case 2: inputString = ""; break; case 3: inputString = "a"; break; case 4: inputString = "ab"; break; case 5: inputString = "a\udbff\udfffb"; break; case 6: inputString = "abcd\udbff\udfffdcba"; break; case 7: inputString = "\udbff\udfffabcddcba"; break; case 8: inputString = "abcddcba\udbff\udfff"; break; case 9: inputString = "a\udfff\udbffb"; break; case 10: inputString = "a\udfffb"; break; case 11: inputString = "a\udbffb"; break; case 12: inputString = "abcd\udbff \udfffdcba"; break; case 13: inputString = "\uffffabcd\ud801\udc01dcba"; break; case 14: inputString = "abcd\uffff\ud801\udc01dcba"; break; case 15: inputString = "abcd\ud801\udc01dcba\uffff"; break; } try { string outString = XmlConvert.VerifyXmlChars(inputString); CError.Compare(inputString, outString, "Content"); } catch (ArgumentNullException e) { return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } catch (XmlException e) { CError.WriteLine(e.LineNumber); CError.WriteLine(e.LinePosition); return (exceptionType != null && e.GetType().Name == exceptionType.Name) ? TEST_PASS : TEST_FAIL; } return exceptionType == null ? TEST_PASS : TEST_FAIL; } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Classification; using Microsoft.CodeAnalysis.DocumentationCommentFormatting; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.LanguageServices { internal partial class AbstractSymbolDisplayService { protected abstract partial class AbstractSymbolDescriptionBuilder { private static readonly SymbolDisplayFormat s_typeParameterOwnerFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, parameterOptions: SymbolDisplayParameterOptions.None, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_memberSignatureDisplayFormat = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints, memberOptions: SymbolDisplayMemberOptions.IncludeParameters | SymbolDisplayMemberOptions.IncludeType | SymbolDisplayMemberOptions.IncludeContainingType, kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword, propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor, parameterOptions: SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeParamsRefOut | SymbolDisplayParameterOptions.IncludeExtensionThis | SymbolDisplayParameterOptions.IncludeDefaultValue | SymbolDisplayParameterOptions.IncludeOptionalBrackets, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.UseSpecialTypes | SymbolDisplayMiscellaneousOptions.UseErrorTypeSymbolName); private static readonly SymbolDisplayFormat s_descriptionStyle = new SymbolDisplayFormat( typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces, delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeVariance | SymbolDisplayGenericsOptions.IncludeTypeConstraints, parameterOptions: SymbolDisplayParameterOptions.IncludeType | SymbolDisplayParameterOptions.IncludeName | SymbolDisplayParameterOptions.IncludeParamsRefOut, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers, kindOptions: SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword); private static readonly SymbolDisplayFormat s_globalNamespaceStyle = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included); private readonly ISymbolDisplayService _displayService; private readonly SemanticModel _semanticModel; private readonly int _position; private readonly IAnonymousTypeDisplayService _anonymousTypeDisplayService; private readonly Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>> _groupMap = new Dictionary<SymbolDescriptionGroups, IList<SymbolDisplayPart>>(); protected readonly Workspace Workspace; protected readonly CancellationToken CancellationToken; protected AbstractSymbolDescriptionBuilder( ISymbolDisplayService displayService, SemanticModel semanticModel, int position, Workspace workspace, IAnonymousTypeDisplayService anonymousTypeDisplayService, CancellationToken cancellationToken) { _displayService = displayService; _anonymousTypeDisplayService = anonymousTypeDisplayService; this.Workspace = workspace; this.CancellationToken = cancellationToken; _semanticModel = semanticModel; _position = position; } protected abstract void AddExtensionPrefix(); protected abstract void AddAwaitablePrefix(); protected abstract void AddAwaitableExtensionPrefix(); protected abstract void AddDeprecatedPrefix(); protected abstract Task<IEnumerable<SymbolDisplayPart>> GetInitializerSourcePartsAsync(ISymbol symbol); protected abstract SymbolDisplayFormat MinimallyQualifiedFormat { get; } protected abstract SymbolDisplayFormat MinimallyQualifiedFormatWithConstants { get; } protected void AddPrefixTextForAwaitKeyword() { AddToGroup(SymbolDescriptionGroups.MainDescription, PlainText(FeaturesResources.PrefixTextForAwaitKeyword), Space()); } protected void AddTextForSystemVoid() { AddToGroup(SymbolDescriptionGroups.MainDescription, PlainText(FeaturesResources.TextForSystemVoid)); } protected SemanticModel GetSemanticModel(SyntaxTree tree) { if (_semanticModel.SyntaxTree == tree) { return _semanticModel; } var model = _semanticModel.GetOriginalSemanticModel(); if (model.Compilation.ContainsSyntaxTree(tree)) { return model.Compilation.GetSemanticModel(tree); } // it is from one of its p2p references foreach (var reference in model.Compilation.References.OfType<CompilationReference>()) { // find the reference that contains the given tree if (reference.Compilation.ContainsSyntaxTree(tree)) { return reference.Compilation.GetSemanticModel(tree); } } // the tree, a source symbol is defined in, doesn't exist in universe // how this can happen? Contract.Requires(false, "How?"); return null; } private async Task AddPartsAsync(ImmutableArray<ISymbol> symbols) { await AddDescriptionPartAsync(symbols[0]).ConfigureAwait(false); AddOverloadCountPart(symbols); FixAllAnonymousTypes(symbols[0]); AddExceptions(symbols[0]); } private void AddExceptions(ISymbol symbol) { var exceptionTypes = symbol.GetDocumentationComment().ExceptionTypes; if (exceptionTypes.Any()) { var parts = new List<SymbolDisplayPart>(); parts.Add(new SymbolDisplayPart(kind: SymbolDisplayPartKind.Text, symbol: null, text: $"\r\n{WorkspacesResources.Exceptions}")); foreach (var exceptionString in exceptionTypes) { parts.AddRange(LineBreak()); parts.AddRange(Space(count: 2)); parts.AddRange(AbstractDocumentationCommentFormattingService.CrefToSymbolDisplayParts(exceptionString, _position, _semanticModel)); } AddToGroup(SymbolDescriptionGroups.Exceptions, parts); } } public async Task<ImmutableArray<SymbolDisplayPart>> BuildDescriptionAsync( ImmutableArray<ISymbol> symbolGroup, SymbolDescriptionGroups groups) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return this.BuildDescription(groups); } public async Task<IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>>> BuildDescriptionSectionsAsync(ImmutableArray<ISymbol> symbolGroup) { Contract.ThrowIfFalse(symbolGroup.Length > 0); await AddPartsAsync(symbolGroup).ConfigureAwait(false); return this.BuildDescriptionSections(); } private async Task AddDescriptionPartAsync(ISymbol symbol) { if (symbol.GetAttributes().Any(x => x.AttributeClass.MetadataName == "ObsoleteAttribute")) { AddDeprecatedPrefix(); } if (symbol is IDynamicTypeSymbol) { AddDescriptionForDynamicType(); } else if (symbol is IFieldSymbol) { await AddDescriptionForFieldAsync((IFieldSymbol)symbol).ConfigureAwait(false); } else if (symbol is ILocalSymbol) { await AddDescriptionForLocalAsync((ILocalSymbol)symbol).ConfigureAwait(false); } else if (symbol is IMethodSymbol) { AddDescriptionForMethod((IMethodSymbol)symbol); } else if (symbol is ILabelSymbol) { AddDescriptionForLabel((ILabelSymbol)symbol); } else if (symbol is INamedTypeSymbol) { AddDescriptionForNamedType((INamedTypeSymbol)symbol); } else if (symbol is INamespaceSymbol) { AddDescriptionForNamespace((INamespaceSymbol)symbol); } else if (symbol is IParameterSymbol) { await AddDescriptionForParameterAsync((IParameterSymbol)symbol).ConfigureAwait(false); } else if (symbol is IPropertySymbol) { AddDescriptionForProperty((IPropertySymbol)symbol); } else if (symbol is IRangeVariableSymbol) { AddDescriptionForRangeVariable((IRangeVariableSymbol)symbol); } else if (symbol is ITypeParameterSymbol) { AddDescriptionForTypeParameter((ITypeParameterSymbol)symbol); } else if (symbol is IAliasSymbol) { await AddDescriptionPartAsync(((IAliasSymbol)symbol).Target).ConfigureAwait(false); } else { AddDescriptionForArbitrarySymbol(symbol); } } private ImmutableArray<SymbolDisplayPart> BuildDescription(SymbolDescriptionGroups groups) { var finalParts = new List<SymbolDisplayPart>(); var orderedGroups = _groupMap.Keys.OrderBy((g1, g2) => g1 - g2); foreach (var group in orderedGroups) { if ((groups & group) == 0) { continue; } if (!finalParts.IsEmpty()) { var newLines = GetPrecedingNewLineCount(group); finalParts.AddRange(LineBreak(newLines)); } var parts = _groupMap[group]; finalParts.AddRange(parts); } return finalParts.AsImmutable(); } private static int GetPrecedingNewLineCount(SymbolDescriptionGroups group) { switch (group) { case SymbolDescriptionGroups.MainDescription: // these parts are continuations of whatever text came before them return 0; case SymbolDescriptionGroups.Documentation: return 1; case SymbolDescriptionGroups.AnonymousTypes: return 0; case SymbolDescriptionGroups.Exceptions: case SymbolDescriptionGroups.TypeParameterMap: // Everything else is in a group on its own return 2; default: return Contract.FailWithReturn<int>("unknown part kind"); } } private IDictionary<SymbolDescriptionGroups, ImmutableArray<SymbolDisplayPart>> BuildDescriptionSections() { return _groupMap.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.AsImmutableOrEmpty()); } private void AddDescriptionForDynamicType() { AddToGroup(SymbolDescriptionGroups.MainDescription, Keyword("dynamic")); AddToGroup(SymbolDescriptionGroups.Documentation, PlainText(FeaturesResources.RepresentsAnObjectWhoseOperations)); } private void AddDescriptionForNamedType(INamedTypeSymbol symbol) { if (symbol.IsAwaitable(_semanticModel, _position)) { AddAwaitablePrefix(); } var token = _semanticModel.SyntaxTree.GetTouchingToken(_position, this.CancellationToken); if (token != default(SyntaxToken)) { var syntaxFactsService = this.Workspace.Services.GetLanguageServices(token.Language).GetService<ISyntaxFactsService>(); if (syntaxFactsService.IsAwaitKeyword(token)) { AddPrefixTextForAwaitKeyword(); if (symbol.SpecialType == SpecialType.System_Void) { AddTextForSystemVoid(); return; } } } if (symbol.TypeKind == TypeKind.Delegate) { var style = s_descriptionStyle.WithMiscellaneousOptions(SymbolDisplayMiscellaneousOptions.UseSpecialTypes); AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol.OriginalDefinition, style)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol.OriginalDefinition, s_descriptionStyle)); } if (!symbol.IsUnboundGenericType && !TypeArgumentsAndParametersAreSame(symbol)) { var allTypeParameters = symbol.GetAllTypeParameters().ToList(); var allTypeArguments = symbol.GetAllTypeArguments().ToList(); AddTypeParameterMapPart(allTypeParameters, allTypeArguments); } } private bool TypeArgumentsAndParametersAreSame(INamedTypeSymbol symbol) { var typeArguments = symbol.GetAllTypeArguments().ToList(); var typeParameters = symbol.GetAllTypeParameters().ToList(); for (int i = 0; i < typeArguments.Count; i++) { var typeArgument = typeArguments[i]; var typeParameter = typeParameters[i]; if (typeArgument is ITypeParameterSymbol && typeArgument.Name == typeParameter.Name) { continue; } return false; } return true; } private void AddDescriptionForNamespace(INamespaceSymbol symbol) { if (symbol.IsGlobalNamespace) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol, s_globalNamespaceStyle)); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, ToDisplayParts(symbol, s_descriptionStyle)); } } private async Task AddDescriptionForFieldAsync(IFieldSymbol symbol) { var parts = await GetFieldPartsAsync(symbol).ConfigureAwait(false); // Don't bother showing disambiguating text for enum members. The icon displayed // on Quick Info should be enough. if (symbol.ContainingType != null && symbol.ContainingType.TypeKind == TypeKind.Enum) { AddToGroup(SymbolDescriptionGroups.MainDescription, parts); } else { AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.Constant) : Description(FeaturesResources.Field), parts); } } private async Task<IEnumerable<SymbolDisplayPart>> GetFieldPartsAsync(IFieldSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts; } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private async Task AddDescriptionForLocalAsync(ILocalSymbol symbol) { var parts = await GetLocalPartsAsync(symbol).ConfigureAwait(false); AddToGroup(SymbolDescriptionGroups.MainDescription, symbol.IsConst ? Description(FeaturesResources.LocalConstant) : Description(FeaturesResources.LocalVariable), parts); } private async Task<IEnumerable<SymbolDisplayPart>> GetLocalPartsAsync(ILocalSymbol symbol) { if (symbol.IsConst) { var initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); return parts; } } return ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants); } private void AddDescriptionForLabel(ILabelSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.Label), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForRangeVariable(IRangeVariableSymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.RangeVariable), ToMinimalDisplayParts(symbol)); } private void AddDescriptionForMethod(IMethodSymbol method) { // TODO : show duplicated member case // TODO : a way to check whether it is a member call off dynamic type? var awaitable = method.IsAwaitable(_semanticModel, _position); var extension = method.IsExtensionMethod || method.MethodKind == MethodKind.ReducedExtension; if (awaitable && extension) { AddAwaitableExtensionPrefix(); } else if (awaitable) { AddAwaitablePrefix(); } else if (extension) { AddExtensionPrefix(); } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(method, s_memberSignatureDisplayFormat)); if (awaitable) { AddAwaitableUsageText(method, _semanticModel, _position); } } protected abstract void AddAwaitableUsageText(IMethodSymbol method, SemanticModel semanticModel, int position); private async Task AddDescriptionForParameterAsync(IParameterSymbol symbol) { IEnumerable<SymbolDisplayPart> initializerParts; if (symbol.IsOptional) { initializerParts = await GetInitializerSourcePartsAsync(symbol).ConfigureAwait(false); if (initializerParts != null) { var parts = ToMinimalDisplayParts(symbol, MinimallyQualifiedFormat).ToList(); parts.AddRange(Space()); parts.AddRange(Punctuation("=")); parts.AddRange(Space()); parts.AddRange(initializerParts); AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.Parameter), parts); return; } } AddToGroup(SymbolDescriptionGroups.MainDescription, Description(FeaturesResources.Parameter), ToMinimalDisplayParts(symbol, MinimallyQualifiedFormatWithConstants)); } protected virtual void AddDescriptionForProperty(IPropertySymbol symbol) { if (symbol.IsIndexer) { // TODO : show duplicated member case // TODO : a way to check whether it is a member call off dynamic type? AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); return; } AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol, s_memberSignatureDisplayFormat)); } private void AddDescriptionForArbitrarySymbol(ISymbol symbol) { AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol)); } private void AddDescriptionForTypeParameter(ITypeParameterSymbol symbol) { Contract.ThrowIfTrue(symbol.TypeParameterKind == TypeParameterKind.Cref); AddToGroup(SymbolDescriptionGroups.MainDescription, ToMinimalDisplayParts(symbol), Space(), PlainText(FeaturesResources.In), Space(), ToMinimalDisplayParts(symbol.ContainingSymbol, s_typeParameterOwnerFormat)); } private void AddOverloadCountPart( ImmutableArray<ISymbol> symbolGroup) { var count = GetOverloadCount(symbolGroup); if (count >= 1) { AddToGroup(SymbolDescriptionGroups.MainDescription, Space(), Punctuation("("), Punctuation("+"), Space(), PlainText(count.ToString()), Space(), count == 1 ? PlainText(FeaturesResources.Overload) : PlainText(FeaturesResources.Overloads), Punctuation(")")); } } private static int GetOverloadCount(ImmutableArray<ISymbol> symbolGroup) { return symbolGroup.Select(s => s.OriginalDefinition) .Where(s => !s.Equals(symbolGroup.First().OriginalDefinition)) .Where(s => s is IMethodSymbol || s.IsIndexer()) .Count(); } protected void AddTypeParameterMapPart( List<ITypeParameterSymbol> typeParameters, List<ITypeSymbol> typeArguments) { var parts = new List<SymbolDisplayPart>(); var count = typeParameters.Count; for (int i = 0; i < count; i++) { parts.AddRange(TypeParameterName(typeParameters[i].Name)); parts.AddRange(Space()); parts.AddRange(PlainText(FeaturesResources.Is)); parts.AddRange(Space()); parts.AddRange(ToMinimalDisplayParts(typeArguments[i])); if (i < count - 1) { parts.AddRange(LineBreak()); } } AddToGroup(SymbolDescriptionGroups.TypeParameterMap, parts); } protected void AddToGroup(SymbolDescriptionGroups group, params SymbolDisplayPart[] partsArray) { AddToGroup(group, (IEnumerable<SymbolDisplayPart>)partsArray); } protected void AddToGroup(SymbolDescriptionGroups group, params IEnumerable<SymbolDisplayPart>[] partsArray) { var partsList = partsArray.Flatten().ToList(); if (partsList.Count > 0) { IList<SymbolDisplayPart> existingParts; if (!_groupMap.TryGetValue(group, out existingParts)) { existingParts = new List<SymbolDisplayPart>(); _groupMap.Add(group, existingParts); } existingParts.AddRange(partsList); } } private IEnumerable<SymbolDisplayPart> Description(string description) { return Punctuation("(") .Concat(PlainText(description)) .Concat(Punctuation(")")) .Concat(Space()); } protected IEnumerable<SymbolDisplayPart> Keyword(string text) { return Part(SymbolDisplayPartKind.Keyword, text); } protected IEnumerable<SymbolDisplayPart> LineBreak(int count = 1) { for (int i = 0; i < count; i++) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.LineBreak, null, "\r\n"); } } protected IEnumerable<SymbolDisplayPart> PlainText(string text) { return Part(SymbolDisplayPartKind.Text, text); } protected IEnumerable<SymbolDisplayPart> Punctuation(string text) { return Part(SymbolDisplayPartKind.Punctuation, text); } protected IEnumerable<SymbolDisplayPart> Space(int count = 1) { yield return new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, new string(' ', count)); } protected IEnumerable<SymbolDisplayPart> ToMinimalDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { format = format ?? MinimallyQualifiedFormat; return _displayService.ToMinimalDisplayParts(_semanticModel, _position, symbol, format); } protected IEnumerable<SymbolDisplayPart> ToDisplayParts(ISymbol symbol, SymbolDisplayFormat format = null) { return _displayService.ToDisplayParts(symbol, format); } private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, ISymbol symbol, string text) { yield return new SymbolDisplayPart(kind, symbol, text); } private IEnumerable<SymbolDisplayPart> Part(SymbolDisplayPartKind kind, string text) { return Part(kind, null, text); } private IEnumerable<SymbolDisplayPart> TypeParameterName(string text) { return Part(SymbolDisplayPartKind.TypeParameterName, text); } protected IEnumerable<SymbolDisplayPart> ConvertClassifications(SourceText text, IEnumerable<ClassifiedSpan> classifications) { var parts = new List<SymbolDisplayPart>(); ClassifiedSpan? lastSpan = null; foreach (var span in classifications) { // If there is space between this span and the last one, then add a space. if (lastSpan != null && lastSpan.Value.TextSpan.End != span.TextSpan.Start) { parts.AddRange(Space()); } var kind = GetClassificationKind(span.ClassificationType); if (kind != null) { parts.Add(new SymbolDisplayPart(kind.Value, null, text.ToString(span.TextSpan))); lastSpan = span; } } return parts; } private SymbolDisplayPartKind? GetClassificationKind(string type) { switch (type) { default: return null; case ClassificationTypeNames.Identifier: return SymbolDisplayPartKind.Text; case ClassificationTypeNames.Keyword: return SymbolDisplayPartKind.Keyword; case ClassificationTypeNames.NumericLiteral: return SymbolDisplayPartKind.NumericLiteral; case ClassificationTypeNames.StringLiteral: return SymbolDisplayPartKind.StringLiteral; case ClassificationTypeNames.WhiteSpace: return SymbolDisplayPartKind.Space; case ClassificationTypeNames.Operator: return SymbolDisplayPartKind.Operator; case ClassificationTypeNames.Punctuation: return SymbolDisplayPartKind.Punctuation; case ClassificationTypeNames.ClassName: return SymbolDisplayPartKind.ClassName; case ClassificationTypeNames.StructName: return SymbolDisplayPartKind.StructName; case ClassificationTypeNames.InterfaceName: return SymbolDisplayPartKind.InterfaceName; case ClassificationTypeNames.DelegateName: return SymbolDisplayPartKind.DelegateName; case ClassificationTypeNames.EnumName: return SymbolDisplayPartKind.EnumName; case ClassificationTypeNames.TypeParameterName: return SymbolDisplayPartKind.TypeParameterName; case ClassificationTypeNames.ModuleName: return SymbolDisplayPartKind.ModuleName; case ClassificationTypeNames.VerbatimStringLiteral: return SymbolDisplayPartKind.StringLiteral; } } } } }
// 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.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using Microsoft.Rest.Generator.Logging; using Microsoft.Rest.Generator.Properties; using Microsoft.Rest.Generator.Utilities; using Newtonsoft.Json; namespace Microsoft.Rest.Generator.Extensibility { public static class ExtensionsLoader { /// <summary> /// The name of the AutoRest configuration file. /// </summary> private const string ConfigurationFileName = "AutoRest.json"; /// <summary> /// Gets the code generator specified in the provided Settings. /// </summary> /// <param name="settings">The code generation settings</param> /// <returns>Code generator specified in Settings.CodeGenerator</returns> public static CodeGenerator GetCodeGenerator(Settings settings) { Logger.LogInfo(Resources.InitializingCodeGenerator); if (settings == null) { throw new ArgumentNullException("settings"); } if (string.IsNullOrEmpty(settings.CodeGenerator)) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ParameterValueIsMissing, "CodeGenerator")); } CodeGenerator codeGenerator = null; string configurationFile = GetConfigurationFileContent(settings); if (configurationFile != null) { try { var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile); codeGenerator = LoadTypeFromAssembly<CodeGenerator>(config.CodeGenerators, settings.CodeGenerator, settings); Settings.PopulateSettings(codeGenerator, settings.CustomSettings).ForEach(kv => settings.CustomSettings[kv.Key] = kv.Value); } catch (Exception ex) { throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig); } } else { throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound); } Logger.LogInfo(Resources.GeneratorInitialized, settings.CodeGenerator, codeGenerator.GetType().Assembly.GetName().Version); return codeGenerator; } /// <summary> /// Gets the modeler specified in the provided Settings. /// </summary> /// <param name="settings">The code generation settings</param> /// <returns>Modeler specified in Settings.Modeler</returns> public static Modeler GetModeler(Settings settings) { Logger.LogInfo(Resources.ModelerInitialized); if (settings == null) { throw new ArgumentNullException("settings", "settings or settings.Modeler cannot be null."); } if (string.IsNullOrEmpty(settings.Modeler)) { throw new ArgumentException( string.Format(CultureInfo.InvariantCulture, Resources.ParameterValueIsMissing, "Modeler")); } Modeler modeler = null; string configurationFile = GetConfigurationFileContent(settings); if (configurationFile != null) { try { var config = JsonConvert.DeserializeObject<AutoRestConfiguration>(configurationFile); modeler = LoadTypeFromAssembly<Modeler>(config.Modelers, settings.Modeler, settings); Settings.PopulateSettings(modeler, settings.CustomSettings).ForEach(kv => settings.CustomSettings[kv.Key] = kv.Value); } catch (Exception ex) { throw ErrorManager.CreateError(ex, Resources.ErrorParsingConfig); } } else { throw ErrorManager.CreateError(Resources.ConfigurationFileNotFound); } Logger.LogInfo(Resources.ModelerInitialized, settings.Modeler, modeler.GetType().Assembly.GetName().Version); return modeler; } private static string GetConfigurationFileContent(Settings settings) { string path = ConfigurationFileName; if (!settings.FileSystem.FileExists(path)) { path = Path.Combine(Directory.GetCurrentDirectory(), ConfigurationFileName); } if (!settings.FileSystem.FileExists(path)) { path = Path.Combine(Path.GetDirectoryName(Assembly.GetAssembly(typeof (Settings)).Location), ConfigurationFileName); } if (!settings.FileSystem.FileExists(path)) { return null; } return settings.FileSystem.ReadFileAsText(path); } [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom")] private static T LoadTypeFromAssembly<T>(IDictionary<string, AutoRestProviderConfiguration> section, string key, Settings settings) { T instance = default(T); if (!section.IsNullOrEmpty() && section.ContainsKey(key)) { string fullTypeName = section[key].TypeName; if (string.IsNullOrEmpty(fullTypeName)) { throw ErrorManager.CreateError(Resources.ExtensionNotFound, key); } int indexOfComma = fullTypeName.IndexOf(','); if (indexOfComma < 0) { throw ErrorManager.CreateError(Resources.TypeShouldBeAssemblyQualified, fullTypeName); } string typeName = fullTypeName.Substring(0, indexOfComma).Trim(); string assemblyName = fullTypeName.Substring(indexOfComma + 1).Trim(); try { Assembly loadedAssembly; try { loadedAssembly = Assembly.Load(assemblyName); } catch(FileNotFoundException) { loadedAssembly = Assembly.LoadFrom(assemblyName + ".dll"); if(loadedAssembly == null) { throw; } } Type loadedType = loadedAssembly.GetTypes() .Single(t => string.IsNullOrEmpty(typeName) || t.Name == typeName || t.FullName == typeName); instance = (T) loadedType.GetConstructor( new[] {typeof (Settings)}).Invoke(new object[] {settings}); if (!section[key].Settings.IsNullOrEmpty()) { foreach (var settingFromFile in section[key].Settings) { settings.CustomSettings[settingFromFile.Key] = settingFromFile.Value; } } } catch (Exception ex) { throw ErrorManager.CreateError(ex, Resources.ErrorLoadingAssembly, key, ex.Message); } return instance; } throw ErrorManager.CreateError(Resources.ExtensionNotFound, key); } } }
// // Mono.System.Xml.Serialization.MapCodeGenerator // // Author: // Lluis Sanchez Gual (lluis@ximian.com) // // Copyright (C) Ximian, Inc., 2003 // // // 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.CodeDom; using System.CodeDom.Compiler; using System.Collections; #if NET_2_0 using System.ComponentModel; using System.Diagnostics; #endif using System.Globalization; using Mono.System.Xml.Schema; using Microsoft.CSharp; namespace Mono.System.Xml.Serialization { internal class MapCodeGenerator { CodeNamespace codeNamespace; // CodeCompileUnit codeCompileUnit; CodeAttributeDeclarationCollection includeMetadata; XmlTypeMapping exportedAnyType; protected bool includeArrayTypes; #if NET_2_0 CodeDomProvider codeProvider; #endif CodeGenerationOptions options; CodeIdentifiers identifiers; Hashtable exportedMaps = new Hashtable (); Hashtable includeMaps = new Hashtable (); public MapCodeGenerator (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeGenerationOptions options) { // this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; this.options = options; this.identifiers = new CodeIdentifiers (); } public MapCodeGenerator (CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit, CodeDomProvider codeProvider, CodeGenerationOptions options, Hashtable mappings) { // this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; this.options = options; #if NET_2_0 this.codeProvider = codeProvider; this.identifiers = new CodeIdentifiers ((codeProvider.LanguageOptions & LanguageOptions.CaseInsensitive) == 0); #else this.identifiers = new CodeIdentifiers (); #endif // this.mappings = mappings; } public CodeAttributeDeclarationCollection IncludeMetadata { get { if (includeMetadata != null) return includeMetadata; includeMetadata = new CodeAttributeDeclarationCollection (); foreach (XmlTypeMapping map in includeMaps.Values) GenerateClassInclude (includeMetadata, map); return includeMetadata; } } #region Code generation methods public void ExportMembersMapping (XmlMembersMapping xmlMembersMapping) { CodeTypeDeclaration dummyClass = new CodeTypeDeclaration (); ExportMembersMapCode (dummyClass, (ClassMap)xmlMembersMapping.ObjectMap, xmlMembersMapping.Namespace, null); } public void ExportTypeMapping (XmlTypeMapping xmlTypeMapping, bool isTopLevel) { ExportMapCode (xmlTypeMapping, isTopLevel); RemoveInclude (xmlTypeMapping); } void ExportMapCode (XmlTypeMapping map, bool isTopLevel) { switch (map.TypeData.SchemaType) { case SchemaTypes.Enum: ExportEnumCode (map, isTopLevel); break; case SchemaTypes.Array: ExportArrayCode (map); break; case SchemaTypes.Class: ExportClassCode (map, isTopLevel); break; case SchemaTypes.XmlSerializable: case SchemaTypes.XmlNode: case SchemaTypes.Primitive: // Ignore break; } } void ExportClassCode (XmlTypeMapping map, bool isTopLevel) { CodeTypeDeclaration codeClass; if (IsMapExported (map)) { codeClass = GetMapDeclaration (map); if (codeClass != null) { // Regenerate attributes, since things may have changed codeClass.CustomAttributes.Clear (); #if NET_2_0 AddClassAttributes (codeClass); #endif GenerateClass (map, codeClass, isTopLevel); ExportDerivedTypeAttributes (map, codeClass); } return; } if (map.TypeData.Type == typeof(object)) { exportedAnyType = map; SetMapExported (map, null); foreach (XmlTypeMapping dmap in exportedAnyType.DerivedTypes) { if (IsMapExported (dmap) || !dmap.IncludeInSchema) continue; ExportTypeMapping (dmap, false); AddInclude (dmap); } return; } codeClass = new CodeTypeDeclaration (map.TypeData.TypeName); SetMapExported (map, codeClass); AddCodeType (codeClass, map.Documentation); codeClass.Attributes = MemberAttributes.Public; #if NET_2_0 codeClass.IsPartial = CodeProvider.Supports(GeneratorSupport.PartialTypes); AddClassAttributes (codeClass); #endif GenerateClass (map, codeClass, isTopLevel); ExportDerivedTypeAttributes (map, codeClass); ExportMembersMapCode (codeClass, (ClassMap)map.ObjectMap, map.XmlTypeNamespace, map.BaseMap); if (map.BaseMap != null && map.BaseMap.TypeData.SchemaType != SchemaTypes.XmlNode) { CodeTypeReference ctr = GetDomType (map.BaseMap.TypeData, false); codeClass.BaseTypes.Add (ctr); if (map.BaseMap.IncludeInSchema) { ExportMapCode (map.BaseMap, false); AddInclude (map.BaseMap); } } ExportDerivedTypes (map, codeClass); } void ExportDerivedTypeAttributes (XmlTypeMapping map, CodeTypeDeclaration codeClass) { foreach (XmlTypeMapping tm in map.DerivedTypes) { GenerateClassInclude (codeClass.CustomAttributes, tm); ExportDerivedTypeAttributes (tm, codeClass); } } void ExportDerivedTypes (XmlTypeMapping map, CodeTypeDeclaration codeClass) { foreach (XmlTypeMapping tm in map.DerivedTypes) { if (codeClass.CustomAttributes == null) codeClass.CustomAttributes = new CodeAttributeDeclarationCollection (); ExportMapCode (tm, false); ExportDerivedTypes (tm, codeClass); } } void ExportMembersMapCode (CodeTypeDeclaration codeClass, ClassMap map, string defaultNamespace, XmlTypeMapping baseMap) { ICollection attributes = map.AttributeMembers; ICollection members = map.ElementMembers; // collect names if (attributes != null) foreach (XmlTypeMapMemberAttribute attr in attributes) identifiers.AddUnique (attr.Name, attr); if (members != null) foreach (XmlTypeMapMemberElement member in members) identifiers.AddUnique (member.Name, member); // Write attributes if (attributes != null) { foreach (XmlTypeMapMemberAttribute attr in attributes) { if (baseMap != null && DefinedInBaseMap (baseMap, attr)) continue; AddAttributeFieldMember (codeClass, attr, defaultNamespace); } } members = map.ElementMembers; if (members != null) { foreach (XmlTypeMapMemberElement member in members) { if (baseMap != null && DefinedInBaseMap (baseMap, member)) continue; Type memType = member.GetType(); if (memType == typeof(XmlTypeMapMemberList)) { AddArrayElementFieldMember (codeClass, (XmlTypeMapMemberList) member, defaultNamespace); } else if (memType == typeof(XmlTypeMapMemberFlatList)) { AddElementFieldMember (codeClass, member, defaultNamespace); } else if (memType == typeof(XmlTypeMapMemberAnyElement)) { AddAnyElementFieldMember (codeClass, member, defaultNamespace); } else if (memType == typeof(XmlTypeMapMemberElement)) { AddElementFieldMember (codeClass, member, defaultNamespace); } else { throw new InvalidOperationException ("Member type " + memType + " not supported"); } } } XmlTypeMapMember anyAttrMember = map.DefaultAnyAttributeMember; if (anyAttrMember != null) { CodeTypeMember codeField = CreateFieldMember (codeClass, anyAttrMember.TypeData, anyAttrMember.Name); AddComments (codeField, anyAttrMember.Documentation); codeField.Attributes = MemberAttributes.Public; GenerateAnyAttribute (codeField); } } CodeTypeMember CreateFieldMember (CodeTypeDeclaration codeClass, Type type, string name) { return CreateFieldMember (codeClass, new CodeTypeReference(type), name, DBNull.Value, null, null); } CodeTypeMember CreateFieldMember (CodeTypeDeclaration codeClass, TypeData type, string name) { return CreateFieldMember (codeClass, GetDomType (type, false), name, DBNull.Value, null, null); } CodeTypeMember CreateFieldMember (CodeTypeDeclaration codeClass, XmlTypeMapMember member) { return CreateFieldMember (codeClass, GetDomType (member.TypeData, member.RequiresNullable), member.Name, member.DefaultValue, member.TypeData, member.Documentation); } CodeTypeMember CreateFieldMember (CodeTypeDeclaration codeClass, CodeTypeReference type, string name, object defaultValue, TypeData defaultType, string documentation) { CodeMemberField codeField = null; CodeTypeMember codeProp = null; if ((options & CodeGenerationOptions.GenerateProperties) > 0) { string field = identifiers.AddUnique (CodeIdentifier.MakeCamel (name + "Field"), name); codeField = new CodeMemberField (type, field); codeField.Attributes = MemberAttributes.Private; codeClass.Members.Add (codeField); CodeMemberProperty prop = new CodeMemberProperty (); prop.Name = name; prop.Type = type; prop.Attributes = MemberAttributes.Public | MemberAttributes.Final; codeProp = prop; prop.HasGet = prop.HasSet = true; CodeExpression ce = new CodeFieldReferenceExpression (new CodeThisReferenceExpression(), field); prop.SetStatements.Add (new CodeAssignStatement (ce, new CodePropertySetValueReferenceExpression())); prop.GetStatements.Add (new CodeMethodReturnStatement (ce)); } else { codeField = new CodeMemberField (type, name); codeField.Attributes = MemberAttributes.Public; codeProp = codeField; } if (defaultValue != DBNull.Value) GenerateDefaultAttribute (codeField, codeProp, defaultType, defaultValue); AddComments (codeProp, documentation); codeClass.Members.Add (codeProp); return codeProp; } void AddAttributeFieldMember (CodeTypeDeclaration codeClass, XmlTypeMapMemberAttribute attinfo, string defaultNamespace) { CodeTypeMember codeField = CreateFieldMember (codeClass, attinfo); CodeAttributeDeclarationCollection attributes = codeField.CustomAttributes; if (attributes == null) attributes = new CodeAttributeDeclarationCollection (); GenerateAttributeMember (attributes, attinfo, defaultNamespace, false); if (attributes.Count > 0) codeField.CustomAttributes = attributes; if (attinfo.MappedType != null) { ExportMapCode (attinfo.MappedType, false); RemoveInclude (attinfo.MappedType); } if (attinfo.TypeData.IsValueType && attinfo.IsOptionalValueType) { codeField = CreateFieldMember (codeClass, typeof(bool), identifiers.MakeUnique (attinfo.Name + "Specified")); codeField.Attributes = MemberAttributes.Public; GenerateSpecifierMember (codeField); } } public void AddAttributeMemberAttributes (XmlTypeMapMemberAttribute attinfo, string defaultNamespace, CodeAttributeDeclarationCollection attributes, bool forceUseMemberName) { GenerateAttributeMember (attributes, attinfo, defaultNamespace, forceUseMemberName); } void AddElementFieldMember (CodeTypeDeclaration codeClass, XmlTypeMapMemberElement member, string defaultNamespace) { CodeTypeMember codeField = CreateFieldMember (codeClass, member); CodeAttributeDeclarationCollection attributes = codeField.CustomAttributes; if (attributes == null) attributes = new CodeAttributeDeclarationCollection (); AddElementMemberAttributes (member, defaultNamespace, attributes, false); if (attributes.Count > 0) codeField.CustomAttributes = attributes; if (member.TypeData.IsValueType && member.IsOptionalValueType) { codeField = CreateFieldMember (codeClass, typeof(bool), identifiers.MakeUnique (member.Name + "Specified")); codeField.Attributes = MemberAttributes.Public; GenerateSpecifierMember (codeField); } } public void AddElementMemberAttributes (XmlTypeMapMemberElement member, string defaultNamespace, CodeAttributeDeclarationCollection attributes, bool forceUseMemberName) { TypeData defaultType = member.TypeData; bool addAlwaysAttr = false; if (member is XmlTypeMapMemberFlatList) { defaultType = defaultType.ListItemTypeData; addAlwaysAttr = true; } foreach (XmlTypeMapElementInfo einfo in member.ElementInfo) { if (einfo.MappedType != null) { ExportMapCode (einfo.MappedType, false); RemoveInclude (einfo.MappedType); } if (ExportExtraElementAttributes (attributes, einfo, defaultNamespace, defaultType)) continue; GenerateElementInfoMember (attributes, member, einfo, defaultType, defaultNamespace, addAlwaysAttr, forceUseMemberName | addAlwaysAttr); } GenerateElementMember (attributes, member); } void AddAnyElementFieldMember (CodeTypeDeclaration codeClass, XmlTypeMapMemberElement member, string defaultNamespace) { CodeTypeMember codeField = CreateFieldMember (codeClass, member); CodeAttributeDeclarationCollection attributes = new CodeAttributeDeclarationCollection (); foreach (XmlTypeMapElementInfo einfo in member.ElementInfo) ExportExtraElementAttributes (attributes, einfo, defaultNamespace, einfo.TypeData); if (attributes.Count > 0) codeField.CustomAttributes = attributes; } bool DefinedInBaseMap (XmlTypeMapping map, XmlTypeMapMember member) { if (((ClassMap)map.ObjectMap).FindMember (member.Name) != null) return true; else if (map.BaseMap != null) return DefinedInBaseMap (map.BaseMap, member); else return false; } void AddArrayElementFieldMember (CodeTypeDeclaration codeClass, XmlTypeMapMemberList member, string defaultNamespace) { CodeTypeMember codeField = CreateFieldMember (codeClass, member.TypeData, member.Name); CodeAttributeDeclarationCollection attributes = new CodeAttributeDeclarationCollection (); AddArrayAttributes (attributes, member, defaultNamespace, false); ListMap listMap = (ListMap) member.ListTypeMapping.ObjectMap; AddArrayItemAttributes (attributes, listMap, member.TypeData.ListItemTypeData, defaultNamespace, 0); if (attributes.Count > 0) codeField.CustomAttributes = attributes; } public void AddArrayAttributes (CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, string defaultNamespace, bool forceUseMemberName) { GenerateArrayElement (attributes, member, defaultNamespace, forceUseMemberName); } public void AddArrayItemAttributes (CodeAttributeDeclarationCollection attributes, ListMap listMap, TypeData type, string defaultNamespace, int nestingLevel) { foreach (XmlTypeMapElementInfo ainfo in listMap.ItemInfo) { string defaultName; if (ainfo.MappedType != null) defaultName = ainfo.MappedType.ElementName; else defaultName = ainfo.TypeData.XmlType; GenerateArrayItemAttributes (attributes, listMap, type, ainfo, defaultName, defaultNamespace, nestingLevel); if (ainfo.MappedType != null) { if (!IsMapExported (ainfo.MappedType) && includeArrayTypes) AddInclude (ainfo.MappedType); ExportMapCode (ainfo.MappedType, false); } } if (listMap.IsMultiArray) { XmlTypeMapping nmap = listMap.NestedArrayMapping; AddArrayItemAttributes (attributes, (ListMap) nmap.ObjectMap, nmap.TypeData.ListItemTypeData, defaultNamespace, nestingLevel + 1); } } void ExportArrayCode (XmlTypeMapping map) { ListMap listMap = (ListMap) map.ObjectMap; foreach (XmlTypeMapElementInfo ainfo in listMap.ItemInfo) { if (ainfo.MappedType != null) { if (!IsMapExported (ainfo.MappedType) && includeArrayTypes) AddInclude (ainfo.MappedType); ExportMapCode (ainfo.MappedType, false); } } } bool ExportExtraElementAttributes (CodeAttributeDeclarationCollection attributes, XmlTypeMapElementInfo einfo, string defaultNamespace, TypeData defaultType) { if (einfo.IsTextElement) { GenerateTextElementAttribute (attributes, einfo, defaultType); return true; } else if (einfo.IsUnnamedAnyElement) { GenerateUnnamedAnyElementAttribute (attributes, einfo, defaultNamespace); return true; } return false; } void ExportEnumCode (XmlTypeMapping map, bool isTopLevel) { if (IsMapExported (map)) return; CodeTypeDeclaration codeEnum = new CodeTypeDeclaration (map.TypeData.TypeName); SetMapExported (map, codeEnum); codeEnum.Attributes = MemberAttributes.Public; codeEnum.IsEnum = true; AddCodeType (codeEnum, map.Documentation); EnumMap emap = (EnumMap) map.ObjectMap; if (emap.IsFlags) codeEnum.CustomAttributes.Add (new CodeAttributeDeclaration ("System.FlagsAttribute")); #if NET_2_0 CodeAttributeDeclaration generatedCodeAttribute = new CodeAttributeDeclaration ( new CodeTypeReference (typeof(GeneratedCodeAttribute))); generatedCodeAttribute.Arguments.Add (new CodeAttributeArgument ( new CodePrimitiveExpression ("System.Xml"))); generatedCodeAttribute.Arguments.Add (new CodeAttributeArgument ( new CodePrimitiveExpression (Consts.FxFileVersion))); codeEnum.CustomAttributes.Add (generatedCodeAttribute); codeEnum.CustomAttributes.Add (new CodeAttributeDeclaration ( new CodeTypeReference (typeof (SerializableAttribute)))); #endif GenerateEnum (map, codeEnum, isTopLevel); int flag = 1; foreach (EnumMap.EnumMapMember emem in emap.Members) { CodeMemberField codeField = new CodeMemberField ("", emem.EnumName); if (emap.IsFlags) { codeField.InitExpression = new CodePrimitiveExpression (flag); flag *= 2; } AddComments (codeField, emem.Documentation); GenerateEnumItem (codeField, emem); codeEnum.Members.Add (codeField); } } void AddInclude (XmlTypeMapping map) { if (!includeMaps.ContainsKey (map.TypeData.FullTypeName)) includeMaps [map.TypeData.FullTypeName] = map; } void RemoveInclude (XmlTypeMapping map) { includeMaps.Remove (map.TypeData.FullTypeName); } #endregion #region Helper methods bool IsMapExported (XmlTypeMapping map) { if (exportedMaps.Contains (map.TypeData.FullTypeName)) return true; return false; } void SetMapExported (XmlTypeMapping map, CodeTypeDeclaration declaration) { exportedMaps.Add (map.TypeData.FullTypeName, declaration); } CodeTypeDeclaration GetMapDeclaration (XmlTypeMapping map) { return exportedMaps [map.TypeData.FullTypeName] as CodeTypeDeclaration; } public static void AddCustomAttribute (CodeTypeMember ctm, CodeAttributeDeclaration att, bool addIfNoParams) { if (att.Arguments.Count == 0 && !addIfNoParams) return; if (ctm.CustomAttributes == null) ctm.CustomAttributes = new CodeAttributeDeclarationCollection (); ctm.CustomAttributes.Add (att); } public static void AddCustomAttribute (CodeTypeMember ctm, string name, params CodeAttributeArgument[] args) { if (ctm.CustomAttributes == null) ctm.CustomAttributes = new CodeAttributeDeclarationCollection (); ctm.CustomAttributes.Add (new CodeAttributeDeclaration (name, args)); } public static CodeAttributeArgument GetArg (string name, object value) { return new CodeAttributeArgument (name, new CodePrimitiveExpression(value)); } public static CodeAttributeArgument GetArg (object value) { return new CodeAttributeArgument (new CodePrimitiveExpression(value)); } public static CodeAttributeArgument GetTypeArg (string name, string typeName) { return new CodeAttributeArgument (name, new CodeTypeOfExpression(typeName)); } public static CodeAttributeArgument GetEnumArg (string name, string enumType, string enumValue) { return new CodeAttributeArgument (name, new CodeFieldReferenceExpression (new CodeTypeReferenceExpression(enumType), enumValue)); } public static void AddComments (CodeTypeMember member, string comments) { if (comments == null || comments == "") member.Comments.Add (new CodeCommentStatement ("<remarks/>", true)); else member.Comments.Add (new CodeCommentStatement ("<remarks>\n" + comments + "\n</remarks>", true)); } void AddCodeType (CodeTypeDeclaration type, string comments) { AddComments (type, comments); codeNamespace.Types.Add (type); } #if NET_2_0 void AddClassAttributes (CodeTypeDeclaration codeClass) { CodeAttributeDeclaration generatedCodeAttribute = new CodeAttributeDeclaration ( new CodeTypeReference (typeof (GeneratedCodeAttribute))); generatedCodeAttribute.Arguments.Add (new CodeAttributeArgument ( new CodePrimitiveExpression ("System.Xml"))); generatedCodeAttribute.Arguments.Add (new CodeAttributeArgument ( new CodePrimitiveExpression (Consts.FxFileVersion))); codeClass.CustomAttributes.Add (generatedCodeAttribute); codeClass.CustomAttributes.Add (new CodeAttributeDeclaration ( new CodeTypeReference (typeof (SerializableAttribute)))); codeClass.CustomAttributes.Add (new CodeAttributeDeclaration ( new CodeTypeReference (typeof (DebuggerStepThroughAttribute)))); CodeAttributeDeclaration designerCategoryAttribute = new CodeAttributeDeclaration ( new CodeTypeReference (typeof (DesignerCategoryAttribute))); designerCategoryAttribute.Arguments.Add (new CodeAttributeArgument ( new CodePrimitiveExpression ("code"))); codeClass.CustomAttributes.Add (designerCategoryAttribute); } #endif CodeTypeReference GetDomType (TypeData data, bool requiresNullable) { #if NET_2_0 if (data.IsValueType && (data.IsNullable || requiresNullable)) return new CodeTypeReference ("System.Nullable", new CodeTypeReference (data.FullTypeName)); #endif if (data.SchemaType == SchemaTypes.Array) return new CodeTypeReference (GetDomType (data.ListItemTypeData, false),1); else return new CodeTypeReference (data.FullTypeName); } #endregion #region Private Properties #if NET_2_0 private CodeDomProvider CodeProvider { get { if (codeProvider == null) { codeProvider = new CSharpCodeProvider (); } return codeProvider; } } #endif #endregion #region Overridable methods protected virtual void GenerateClass (XmlTypeMapping map, CodeTypeDeclaration codeClass, bool isTopLevel) { } protected virtual void GenerateClassInclude (CodeAttributeDeclarationCollection attributes, XmlTypeMapping map) { } protected virtual void GenerateAnyAttribute (CodeTypeMember codeField) { } protected virtual void GenerateDefaultAttribute (CodeMemberField internalField, CodeTypeMember externalField, TypeData typeData, object defaultValue) { if (typeData.Type == null) { // It must be an enumeration defined in the schema. if (typeData.SchemaType != SchemaTypes.Enum) throw new InvalidOperationException ("Type " + typeData.TypeName + " not supported"); IFormattable defaultValueFormattable = defaultValue as IFormattable; CodeFieldReferenceExpression fref = new CodeFieldReferenceExpression (new CodeTypeReferenceExpression (GetDomType (typeData, false)), defaultValueFormattable != null ? defaultValueFormattable.ToString(null, CultureInfo.InvariantCulture) : defaultValue.ToString ()); CodeAttributeArgument arg = new CodeAttributeArgument (fref); AddCustomAttribute (externalField, "System.ComponentModel.DefaultValue", arg); //internalField.InitExpression = fref; } else { defaultValue = defaultValue is decimal ? (object) ('"' + ((decimal) defaultValue).ToString (CultureInfo.InvariantCulture) + '"') : defaultValue; AddCustomAttribute (externalField, "System.ComponentModel.DefaultValue", GetArg (defaultValue)); //internalField.InitExpression = new CodePrimitiveExpression (defaultValue); } } protected virtual void GenerateAttributeMember (CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberAttribute attinfo, string defaultNamespace, bool forceUseMemberName) { } protected virtual void GenerateElementInfoMember (CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, XmlTypeMapElementInfo einfo, TypeData defaultType, string defaultNamespace, bool addAlwaysAttr, bool forceUseMemberName) { } protected virtual void GenerateElementMember (CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member) { } protected virtual void GenerateArrayElement (CodeAttributeDeclarationCollection attributes, XmlTypeMapMemberElement member, string defaultNamespace, bool forceUseMemberName) { } protected virtual void GenerateArrayItemAttributes (CodeAttributeDeclarationCollection attributes, ListMap listMap, TypeData type, XmlTypeMapElementInfo ainfo, string defaultName, string defaultNamespace, int nestingLevel) { } protected virtual void GenerateTextElementAttribute (CodeAttributeDeclarationCollection attributes, XmlTypeMapElementInfo einfo, TypeData defaultType) { } protected virtual void GenerateUnnamedAnyElementAttribute (CodeAttributeDeclarationCollection attributes, XmlTypeMapElementInfo einfo, string defaultNamespace) { } protected virtual void GenerateEnum (XmlTypeMapping map, CodeTypeDeclaration codeEnum, bool isTopLevel) { } protected virtual void GenerateEnumItem (CodeMemberField codeField, EnumMap.EnumMapMember emem) { } protected virtual void GenerateSpecifierMember (CodeTypeMember codeField) { } #endregion } }
// Security parameters type. // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors. // // 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.Globalization; /* * Created by SharpDevelop. * User: lextm * Date: 5/3/2009 * Time: 1:59 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ namespace GSF.Net.Snmp { /// <summary> /// Description of SecurityParameters. /// </summary> public sealed class SecurityParameters : ISegment { /// <summary> /// Gets the engine ID. /// </summary> /// <value>The engine ID.</value> public OctetString EngineId { get; private set; } /// <summary> /// Gets the boot count. /// </summary> /// <value>The boot count.</value> public Integer32 EngineBoots { get; private set; } /// <summary> /// Gets the engine time. /// </summary> /// <value>The engine time.</value> public Integer32 EngineTime { get; private set; } /// <summary> /// Gets the user name. /// </summary> /// <value>The user name.</value> public OctetString UserName { get; private set; } private OctetString _authenticationParameters; private readonly byte[] _length; /// <summary> /// Gets the authentication parameters. /// </summary> /// <value>The authentication parameters.</value> public OctetString AuthenticationParameters { get { return _authenticationParameters; } set { if (_authenticationParameters == null) { _authenticationParameters = value; return; } if (value.GetRaw().Length != _authenticationParameters.GetRaw().Length) { throw new ArgumentException( $"Length of new authentication parameters is invalid: {value.GetRaw().Length} found while {_authenticationParameters.GetRaw().Length} expected.", nameof(value)); } if (value.GetLengthBytes() != _authenticationParameters.GetLengthBytes()) { value.SetLengthBytes(_authenticationParameters.GetLengthBytes()); } _authenticationParameters = value; } } /// <summary> /// Gets the privacy parameters. /// </summary> /// <value>The privacy parameters.</value> public OctetString PrivacyParameters { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="SecurityParameters"/> class. /// </summary> /// <param name="parameters">The <see cref="OctetString"/> that contains parameters.</param> public SecurityParameters(OctetString parameters) { if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } Sequence container = (Sequence)DataFactory.CreateSnmpData(parameters.GetRaw()); EngineId = (OctetString)container[0]; EngineBoots = (Integer32)container[1]; EngineTime = (Integer32)container[2]; UserName = (OctetString)container[3]; AuthenticationParameters = (OctetString)container[4]; PrivacyParameters = (OctetString)container[5]; _length = container.GetLengthBytes(); } /// <summary> /// Initializes a new instance of the <see cref="SecurityParameters"/> class. /// </summary> /// <param name="engineId">The engine ID.</param> /// <param name="engineBoots">The engine boots.</param> /// <param name="engineTime">The engine time.</param> /// <param name="userName">The user name.</param> /// <param name="authenticationParameters">The authentication parameters.</param> /// <param name="privacyParameters">The privacy parameters.</param> /// <remarks>Only <paramref name="userName"/> cannot be null.</remarks> public SecurityParameters(OctetString engineId, Integer32 engineBoots, Integer32 engineTime, OctetString userName, OctetString authenticationParameters, OctetString privacyParameters) { if (userName == null) { throw new ArgumentNullException(nameof(userName)); } EngineId = engineId; EngineBoots = engineBoots; EngineTime = engineTime; UserName = userName; AuthenticationParameters = authenticationParameters; PrivacyParameters = privacyParameters; } /// <summary> /// Creates an instance of <see cref="SecurityParameters"/>. /// </summary> /// <param name="userName">User name.</param> /// <returns></returns> public static SecurityParameters Create(OctetString userName) { return new SecurityParameters(null, null, null, userName, null, null); } /// <summary> /// Converts to <see cref="Sequence"/>. /// </summary> /// <returns></returns> public Sequence ToSequence() { return new Sequence(_length, EngineId, EngineBoots, EngineTime, UserName, AuthenticationParameters, PrivacyParameters); } #region ISegment Members /// <summary> /// Gets the data. /// </summary> /// <param name="version">The version.</param> /// <returns></returns> public ISnmpData GetData(VersionCode version) { return version == VersionCode.V3 ? new OctetString(ToSequence().ToBytes()) : UserName; } #endregion /// <summary> /// Returns a <see cref="System.String"/> that represents this instance. /// </summary> /// <returns> /// A <see cref="System.String"/> that represents this instance. /// </returns> public override string ToString() { return string.Format(CultureInfo.InvariantCulture, "Security parameters: engineId: {0};engineBoots: {1};engineTime: {2};userName: {3}; authen hash: {4}; privacy hash: {5}", EngineId, EngineBoots, EngineTime, UserName, AuthenticationParameters == null ? null : AuthenticationParameters.ToHexString(), PrivacyParameters == null ? null : PrivacyParameters.ToHexString()); } /// <summary> /// Gets a value that indicates whether the hashes are invalid. /// </summary> public bool IsInvalid { get; set; } } }
using System; namespace LinqToDB.SqlProvider { using System.Collections.Generic; using System.Diagnostics; using System.Linq; using JetBrains.Annotations; using SqlQuery; internal class JoinOptimizer { Dictionary<SelectQuery.SearchCondition, SelectQuery.SearchCondition> _additionalFilter; Dictionary<VirtualField, HashSet<Tuple<int, VirtualField>>> _equalityMap; Dictionary<Tuple<SelectQuery.TableSource, SelectQuery.TableSource>, List<FoundEquality>> _fieldPairCache; Dictionary<int, List<List<string>>> _keysCache; HashSet<int> _removedSources; Dictionary<VirtualField, VirtualField> _replaceMap; SelectQuery _selectQuery; static bool IsEqualTables(SqlTable table1, SqlTable table2) { var result = table1 != null && table2 != null && table1.Database == table2.Database && table1.Owner == table2.Owner && table1.Name == table2.Name; return result; } void FlattenJoins(SelectQuery.TableSource table) { for (var i = 0; i < table.Joins.Count; i++) { var j = table.Joins[i]; FlattenJoins(j.Table); if (j.JoinType == SelectQuery.JoinType.Inner) for (var si = 0; si < j.Table.Joins.Count; si++) { var sj = j.Table.Joins[si]; if ((sj.JoinType == SelectQuery.JoinType.Inner || sj.JoinType == SelectQuery.JoinType.Left) && table != j.Table && !HasDependencyWithParent(j, sj)) { table.Joins.Insert(i + 1, sj); j.Table.Joins.RemoveAt(si); --si; } } } } bool IsDependedBetweenJoins(SelectQuery.TableSource table, SelectQuery.JoinedTable testedJoin) { var testedSources = new HashSet<int>(testedJoin.Table.GetTables().Select(t => t.SourceID)); foreach (var tableJoin in table.Joins) { if (testedSources.Contains(tableJoin.Table.SourceID)) continue; if (IsDependedOnJoin(table, tableJoin, testedSources)) return true; } return IsDependedExcludeJoins(testedSources); } bool IsDepended(SelectQuery.JoinedTable join, SelectQuery.JoinedTable toIgnore) { var testedSources = new HashSet<int>(join.Table.GetTables().Select(t => t.SourceID)); if (toIgnore != null) foreach (var sourceId in toIgnore.Table.GetTables().Select(t => t.SourceID)) testedSources.Add(sourceId); var dependent = false; new QueryVisitor().VisitParentFirst(_selectQuery, e => { if (dependent) return false; // ignore non searchable parts if ( e.ElementType == QueryElementType.SelectClause || e.ElementType == QueryElementType.GroupByClause || e.ElementType == QueryElementType.OrderByClause) return false; if (e.ElementType == QueryElementType.JoinedTable) if (testedSources.Contains(((SelectQuery.JoinedTable) e).Table.SourceID)) return false; var expression = e as ISqlExpression; if (expression != null) { var field = GetUnderlayingField(expression); if (field != null) { var newField = GetNewField(field); var local = testedSources.Contains(newField.SourceID); if (local) dependent = !CanWeReplaceField(null, newField, testedSources, -1); } } return !dependent; }); return dependent; } bool IsDependedExcludeJoins(SelectQuery.JoinedTable join) { var testedSources = new HashSet<int>(join.Table.GetTables().Select(t => t.SourceID)); return IsDependedExcludeJoins(testedSources); } bool IsDependedExcludeJoins(HashSet<int> testedSources) { var dependent = false; new QueryVisitor().VisitParentFirst(_selectQuery, e => { if (dependent) return false; if (e.ElementType == QueryElementType.JoinedTable) return false; var expression = e as ISqlExpression; if (expression != null) { var field = GetUnderlayingField(expression); if (field != null) { var newField = GetNewField(field); var local = testedSources.Contains(newField.SourceID); if (local) dependent = !CanWeReplaceField(null, newField, testedSources, -1); } } return !dependent; }); return dependent; } bool HasDependencyWithParent(SelectQuery.JoinedTable parent, SelectQuery.JoinedTable child) { var sources = new HashSet<int>(child.Table.GetTables().Select(t => t.SourceID)); var dependent = false; // check that parent has dependency on child new QueryVisitor().VisitParentFirst(parent, e => { if (dependent) return false; if (e == child) return false; var expression = e as ISqlExpression; if (expression != null) { var field = GetUnderlayingField(expression); if (field != null) dependent = sources.Contains(field.SourceID); } return !dependent; }); return dependent; } bool IsDependedOnJoin(SelectQuery.TableSource table, SelectQuery.JoinedTable testedJoin, HashSet<int> testedSources) { var dependent = false; var currentSourceId = testedJoin.Table.SourceID; // check everyting that can be dependent on specific table new QueryVisitor().VisitParentFirst(testedJoin, e => { if (dependent) return false; var expression = e as ISqlExpression; if (expression != null) { var field = GetUnderlayingField(expression); if (field != null) { var newField = GetNewField(field); var local = testedSources.Contains(newField.SourceID); if (local) dependent = !CanWeReplaceField(table, newField, testedSources, currentSourceId); } } return !dependent; }); return dependent; } bool CanWeReplaceFieldInternal(SelectQuery.TableSource table, VirtualField field, HashSet<int> excludeSourceIds, int testedSourceIndex, HashSet<VirtualField> visited) { if (visited.Contains(field)) return false; if (!excludeSourceIds.Contains(field.SourceID) && !IsSourceRemoved(field.SourceID)) return true; visited.Add(field); if (_equalityMap == null) return false; if (testedSourceIndex < 0) return false; HashSet<Tuple<int, VirtualField>> sameFields; if (_equalityMap.TryGetValue(field, out sameFields)) foreach (var pair in sameFields) if ((testedSourceIndex == 0 || GetSourceIndex(table, pair.Item1) > testedSourceIndex) && CanWeReplaceFieldInternal(table, pair.Item2, excludeSourceIds, testedSourceIndex, visited)) return true; return false; } bool CanWeReplaceField(SelectQuery.TableSource table, VirtualField field, HashSet<int> excludeSourceId, int testedSourceId) { var visited = new HashSet<VirtualField>(); return CanWeReplaceFieldInternal(table, field, excludeSourceId, GetSourceIndex(table, testedSourceId), visited); } VirtualField GetNewField(VirtualField field) { if (_replaceMap == null) return field; VirtualField newField; if (_replaceMap.TryGetValue(field, out newField)) { VirtualField fieldOther; while (_replaceMap.TryGetValue(newField, out fieldOther)) newField = fieldOther; } else { newField = field; } return newField; } VirtualField MapToSourceInternal(SelectQuery.TableSource fromTable, VirtualField field, int sourceId, HashSet<VirtualField> visited) { if (visited.Contains(field)) return null; if (field.SourceID == sourceId) return field; visited.Add(field); if (_equalityMap == null) return null; var sourceIndex = GetSourceIndex(fromTable, sourceId); HashSet<Tuple<int, VirtualField>> sameFields; if (_equalityMap.TryGetValue(field, out sameFields)) foreach (var pair in sameFields) { var itemIndex = GetSourceIndex(fromTable, pair.Item1); if (itemIndex >= 0 && (sourceIndex == 0 || itemIndex < sourceIndex)) { var newField = MapToSourceInternal(fromTable, pair.Item2, sourceId, visited); if (newField != null) return newField; } } return null; } VirtualField MapToSource(SelectQuery.TableSource table, VirtualField field, int sourceId) { var visited = new HashSet<VirtualField>(); return MapToSourceInternal(table, field, sourceId, visited); } void RemoveSource(SelectQuery.TableSource fromTable, SelectQuery.JoinedTable join) { if (_removedSources == null) _removedSources = new HashSet<int>(); _removedSources.Add(join.Table.SourceID); if (_equalityMap != null) { var keys = _equalityMap.Keys.Where(k => k.SourceID == join.Table.SourceID).ToArray(); foreach (var key in keys) { var newField = MapToSource(fromTable, key, fromTable.SourceID); if (newField != null) ReplaceField(key, newField); _equalityMap.Remove(key); } } ResetFieldSearchCache(join.Table); } bool IsSourceRemoved(int sourceId) { return _removedSources != null && _removedSources.Contains(sourceId); } void ReplaceField(VirtualField oldField, VirtualField newField) { if (_replaceMap == null) _replaceMap = new Dictionary<VirtualField, VirtualField>(); _replaceMap.Remove(oldField); _replaceMap.Add (oldField, newField); } void AddEqualFields(VirtualField field1, VirtualField field2, int levelSourceId) { if (_equalityMap == null) _equalityMap = new Dictionary<VirtualField, HashSet<Tuple<int, VirtualField>>>(); HashSet<Tuple<int, VirtualField>> set; if (!_equalityMap.TryGetValue(field1, out set)) { set = new HashSet<Tuple<int, VirtualField>>(); _equalityMap.Add(field1, set); } set.Add(Tuple.Create(levelSourceId, field2)); } bool CompareExpressions(SelectQuery.Predicate.ExprExpr expr1, SelectQuery.Predicate.ExprExpr expr2) { if (expr1.Operator != expr2.Operator) return false; if (expr1.ElementType != expr2.ElementType) return false; switch (expr1.ElementType) { case QueryElementType.ExprExprPredicate: { return CompareExpressions(expr1.Expr1, expr2.Expr1) == true && CompareExpressions(expr1.Expr2, expr2.Expr2) == true || CompareExpressions(expr1.Expr1, expr2.Expr2) == true && CompareExpressions(expr1.Expr2, expr2.Expr1) == true; } } return false; } bool? CompareExpressions(ISqlExpression expr1, ISqlExpression expr2) { if (expr1.ElementType != expr2.ElementType) return null; switch (expr1.ElementType) { case QueryElementType.Column: { return CompareExpressions(((SelectQuery.Column) expr1).Expression, ((SelectQuery.Column) expr2).Expression); } case QueryElementType.SqlField: { var field1 = GetNewField(new VirtualField((SqlField) expr1)); var field2 = GetNewField(new VirtualField((SqlField) expr2)); return field1.Equals(field2); } } return null; } bool CompareConditions(SelectQuery.Condition cond1, SelectQuery.Condition cond2) { if (cond1.ElementType != cond2.ElementType) return false; if (cond1.Predicate.ElementType != cond2.Predicate.ElementType) return false; switch (cond1.Predicate.ElementType) { case QueryElementType.IsNullPredicate: { var isNull1 = (SelectQuery.Predicate.IsNull) cond1.Predicate; var isNull2 = (SelectQuery.Predicate.IsNull) cond2.Predicate; return isNull1.IsNot == isNull2.IsNot && CompareExpressions(isNull1.Expr1, isNull2.Expr1) == true; } case QueryElementType.ExprExprPredicate: { var expr1 = (SelectQuery.Predicate.ExprExpr) cond1.Predicate; var expr2 = (SelectQuery.Predicate.ExprExpr) cond2.Predicate; return CompareExpressions(expr1, expr2); } } return false; } bool? EvaluateLogical(SelectQuery.Condition condition) { switch (condition.ElementType) { case QueryElementType.Condition: { var expr = condition.Predicate as SelectQuery.Predicate.ExprExpr; if (expr != null && expr.Operator == SelectQuery.Predicate.Operator.Equal) return CompareExpressions(expr.Expr1, expr.Expr2); break; } } return null; } void OptimizeSearchCondition(SelectQuery.SearchCondition searchCondition) { var items = searchCondition.Conditions; if (items.Any(c => c.IsOr)) return; for (var i1 = 0; i1 < items.Count; i1++) { var c1 = items[i1]; var cmp = EvaluateLogical(c1); if (cmp != null) if (cmp.Value) { items.RemoveAt(i1); --i1; continue; } switch (c1.ElementType) { case QueryElementType.Condition: case QueryElementType.SearchCondition: { var search = c1.Predicate as SelectQuery.SearchCondition; if (search != null) { OptimizeSearchCondition(search); if (search.Conditions.Count == 0) { items.RemoveAt(i1); --i1; continue; } } break; } } for (var i2 = i1 + 1; i2 < items.Count; i2++) { var c2 = items[i2]; if (CompareConditions(c2, c1)) { searchCondition.Conditions.RemoveAt(i2); --i2; } } } } void AddSearchCondition(SelectQuery.SearchCondition search, SelectQuery.Condition condition) { AddSearchConditions(search, new[] {condition}); } void AddSearchConditions(SelectQuery.SearchCondition search, IEnumerable<SelectQuery.Condition> conditions) { if (_additionalFilter == null) _additionalFilter = new Dictionary<SelectQuery.SearchCondition, SelectQuery.SearchCondition>(); SelectQuery.SearchCondition value; if (!_additionalFilter.TryGetValue(search, out value)) { if (search.Conditions.Count > 0 && search.Precedence < Precedence.LogicalConjunction) { value = new SelectQuery.SearchCondition(); var prev = new SelectQuery.SearchCondition(); prev. Conditions.AddRange(search.Conditions); search.Conditions.Clear(); search.Conditions.Add(new SelectQuery.Condition(false, value, false)); search.Conditions.Add(new SelectQuery.Condition(false, prev, false)); } else { value = search; } _additionalFilter.Add(search, value); } value.Conditions.AddRange(conditions); } void OptimizeFilters() { if (_additionalFilter == null) return; foreach (var pair in _additionalFilter) { OptimizeSearchCondition(pair.Value); if (!ReferenceEquals(pair.Key, pair.Value) && pair.Value.Conditions.Count == 1) { // conditions can be optimized so we have to remove empty SearchCondition var searchCondition = pair.Value.Conditions[0].Predicate as SelectQuery.SearchCondition; if (searchCondition != null && searchCondition.Conditions.Count == 0) pair.Key.Conditions.Remove(pair.Value.Conditions[0]); } } } Dictionary<string, VirtualField> GetFields(ISqlTableSource source) { var res = new Dictionary<string, VirtualField>(); var table = source as SqlTable; if (table != null) foreach (var pair in table.Fields) res.Add(pair.Key, new VirtualField(pair.Value)); return res; } void ReplaceSource(SelectQuery.TableSource fromTable, SelectQuery.JoinedTable oldSource, SelectQuery.TableSource newSource) { var oldFields = GetFields(oldSource.Table.Source); var newFields = GetFields(newSource.Source); foreach (var old in oldFields) { var newField = newFields[old.Key]; ReplaceField(old.Value, newField); } RemoveSource(fromTable, oldSource); } void CorrectMappings() { if (_replaceMap != null && _replaceMap.Count > 0 || _removedSources != null) _selectQuery = new QueryVisitor().Convert(_selectQuery, element => { var field = element as SqlField; if (field != null) return GetNewField(new VirtualField(field)).Element; var column = element as SelectQuery.Column; if (column != null) return GetNewField(new VirtualField(column)).Element; return element; }); } int GetSourceIndex(SelectQuery.TableSource table, int sourceId) { if (table == null || table.SourceID == sourceId || sourceId == -1) return 0; var i = 0; while (i < table.Joins.Count) { if (table.Joins[i].Table.SourceID == sourceId) return i + 1; ++i; } return -1; } void CollectEqualFields(SelectQuery.JoinedTable join) { if (join.JoinType != SelectQuery.JoinType.Inner) return; if (join.Condition.Conditions.Any(c => c.IsOr)) return; for (var i1 = 0; i1 < join.Condition.Conditions.Count; i1++) { var c = join.Condition.Conditions[i1]; if ( c.ElementType != QueryElementType.Condition || c.Predicate.ElementType != QueryElementType.ExprExprPredicate || ((SelectQuery.Predicate.ExprExpr) c.Predicate).Operator != SelectQuery.Predicate.Operator.Equal) continue; var predicate = (SelectQuery.Predicate.ExprExpr) c.Predicate; var field1 = GetUnderlayingField(predicate.Expr1); if (field1 == null) continue; var field2 = GetUnderlayingField(predicate.Expr2); if (field2 == null) continue; if (field1.Equals(field2)) continue; AddEqualFields(field1, field2, join.Table.SourceID); AddEqualFields(field2, field1, join.Table.SourceID); } } List<List<string>> GetKeysInternal(ISqlTableSource tableSource) { //TODO: needed mechanism to define unique indexes. Currently only primary key is used // only from tables we can get keys if (!(tableSource is SqlTable)) return null; var keys = tableSource.GetKeys(false); if (keys == null || keys.Count == 0) return null; var fields = keys.Select(GetUnderlayingField) .Where(f => f != null) .Select(f => f.Name).ToList(); if (fields.Count != keys.Count) return null; var knownKeys = new List<List<string>>(); knownKeys.Add(fields); return knownKeys; } List<List<string>> GetKeys(ISqlTableSource tableSource) { List<List<string>> keys; if (_keysCache == null || !_keysCache.TryGetValue(tableSource.SourceID, out keys)) { keys = GetKeysInternal(tableSource); if (_keysCache == null) _keysCache = new Dictionary<int, List<List<string>>>(); _keysCache.Add(tableSource.SourceID, keys); } return keys; } public SelectQuery OptimizeJoins(SelectQuery selectQuery) { _selectQuery = selectQuery; for (var i = 0; i < selectQuery.From.Tables.Count; i++) { var fromTable = selectQuery.From.Tables[i]; FlattenJoins(fromTable); for (var i1 = 0; i1 < fromTable.Joins.Count; i1++) { var j1 = fromTable.Joins[i1]; CollectEqualFields(j1); // supported only INNER and LEFT joins if (j1.JoinType != SelectQuery.JoinType.Inner && j1.JoinType != SelectQuery.JoinType.Left) continue; // trying to remove join that is equal to FROM table if (IsEqualTables(fromTable.Source as SqlTable, j1.Table.Source as SqlTable)) { var keys = GetKeys(j1.Table.Source); if (keys != null && TryMergeWithTable(fromTable, j1, keys)) { fromTable.Joins.RemoveAt(i1); --i1; continue; } } for (var i2 = i1 + 1; i2 < fromTable.Joins.Count; i2++) { var j2 = fromTable.Joins[i2]; // we can merge LEFT and INNER joins together if (j2.JoinType != SelectQuery.JoinType.Inner && j2.JoinType != SelectQuery.JoinType.Left) continue; if (!IsEqualTables(j1.Table.Source as SqlTable, j2.Table.Source as SqlTable)) continue; var keys = GetKeys(j2.Table.Source); if (keys != null) { // try merge if joins are the same var merged = TryMergeJoins(fromTable, fromTable, j1, j2, keys); if (!merged) for (var im = 0; im < i2; im++) if (fromTable.Joins[im].JoinType == SelectQuery.JoinType.Inner || j2.JoinType != SelectQuery.JoinType.Left) { merged = TryMergeJoins(fromTable, fromTable.Joins[im].Table, j1, j2, keys); if (merged) break; } if (merged) { fromTable.Joins.RemoveAt(i2); --i2; } } } } // trying to remove joins that are not in projection for (var i1 = 0; i1 < fromTable.Joins.Count; i1++) { var j1 = fromTable.Joins[i1]; if (j1.JoinType == SelectQuery.JoinType.Left || j1.JoinType == SelectQuery.JoinType.Inner) { var keys = GetKeys(j1.Table.Source); if (keys != null && !IsDependedBetweenJoins(fromTable, j1)) { // try merge if joins are the same var removed = TryToRemoveIndepended(fromTable, fromTable, j1, keys); if (!removed) for (var im = 0; im < i1; im++) { var jm = fromTable.Joins[im]; if (jm.JoinType == SelectQuery.JoinType.Inner || jm.JoinType != SelectQuery.JoinType.Left) { removed = TryToRemoveIndepended(fromTable, jm.Table, j1, keys); if (removed) break; } } if (removed) { fromTable.Joins.RemoveAt(i1); --i1; } } } } // independed joins loop } // table loop OptimizeFilters(); CorrectMappings(); return _selectQuery; } static VirtualField GetUnderlayingField(ISqlExpression expr) { switch (expr.ElementType) { case QueryElementType.SqlField: return new VirtualField((SqlField) expr); case QueryElementType.Column: { return new VirtualField((SelectQuery.Column) expr); } } return null; } void DetectField(SelectQuery.TableSource manySource, SelectQuery.TableSource oneSource, VirtualField field, FoundEquality equality) { field = GetNewField(field); if (oneSource.Source.SourceID == field.SourceID) equality.OneField = field; else if (manySource.Source.SourceID == field.SourceID) equality.ManyField = field; else equality.ManyField = MapToSource(manySource, field, manySource.Source.SourceID); } bool MatchFields(SelectQuery.TableSource manySource, SelectQuery.TableSource oneSource, VirtualField field1, VirtualField field2, FoundEquality equality) { if (field1 == null || field2 == null) return false; DetectField(manySource, oneSource, field1, equality); DetectField(manySource, oneSource, field2, equality); return equality.OneField != null && equality.ManyField != null; } void ResetFieldSearchCache(SelectQuery.TableSource table) { if (_fieldPairCache == null) return; var keys = _fieldPairCache.Keys.Where(k => k.Item2 == table || k.Item1 == table).ToArray(); foreach (var key in keys) _fieldPairCache.Remove(key); } List<FoundEquality> SearchForFields(SelectQuery.TableSource manySource, SelectQuery.JoinedTable join) { var key = Tuple.Create(manySource, join.Table); List<FoundEquality> found = null; if (_fieldPairCache != null && _fieldPairCache.TryGetValue(key, out found)) return found; for (var i1 = 0; i1 < join.Condition.Conditions.Count; i1++) { var c = join.Condition.Conditions[i1]; if (c.IsOr) { found = null; break; } if ( c.ElementType != QueryElementType.Condition || c.Predicate.ElementType != QueryElementType.ExprExprPredicate || ((SelectQuery.Predicate.ExprExpr) c.Predicate).Operator != SelectQuery.Predicate.Operator.Equal) continue; var predicate = (SelectQuery.Predicate.ExprExpr) c.Predicate; var equality = new FoundEquality(); if (!MatchFields(manySource, join.Table, GetUnderlayingField(predicate.Expr1), GetUnderlayingField(predicate.Expr2), equality)) continue; equality.OneCondition = c; if (found == null) found = new List<FoundEquality>(); found.Add(equality); } if (_fieldPairCache == null) _fieldPairCache = new Dictionary<Tuple<SelectQuery.TableSource, SelectQuery.TableSource>, List<FoundEquality>>(); _fieldPairCache.Add(key, found); return found; } bool TryMergeWithTable(SelectQuery.TableSource fromTable, SelectQuery.JoinedTable join, List<List<string>> uniqueKeys) { if (join.Table.Joins.Count != 0) return false; var hasLeftJoin = join.JoinType == SelectQuery.JoinType.Left; var found = SearchForFields(fromTable, join); if (found == null) return false; if (hasLeftJoin) { if (join.Condition.Conditions.Count != found.Count) return false; // currently no dependecies in search condition allowed for left join if (IsDependedExcludeJoins(join)) return false; } HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name)); HashSet<string> uniqueFields = null; for (var i = 0; i < uniqueKeys.Count; i++) { var keys = uniqueKeys[i]; if (keys.All(k => foundFields.Contains(k))) { if (uniqueFields == null) uniqueFields = new HashSet<string>(); foreach (var key in keys) uniqueFields.Add(key); } } if (uniqueFields != null) { foreach (var item in found) if (uniqueFields.Contains(item.OneField.Name)) { // remove unique key conditions join.Condition.Conditions.Remove(item.OneCondition); AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID); } // move rest conditions to the Where section if (join.Condition.Conditions.Count > 0) { AddSearchConditions(_selectQuery.Where.SearchCondition, join.Condition.Conditions); join.Condition.Conditions.Clear(); } // add check that previously joined fields is not null foreach (var item in found) if (item.ManyField.CanBeNull) { var newField = MapToSource(fromTable, item.ManyField, fromTable.SourceID); AddSearchCondition(_selectQuery.Where.SearchCondition, new SelectQuery.Condition(false, new SelectQuery.Predicate.IsNull(newField.Element, true))); } // add mapping to new source ReplaceSource(fromTable, join, fromTable); return true; } return false; } bool TryMergeJoins(SelectQuery.TableSource fromTable, SelectQuery.TableSource manySource, SelectQuery.JoinedTable join1, SelectQuery.JoinedTable join2, List<List<string>> uniqueKeys) { var found1 = SearchForFields(manySource, join1); if (found1 == null) return false; var found2 = SearchForFields(manySource, join2); if (found2 == null) return false; var hasLeftJoin = join1.JoinType == SelectQuery.JoinType.Left || join2.JoinType == SelectQuery.JoinType.Left; // left join should match exactly if (hasLeftJoin) { if (join1.Condition.Conditions.Count != join2.Condition.Conditions.Count) return false; if (found1.Count != found2.Count) return false; if (join1.Table.Joins.Count != 0 || join2.Table.Joins.Count != 0) return false; } List<FoundEquality> found = null; for (var i1 = 0; i1 < found1.Count; i1++) { var f1 = found1[i1]; for (var i2 = 0; i2 < found2.Count; i2++) { var f2 = found2[i2]; if (f1.ManyField.Name == f2.ManyField.Name && f1.OneField.Name == f2.OneField.Name) { if (found == null) found = new List<FoundEquality>(); found.Add(f2); } } } if (found == null) return false; if (hasLeftJoin) { // for left join each expression should be used if (found.Count != join1.Condition.Conditions.Count) return false; // currently no dependecies in search condition allowed for left join if (IsDepended(join1, join2)) return false; } HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name)); HashSet<string> uniqueFields = null; for (var i = 0; i < uniqueKeys.Count; i++) { var keys = uniqueKeys[i]; if (keys.All(k => foundFields.Contains(k))) { if (uniqueFields == null) uniqueFields = new HashSet<string>(); foreach (var key in keys) uniqueFields.Add(key); } } if (uniqueFields != null) { foreach (var item in found) if (uniqueFields.Contains(item.OneField.Name)) { // remove from second join2.Condition.Conditions.Remove(item.OneCondition); AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID); } // move rest conditions to first if (join2.Condition.Conditions.Count > 0) { AddSearchConditions(join1.Condition, join2.Condition.Conditions); join2.Condition.Conditions.Clear(); } join1.Table.Joins.AddRange(join2.Table.Joins); // add mapping to new source ReplaceSource(fromTable, join2, join1.Table); return true; } return false; } // here we can deal with LEFT JOIN and INNER JOIN bool TryToRemoveIndepended(SelectQuery.TableSource fromTable, SelectQuery.TableSource manySource, SelectQuery.JoinedTable join, List<List<string>> uniqueKeys) { if (join.JoinType == SelectQuery.JoinType.Inner) return false; var found = SearchForFields(manySource, join); if (found == null) return false; HashSet<string> foundFields = new HashSet<string>(found.Select(f => f.OneField.Name)); HashSet<string> uniqueFields = null; for (var i = 0; i < uniqueKeys.Count; i++) { var keys = uniqueKeys[i]; if (keys.All(k => foundFields.Contains(k))) { if (uniqueFields == null) uniqueFields = new HashSet<string>(); foreach (var key in keys) uniqueFields.Add(key); } } if (uniqueFields != null) { if (join.JoinType == SelectQuery.JoinType.Inner) { foreach (var item in found) if (uniqueFields.Contains(item.OneField.Name)) { // remove from second join.Condition.Conditions.Remove(item.OneCondition); AddEqualFields(item.ManyField, item.OneField, fromTable.SourceID); } // move rest conditions to Where if (join.Condition.Conditions.Count > 0) { AddSearchConditions(_selectQuery.Where.SearchCondition, join.Condition.Conditions); join.Condition.Conditions.Clear(); } // add filer for nullable fileds because after INNER JOIN records with nulls dissapear foreach (var item in found) if (item.ManyField.CanBeNull) AddSearchCondition(_selectQuery.Where.SearchCondition, new SelectQuery.Condition(false, new SelectQuery.Predicate.IsNull(item.ManyField.Element, true))); } RemoveSource(fromTable, join); return true; } return false; } [DebuggerDisplay("{ManyField.DisplayString()} -> {OneField.DisplayString()}")] class FoundEquality { public VirtualField ManyField; public SelectQuery.Condition OneCondition; public VirtualField OneField; } [DebuggerDisplay("{DisplayString()}")] class VirtualField { public VirtualField([NotNull] SqlField field) { if (field == null) throw new ArgumentNullException("field"); Field = field; } public VirtualField([NotNull] SelectQuery.Column column) { if (column == null) throw new ArgumentNullException("column"); Column = column; } public SqlField Field { get; set; } public SelectQuery.Column Column { get; set; } public string Name { get { return Field == null ? Column.Alias : Field.Name; } } public int SourceID { get { return Field == null ? Column.Parent.SourceID : Field.Table.SourceID; } } public bool CanBeNull { get { return Field == null ? Column.CanBeNull : Field.CanBeNull; } } public ISqlExpression Element { get { if (Field != null) return Field; return Column; } } protected bool Equals(VirtualField other) { return Equals(Field, other.Field) && Equals(Column, other.Column); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((VirtualField) obj); } string GetSourceString(ISqlTableSource source) { var table = source as SqlTable; if (table != null) { var res = string.Format("({0}).{1}", source.SourceID, table.Name); if (table.Alias != table.Name && !string.IsNullOrEmpty(table.Alias)) res = res + "(" + table.Alias + ")"; return res; } return string.Format("({0}).{1}", source.SourceID, source); } public string DisplayString() { if (Field != null) return string.Format("F: '{0}.{1}'", GetSourceString(Field.Table), Name); return string.Format("C: '{0}.{1}'", GetSourceString(Column.Parent), Name); } public override int GetHashCode() { unchecked { return ((Field != null ? Field.GetHashCode() : 0) * 397) ^ (Column != null ? Column.GetHashCode() : 0); } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using JetBrains.Application.Threading; using JetBrains.Diagnostics; using JetBrains.ProjectModel; using JetBrains.ReSharper.Plugins.Unity.Core.Psi.Modules; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.Caches; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.Elements.Stripped; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy.References; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetInspectorValues.Deserializers; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetInspectorValues.Values; using JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.Utils; using JetBrains.ReSharper.Plugins.Yaml.Psi; using JetBrains.ReSharper.Plugins.Yaml.Psi.Tree; using JetBrains.ReSharper.Psi; using JetBrains.ReSharper.Psi.Caches; using JetBrains.ReSharper.Psi.Tree; using JetBrains.Util; namespace JetBrains.ReSharper.Plugins.Unity.Yaml.Psi.DeferredCaches.AssetHierarchy { [SolutionComponent] public class AssetDocumentHierarchyElementContainer : IUnityAssetDataElementContainer { private readonly IPersistentIndexManager myManager; private readonly UnityExternalFilesPsiModule myPsiModule; private readonly MetaFileGuidCache myMetaFileGuidCache; private readonly PrefabImportCache myPrefabImportCache; private readonly IShellLocks myShellLocks; private readonly IEnumerable<IAssetInspectorValueDeserializer> myAssetInspectorValueDeserializers; private readonly ConcurrentDictionary<IPsiSourceFile, IUnityAssetDataElementPointer> myAssetDocumentsHierarchy = new ConcurrentDictionary<IPsiSourceFile, IUnityAssetDataElementPointer>(); public AssetDocumentHierarchyElementContainer(IPersistentIndexManager manager, PrefabImportCache prefabImportCache, IShellLocks shellLocks, UnityExternalFilesModuleFactory psiModuleProvider, MetaFileGuidCache metaFileGuidCache, IEnumerable<IAssetInspectorValueDeserializer> assetInspectorValueDeserializers) { myManager = manager; myPrefabImportCache = prefabImportCache; myShellLocks = shellLocks; myPsiModule = psiModuleProvider.PsiModule; myMetaFileGuidCache = metaFileGuidCache; myAssetInspectorValueDeserializers = assetInspectorValueDeserializers; } public IUnityAssetDataElement CreateDataElement(IPsiSourceFile sourceFile) { return new AssetDocumentHierarchyElement(); } public bool IsApplicable(IPsiSourceFile currentAssetSourceFile) { return true; } public object Build(IPsiSourceFile currentAssetSourceFile, AssetDocument assetDocument) { var anchorRaw = AssetUtils.GetAnchorFromBuffer(assetDocument.Buffer); if (!anchorRaw.HasValue) return null; var anchor = anchorRaw.Value; var isStripped = AssetUtils.IsStripped(assetDocument.Buffer); var location = new LocalReference(currentAssetSourceFile.PsiStorage.PersistentIndex.NotNull("owningPsiPersistentIndex != null"), anchor); if (isStripped) { var prefabInstance = AssetUtils.GetPrefabInstance(currentAssetSourceFile, assetDocument.Buffer) as LocalReference?; var correspondingSourceObject = AssetUtils.GetCorrespondingSourceObject(currentAssetSourceFile, assetDocument.Buffer) as ExternalReference?; if (prefabInstance != null && correspondingSourceObject != null) return new StrippedHierarchyElement(location, prefabInstance.Value, correspondingSourceObject.Value); return null; } var gameObject = AssetUtils.GetGameObjectReference(currentAssetSourceFile, assetDocument.Buffer) as LocalReference?; if (gameObject != null && AssetUtils.IsMonoBehaviourDocument(assetDocument.Buffer)) { var documentReference = assetDocument.Document.GetUnityObjectPropertyValue<INode>(UnityYamlConstants.ScriptProperty) ?.ToHierarchyReference(currentAssetSourceFile); if (documentReference is ExternalReference scriptReference) { return new ScriptComponentHierarchy(location, gameObject.Value, scriptReference); } } else if (gameObject != null && AssetUtils.IsTransform(assetDocument.Buffer)) { var father = AssetUtils.GetTransformFather(currentAssetSourceFile, assetDocument.Buffer) as LocalReference?; if (father == null) return null; var rootIndex = AssetUtils.GetRootIndex(assetDocument.Buffer); return new TransformHierarchy(location, gameObject.Value, father.Value, rootIndex); } else if (AssetUtils.IsGameObject(assetDocument.Buffer)) { var name = AssetUtils.GetGameObjectName(assetDocument.Buffer); if (name != null) { return new GameObjectHierarchy(location, name); } } else if (AssetUtils.IsPrefabModification(assetDocument.Buffer)) { var modification = AssetUtils.GetPrefabModification(assetDocument.Document); var parentTransform = modification?.GetMapEntryValue<INode>("m_TransformParent") ?.ToHierarchyReference(currentAssetSourceFile) as LocalReference? ?? LocalReference.Null; var modifications = modification?.GetMapEntryValue<IBlockSequenceNode>("m_Modifications"); var result = new List<PrefabModification>(); if (modifications != null) { foreach (var entry in modifications.Entries) { var map = entry.Value as IBlockMappingNode; var target = map?.GetMapEntryValue<INode>("target") .ToHierarchyReference(currentAssetSourceFile); if (target == null) continue; var name = map.GetMapEntryPlainScalarText("propertyPath"); if (name == null) continue; var valueNode = map.GetMapEntry("value")?.Content; if (valueNode == null) continue; IAssetValue value = null; foreach (var assetInspectorValueDeserializer in myAssetInspectorValueDeserializers) { if (assetInspectorValueDeserializer.TryGetInspectorValue(currentAssetSourceFile, valueNode, out value)) break; } var objectReference = map.GetMapEntryValue<INode>("objectReference").ToHierarchyReference(currentAssetSourceFile); var valueRange = valueNode.GetTreeTextRange(); result.Add(new PrefabModification(target, name, value, new TextRange(assetDocument.StartOffset + valueRange.StartOffset.Offset, assetDocument.StartOffset + valueRange.EndOffset.Offset), objectReference)); } } var sourcePrefabGuid = AssetUtils.GetSourcePrefab(currentAssetSourceFile, assetDocument.Buffer) as ExternalReference?; if (sourcePrefabGuid == null) return null; return new PrefabInstanceHierarchy(location, parentTransform, result, sourcePrefabGuid.Value.ExternalAssetGuid); } else if (gameObject != null)// regular component { var name = AssetUtils.GetRawComponentName(assetDocument.Buffer); if (name == null) return null; return new ComponentHierarchy(location, gameObject.Value, name); } return null; } public void Drop(IPsiSourceFile currentAssetSourceFile, AssetDocumentHierarchyElement hierarchyElement, IUnityAssetDataElement unityAssetDataElement) { myPrefabImportCache.OnHierarchyRemoved(currentAssetSourceFile, unityAssetDataElement as AssetDocumentHierarchyElement); myAssetDocumentsHierarchy.TryRemove(currentAssetSourceFile, out _); } public void Merge(IPsiSourceFile currentAssetSourceFile, AssetDocumentHierarchyElement hierarchyElement, IUnityAssetDataElementPointer unityAssetDataElementPointer, IUnityAssetDataElement unityAssetDataElement) { var element = unityAssetDataElement as AssetDocumentHierarchyElement; myAssetDocumentsHierarchy[currentAssetSourceFile] = unityAssetDataElementPointer; element.RestoreHierarchy(this, currentAssetSourceFile); myPrefabImportCache.OnHierarchyCreated(currentAssetSourceFile, element); } public IHierarchyElement GetHierarchyElement(IHierarchyReference reference, bool prefabImport) { myShellLocks.AssertReadAccessAllowed(); if (reference == null) return null; var sourceFile = GetSourceFile(reference, out var guid); if (sourceFile == null || guid == null) return null; var element = myAssetDocumentsHierarchy[sourceFile].GetElement(sourceFile, Id) as AssetDocumentHierarchyElement; if (element == null) return null; return element.GetHierarchyElement(guid.Value, reference.LocalDocumentAnchor, prefabImport ? myPrefabImportCache : null); } public AssetDocumentHierarchyElement GetAssetHierarchyFor(IPsiSourceFile sourceFile) { myShellLocks.AssertReadAccessAllowed(); if (myAssetDocumentsHierarchy.TryGetValue(sourceFile, out var result)) return result.GetElement(sourceFile, Id) as AssetDocumentHierarchyElement; return null; } public AssetDocumentHierarchyElement GetAssetHierarchyFor(LocalReference location, out Guid? guid) { myShellLocks.AssertReadAccessAllowed(); var sourceFile = GetSourceFile(location, out guid); if (sourceFile == null || guid == null) return null; return myAssetDocumentsHierarchy.GetValueSafe(sourceFile)?.GetElement(sourceFile, Id) as AssetDocumentHierarchyElement; } public IPsiSourceFile GetSourceFile(IHierarchyReference hierarchyReference, out Guid? guid) { guid = null; if (hierarchyReference == null) return null; myShellLocks.AssertReadAccessAllowed(); switch (hierarchyReference) { case LocalReference localReference: var sourceFile = myManager[localReference.OwningPsiPersistentIndex]; guid = sourceFile != null ? myMetaFileGuidCache.GetAssetGuid(sourceFile) : null; return sourceFile; case ExternalReference externalReference: guid = externalReference.ExternalAssetGuid; var paths = myMetaFileGuidCache.GetAssetFilePathsFromGuid(guid.Value); if (paths.Count != 1) return null; return myPsiModule.TryGetFileByPath(paths[0], out var result) ? result : null; default: throw new InvalidOperationException(); } } public string Id => nameof(AssetDocumentHierarchyElementContainer); public int Order => int.MaxValue; public void Invalidate() { myAssetDocumentsHierarchy.Clear(); } } }
// 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.Runtime.InteropServices; using System.Globalization; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Data.SqlTypes { /// <summary> /// Represents a floating point number within the range of -3.40E +38 through /// 3.40E +38 to be stored in or retrieved from a database. /// </summary> [StructLayout(LayoutKind.Sequential)] [Serializable] [XmlSchemaProvider("GetXsdType")] public struct SqlSingle : INullable, IComparable, IXmlSerializable { private bool _fNotNull; // false if null private float _value; // constructor // construct a Null private SqlSingle(bool fNull) { _fNotNull = false; _value = (float)0.0; } public SqlSingle(float value) { if (float.IsInfinity(value) || float.IsNaN(value)) throw new OverflowException(SQLResource.s_arithOverflowMessage); else { _fNotNull = true; _value = value; } } public SqlSingle(double value) : this(checked((float)value)) { } // INullable public bool IsNull { get { return !_fNotNull; } } // property: Value public float Value { get { if (_fNotNull) return _value; else throw new SqlNullValueException(); } } // Implicit conversion from float to SqlSingle public static implicit operator SqlSingle(float x) { return new SqlSingle(x); } // Explicit conversion from SqlSingle to float. Throw exception if x is Null. public static explicit operator float (SqlSingle x) { return x.Value; } public override string ToString() { return IsNull ? SQLResource.s_nullString : _value.ToString((IFormatProvider)null); } public static SqlSingle Parse(string s) { if (s == SQLResource.s_nullString) return SqlSingle.Null; else return new SqlSingle(float.Parse(s, CultureInfo.InvariantCulture)); } // Unary operators public static SqlSingle operator -(SqlSingle x) { return x.IsNull ? Null : new SqlSingle(-x._value); } // Binary operators // Arithmetic operators public static SqlSingle operator +(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; float value = x._value + y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.s_arithOverflowMessage); return new SqlSingle(value); } public static SqlSingle operator -(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; float value = x._value - y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.s_arithOverflowMessage); return new SqlSingle(value); } public static SqlSingle operator *(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; float value = x._value * y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.s_arithOverflowMessage); return new SqlSingle(value); } public static SqlSingle operator /(SqlSingle x, SqlSingle y) { if (x.IsNull || y.IsNull) return Null; if (y._value == (float)0.0) throw new DivideByZeroException(SQLResource.s_divideByZeroMessage); float value = x._value / y._value; if (float.IsInfinity(value)) throw new OverflowException(SQLResource.s_arithOverflowMessage); return new SqlSingle(value); } // Implicit conversions // Implicit conversion from SqlBoolean to SqlSingle public static explicit operator SqlSingle(SqlBoolean x) { return x.IsNull ? Null : new SqlSingle(x.ByteValue); } // Implicit conversion from SqlByte to SqlSingle public static implicit operator SqlSingle(SqlByte x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlInt16 to SqlSingle public static implicit operator SqlSingle(SqlInt16 x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlInt32 to SqlSingle public static implicit operator SqlSingle(SqlInt32 x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlInt64 to SqlSingle public static implicit operator SqlSingle(SqlInt64 x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.Value); } // Implicit conversion from SqlMoney to SqlSingle public static implicit operator SqlSingle(SqlMoney x) { return x.IsNull ? Null : new SqlSingle(x.ToDouble()); } // Implicit conversion from SqlDecimal to SqlSingle public static implicit operator SqlSingle(SqlDecimal x) { // Will not overflow return x.IsNull ? Null : new SqlSingle(x.ToDouble()); } // Explicit conversions // Explicit conversion from SqlDouble to SqlSingle public static explicit operator SqlSingle(SqlDouble x) { return x.IsNull ? Null : new SqlSingle(x.Value); } // Explicit conversion from SqlString to SqlSingle // Throws FormatException or OverflowException if necessary. public static explicit operator SqlSingle(SqlString x) { if (x.IsNull) return SqlSingle.Null; return Parse(x.Value); } // Overloading comparison operators public static SqlBoolean operator ==(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value == y._value); } public static SqlBoolean operator !=(SqlSingle x, SqlSingle y) { return !(x == y); } public static SqlBoolean operator <(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value < y._value); } public static SqlBoolean operator >(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value > y._value); } public static SqlBoolean operator <=(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value <= y._value); } public static SqlBoolean operator >=(SqlSingle x, SqlSingle y) { return (x.IsNull || y.IsNull) ? SqlBoolean.Null : new SqlBoolean(x._value >= y._value); } //-------------------------------------------------- // Alternative methods for overloaded operators //-------------------------------------------------- // Alternative method for operator + public static SqlSingle Add(SqlSingle x, SqlSingle y) { return x + y; } // Alternative method for operator - public static SqlSingle Subtract(SqlSingle x, SqlSingle y) { return x - y; } // Alternative method for operator * public static SqlSingle Multiply(SqlSingle x, SqlSingle y) { return x * y; } // Alternative method for operator / public static SqlSingle Divide(SqlSingle x, SqlSingle y) { return x / y; } // Alternative method for operator == public static SqlBoolean Equals(SqlSingle x, SqlSingle y) { return (x == y); } // Alternative method for operator != public static SqlBoolean NotEquals(SqlSingle x, SqlSingle y) { return (x != y); } // Alternative method for operator < public static SqlBoolean LessThan(SqlSingle x, SqlSingle y) { return (x < y); } // Alternative method for operator > public static SqlBoolean GreaterThan(SqlSingle x, SqlSingle y) { return (x > y); } // Alternative method for operator <= public static SqlBoolean LessThanOrEqual(SqlSingle x, SqlSingle y) { return (x <= y); } // Alternative method for operator >= public static SqlBoolean GreaterThanOrEqual(SqlSingle x, SqlSingle y) { return (x >= y); } // Alternative method for conversions. public SqlBoolean ToSqlBoolean() { return (SqlBoolean)this; } public SqlByte ToSqlByte() { return (SqlByte)this; } public SqlDouble ToSqlDouble() { return this; } public SqlInt16 ToSqlInt16() { return (SqlInt16)this; } public SqlInt32 ToSqlInt32() { return (SqlInt32)this; } public SqlInt64 ToSqlInt64() { return (SqlInt64)this; } public SqlMoney ToSqlMoney() { return (SqlMoney)this; } public SqlDecimal ToSqlDecimal() { return (SqlDecimal)this; } public SqlString ToSqlString() { return (SqlString)this; } // IComparable // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this < object, zero if this = object, // or a value greater than zero if this > object. // null is considered to be less than any instance. // If object is not of same type, this method throws an ArgumentException. public int CompareTo(object value) { if (value is SqlSingle) { SqlSingle i = (SqlSingle)value; return CompareTo(i); } throw ADP.WrongType(value.GetType(), typeof(SqlSingle)); } public int CompareTo(SqlSingle value) { // If both Null, consider them equal. // Otherwise, Null is less than anything. if (IsNull) return value.IsNull ? 0 : -1; else if (value.IsNull) return 1; if (this < value) return -1; if (this > value) return 1; return 0; } // Compares this instance with a specified object public override bool Equals(object value) { if (!(value is SqlSingle)) { return false; } SqlSingle i = (SqlSingle)value; if (i.IsNull || IsNull) return (i.IsNull && IsNull); else return (this == i).Value; } // For hashing purpose public override int GetHashCode() { return IsNull ? 0 : Value.GetHashCode(); } XmlSchema IXmlSerializable.GetSchema() { return null; } void IXmlSerializable.ReadXml(XmlReader reader) { string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. reader.ReadElementString(); _fNotNull = false; } else { _value = XmlConvert.ToSingle(reader.ReadElementString()); _fNotNull = true; } } void IXmlSerializable.WriteXml(XmlWriter writer) { if (IsNull) { writer.WriteAttributeString("xsi", "nil", XmlSchema.InstanceNamespace, "true"); } else { writer.WriteString(XmlConvert.ToString(_value)); } } public static XmlQualifiedName GetXsdType(XmlSchemaSet schemaSet) { return new XmlQualifiedName("float", XmlSchema.Namespace); } public static readonly SqlSingle Null = new SqlSingle(true); public static readonly SqlSingle Zero = new SqlSingle((float)0.0); public static readonly SqlSingle MinValue = new SqlSingle(float.MinValue); public static readonly SqlSingle MaxValue = new SqlSingle(float.MaxValue); } // SqlSingle } // namespace System.Data.SqlTypes
/* * 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 ParquetSharp.Column.Impl { using System.Globalization; using System.IO; using System.Text; using ParquetSharp.Bytes; using ParquetSharp.Column.Page; using ParquetSharp.Column.Statistics; using ParquetSharp.Column.Values; using ParquetSharp.IO; using ParquetSharp.IO.Api; /** * Writes (repetition level, definition level, value) triplets and deals with writing pages to the underlying layer. * * @author Julien Le Dem * */ sealed class ColumnWriterV1 : ColumnWriter { private static readonly Log LOG = Log.getLog(typeof(ColumnWriterV1)); private static readonly bool DEBUG = Log.DEBUG; private readonly ColumnDescriptor path; private readonly PageWriter pageWriter; private readonly ParquetProperties props; private ValuesWriter repetitionLevelColumn; private ValuesWriter definitionLevelColumn; private ValuesWriter dataColumn; private int valueCount; private int valueCountForNextSizeCheck; private Statistics statistics; public ColumnWriterV1(ColumnDescriptor path, PageWriter pageWriter, ParquetProperties props) { this.path = path; this.pageWriter = pageWriter; this.props = props; // initial check of memory usage. So that we have enough data to make an initial prediction this.valueCountForNextSizeCheck = props.getMinRowCountForPageSizeCheck(); resetStatistics(); this.repetitionLevelColumn = props.newRepetitionLevelWriter(path); this.definitionLevelColumn = props.newDefinitionLevelWriter(path); this.dataColumn = props.newValuesWriter(path); } private void log(object value, int r, int d) { LOG.debug(path + " " + value + " r:" + r + " d:" + d); } private void resetStatistics() { this.statistics = Statistics.getStatsBasedOnType(this.path.getType()); } /** * Counts how many values have been written and checks the memory usage to flush the page when we reach the page threshold. * * We measure the memory used when we reach the mid point toward our estimated count. * We then update the estimate and flush the page if we reached the threshold. * * That way we check the memory size log2(n) times. * */ private void accountForValueWritten() { ++valueCount; if (valueCount > valueCountForNextSizeCheck) { // not checking the memory used for every value long memSize = repetitionLevelColumn.getBufferedSize() + definitionLevelColumn.getBufferedSize() + dataColumn.getBufferedSize(); if (memSize > props.getPageSizeThreshold()) { // we will write the current page and check again the size at the predicted middle of next page if (props.estimateNextSizeCheck()) { valueCountForNextSizeCheck = valueCount / 2; } else { valueCountForNextSizeCheck = props.getMinRowCountForPageSizeCheck(); } writePage(); } else if (props.estimateNextSizeCheck()) { // not reached the threshold, will check again midway valueCountForNextSizeCheck = (int)(valueCount + ((float)valueCount * props.getPageSizeThreshold() / memSize)) / 2 + 1; } else { valueCountForNextSizeCheck += props.getMinRowCountForPageSizeCheck(); } } } private void updateStatisticsNumNulls() { statistics.incrementNumNulls(); } private void updateStatistics(int value) { statistics.updateStats(value); } private void updateStatistics(long value) { statistics.updateStats(value); } private void updateStatistics(float value) { statistics.updateStats(value); } private void updateStatistics(double value) { statistics.updateStats(value); } private void updateStatistics(Binary value) { statistics.updateStats(value); } private void updateStatistics(bool value) { statistics.updateStats(value); } private void writePage() { if (Log.DEBUG) LOG.debug("write page"); try { pageWriter.writePage( BytesInput.concat(repetitionLevelColumn.getBytes(), definitionLevelColumn.getBytes(), dataColumn.getBytes()), valueCount, statistics, repetitionLevelColumn.getEncoding(), definitionLevelColumn.getEncoding(), dataColumn.getEncoding()); } catch (IOException e) { throw new ParquetEncodingException("could not write page for " + path, e); } repetitionLevelColumn.reset(); definitionLevelColumn.reset(); dataColumn.reset(); valueCount = 0; resetStatistics(); } public void writeNull(int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(null, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); updateStatisticsNumNulls(); accountForValueWritten(); } public void write(double value, int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(value, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); dataColumn.writeDouble(value); updateStatistics(value); accountForValueWritten(); } public void write(float value, int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(value, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); dataColumn.writeFloat(value); updateStatistics(value); accountForValueWritten(); } public void write(Binary value, int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(value, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); dataColumn.writeBytes(value); updateStatistics(value); accountForValueWritten(); } public void write(bool value, int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(value, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); dataColumn.writeBoolean(value); updateStatistics(value); accountForValueWritten(); } public void write(int value, int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(value, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); dataColumn.writeInteger(value); updateStatistics(value); accountForValueWritten(); } public void write(long value, int repetitionLevel, int definitionLevel) { if (Log.DEBUG) log(value, repetitionLevel, definitionLevel); repetitionLevelColumn.writeInteger(repetitionLevel); definitionLevelColumn.writeInteger(definitionLevel); dataColumn.writeLong(value); updateStatistics(value); accountForValueWritten(); } public void flush() { if (valueCount > 0) { writePage(); } DictionaryPage dictionaryPage = dataColumn.toDictPageAndClose(); if (dictionaryPage != null) { if (Log.DEBUG) LOG.debug("write dictionary"); try { pageWriter.writeDictionaryPage(dictionaryPage); } catch (IOException e) { throw new ParquetEncodingException("could not write dictionary page for " + path, e); } dataColumn.resetDictionary(); } } public void close() { flush(); // Close the Values writers. repetitionLevelColumn.close(); definitionLevelColumn.close(); dataColumn.close(); } public long getBufferedSizeInMemory() { return repetitionLevelColumn.getBufferedSize() + definitionLevelColumn.getBufferedSize() + dataColumn.getBufferedSize() + pageWriter.getMemSize(); } public long allocatedSize() { return repetitionLevelColumn.getAllocatedSize() + definitionLevelColumn.getAllocatedSize() + dataColumn.getAllocatedSize() + pageWriter.allocatedSize(); } public string memUsageString(string indent) { StringBuilder b = new StringBuilder(indent).Append(path).Append(" {\n"); b.Append(repetitionLevelColumn.memUsageString(indent + " r:")).Append("\n"); b.Append(definitionLevelColumn.memUsageString(indent + " d:")).Append("\n"); b.Append(dataColumn.memUsageString(indent + " data:")).Append("\n"); b.Append(pageWriter.memUsageString(indent + " pages:")).Append("\n"); // TODO: %,d ? b.Append(indent).Append(string.Format(CultureInfo.InvariantCulture, " total: {0}/{1}", getBufferedSizeInMemory(), allocatedSize())).Append("\n"); b.Append(indent).Append("}\n"); return b.ToString(); } } }
// 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 ga = Google.Api; using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using proto = Google.Protobuf; using wkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.RecommendationEngine.V1Beta1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedUserEventServiceClientTest { [xunit::FactAttribute] public void WriteUserEventRequestObject() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent response = client.WriteUserEvent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WriteUserEventRequestObjectAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent responseCallSettings = await client.WriteUserEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserEvent responseCancellationToken = await client.WriteUserEventAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void WriteUserEvent() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent response = client.WriteUserEvent(request.Parent, request.UserEvent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WriteUserEventAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent responseCallSettings = await client.WriteUserEventAsync(request.Parent, request.UserEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserEvent responseCancellationToken = await client.WriteUserEventAsync(request.Parent, request.UserEvent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void WriteUserEventResourceNames() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent response = client.WriteUserEvent(request.ParentAsEventStoreName, request.UserEvent); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task WriteUserEventResourceNamesAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); WriteUserEventRequest request = new WriteUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = new UserEvent(), }; UserEvent expectedResponse = new UserEvent { EventType = "event_type1436d01c", UserInfo = new UserInfo(), EventDetail = new EventDetail(), ProductEventDetail = new ProductEventDetail(), EventTime = new wkt::Timestamp(), EventSource = UserEvent.Types.EventSource.Automl, }; mockGrpcClient.Setup(x => x.WriteUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<UserEvent>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); UserEvent responseCallSettings = await client.WriteUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); UserEvent responseCancellationToken = await client.WriteUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CollectUserEventRequestObject() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody response = client.CollectUserEvent(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CollectUserEventRequestObjectAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::HttpBody>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody responseCallSettings = await client.CollectUserEventAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::HttpBody responseCancellationToken = await client.CollectUserEventAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CollectUserEvent() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody response = client.CollectUserEvent(request.Parent, request.UserEvent, request.Uri, request.Ets); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CollectUserEventAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::HttpBody>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody responseCallSettings = await client.CollectUserEventAsync(request.Parent, request.UserEvent, request.Uri, request.Ets, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::HttpBody responseCancellationToken = await client.CollectUserEventAsync(request.Parent, request.UserEvent, request.Uri, request.Ets, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void CollectUserEventResourceNames() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEvent(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody response = client.CollectUserEvent(request.ParentAsEventStoreName, request.UserEvent, request.Uri, request.Ets); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task CollectUserEventResourceNamesAsync() { moq::Mock<UserEventService.UserEventServiceClient> mockGrpcClient = new moq::Mock<UserEventService.UserEventServiceClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); CollectUserEventRequest request = new CollectUserEventRequest { ParentAsEventStoreName = EventStoreName.FromProjectLocationCatalogEventStore("[PROJECT]", "[LOCATION]", "[CATALOG]", "[EVENT_STORE]"), UserEvent = "user_eventc8146d99", Uri = "uri3db70593", Ets = -4649673071663131288L, }; ga::HttpBody expectedResponse = new ga::HttpBody { ContentType = "content_type085be0ea", Data = proto::ByteString.CopyFromUtf8("data387f778d"), Extensions = { new wkt::Any(), }, }; mockGrpcClient.Setup(x => x.CollectUserEventAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ga::HttpBody>(stt::Task.FromResult(expectedResponse), null, null, null, null)); UserEventServiceClient client = new UserEventServiceClientImpl(mockGrpcClient.Object, null); ga::HttpBody responseCallSettings = await client.CollectUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, request.Uri, request.Ets, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ga::HttpBody responseCancellationToken = await client.CollectUserEventAsync(request.ParentAsEventStoreName, request.UserEvent, request.Uri, request.Ets, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Python Tools for Visual Studio // 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, // MERCHANTABILITY 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.Text.RegularExpressions; namespace Microsoft.PythonTools { public enum TestFrameworkType { None = 0, Pytest = 1, UnitTest = 2 } static class PythonConstants { //Language name public const string LanguageName = "Python"; internal const string TextEditorSettingsRegistryKey = LanguageName; internal const string ProjectFileFilter = "Python Project File (*.pyproj)\n*.pyproj\nAll Files (*.*)\n*.*\n"; /// <summary> /// The extension for Python files which represent Windows applications. /// </summary> internal const string ProjectImageList = "Microsoft.PythonImageList.png"; internal const string FileExtension = ".py"; internal const string WindowsFileExtension = ".pyw"; internal const string StubFileExtension = ".pyi"; internal const string SourceFileExtensions = ".py;.pyw;.pyi"; internal static readonly string[] SourceFileExtensionsArray = SourceFileExtensions.Split(';'); internal const string LibraryManagerGuid = "888888e5-b976-4366-9e98-e7bc01f1842c"; internal const string LibraryManagerServiceGuid = "88888859-2f95-416e-9e2b-cac4678e5af7"; public const string ProjectFactoryGuid = "888888a0-9f3d-457c-b088-3a5042f75d52"; internal const string WebProjectFactoryGuid = "1b580a1a-fdb3-4b32-83e1-6407eb2722e6"; internal const string EditorFactoryGuid = "888888c4-36f9-4453-90aa-29fa4d2e5706"; internal const string ProjectNodeGuid = "8888881a-afb8-42b1-8398-e60d69ee864d"; public const string GeneralPropertyPageGuid = "888888fd-3c4a-40da-aefb-5ac10f5e8b30"; public const string DebugPropertyPageGuid = "9A46BC86-34CB-4597-83E5-498E3BDBA20A"; public const string PublishPropertyPageGuid = "63DF0877-CF53-4975-B200-2B11D669AB00"; public const string TestPropertyPageGuid = "D3B8505A-A2A7-49ED-B2C1-400136801EC6"; internal const string WebPropertyPageGuid = "76EED3B5-14B1-413B-937A-F6F79AC1F8C8"; internal const string EditorFactoryPromptForEncodingGuid = "CA887E0B-55C6-4AE9-B5CF-A2EEFBA90A3E"; internal const string InterpreterItemType = "32235F49-CF87-4F2C-A986-B38D229976A3"; internal const string InterpretersPackageItemType = "64D8C685-F085-4E04-B759-3DF715EBA3FA"; internal static readonly Guid InterpreterItemTypeGuid = new Guid(InterpreterItemType); internal static readonly Guid InterpretersPackageItemTypeGuid = new Guid(InterpretersPackageItemType); internal const string InterpretersPropertiesGuid = "45D3DC23-F419-4744-B55B-B897FAC1F4A2"; internal const string InterpretersWithBaseInterpreterPropertiesGuid = "F86C3C5B-CF94-4184-91F8-29687D3B9227"; internal const string InterpretersPackagePropertiesGuid = "BBF56A45-B037-4CC2-B710-F2CE304CCF32"; internal const string InterpreterListToolWindowGuid = "75504045-D02F-44E5-BF60-5F60DF380E8B"; // Do not change below info without re-requesting PLK: internal const string ProjectSystemPackageGuid = "15490272-3C6B-4129-8E1D-795C8B6D8E9F"; //matches PLK // IDs of the icons for product registration (see Resources.resx) internal const int IconIfForSplashScreen = 300; internal const int IconIdForAboutBox = 400; // Command IDs internal const int AddEnvironment = 0x4006; internal const int AddVirtualEnv = 0x4007; internal const int AddExistingEnv = 0x4008; internal const int ActivateEnvironment = 0x4009; internal const int InstallPythonPackage = 0x400A; internal const int InstallRequirementsTxt = 0x4033; internal const int GenerateRequirementsTxt = 0x4034; internal const int ProcessRequirementsTxt = 0x4036; // deprecated internal const int AddCondaEnv = 0x4037; internal const int OpenInteractiveForEnvironment = 0x4031; internal const int ViewAllEnvironments = 0x400B; internal const int AddSearchPathCommandId = 0x4002; internal const int AddSearchPathZipCommandId = 0x4003; internal const int AddPythonPathToSearchPathCommandId = 0x4030; // Context menu IDs internal const int EnvironmentsContainerMenuId = 0x2006; internal const int EnvironmentMenuId = 0x2007; internal const int EnvironmentPackageMenuId = 0x2008; internal const int SearchPathContainerMenuId = 0x2009; internal const int SearchPathMenuId = 0x200A; internal const int ReplWindowToolbar = 0x200B; internal const int EnvironmentStatusBarMenu = 0x200D; // Custom (per-project) commands internal const int FirstCustomCmdId = 0x4010; internal const int LastCustomCmdId = 0x402F; internal const int CustomProjectCommandsMenu = 0x2005; // Environments status bar switcher commands internal const int FirstEnvironmentCmdId = 0x4050; internal const int LastEnvironmentCmdId = 0x4090; // Shows up before references internal const int InterpretersContainerNodeSortPriority = 200; // Appears after references internal const int SearchPathContainerNodeSortPriority = 400; // Maximal sort priority for Search Path nodes internal const int SearchPathNodeMaxSortPriority = 110; internal const string InterpreterId = "InterpreterId"; internal const string InterpreterVersion = "InterpreterVersion"; internal const string LaunchProvider = "LaunchProvider"; internal const string PythonExtension = "PythonExtension"; public const string SearchPathSetting = "SearchPath"; public const string InterpreterPathSetting = "InterpreterPath"; public const string InterpreterArgumentsSetting = "InterpreterArguments"; public const string CommandLineArgumentsSetting = "CommandLineArguments"; public const string StartupFileSetting = "StartupFile"; public const string IsWindowsApplicationSetting = "IsWindowsApplication"; public const string EnvironmentSetting = "Environment"; public const string TestFrameworkSetting = "TestFramework"; public const string UnitTestRootDirectorySetting = "UnitTestRootDirectory"; public const string DefaultUnitTestRootDirectory = "."; public const string UnitTestPatternSetting = "UnitTestPattern"; public const string DefaultUnitTestPattern = "test*.py"; public static readonly Regex DefaultTestFileNameRegex = new Regex(@"((^test.*)|(^.*_test))\.(py|txt)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static readonly Regex TestFileExtensionRegex = new Regex(@".*\.(py|txt)$", RegexOptions.Compiled | RegexOptions.IgnoreCase); public static readonly HashSet<string> PyTestFrameworkConfigFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase) {"pytest.ini", "setup.cfg", "tox.ini"}; /// <summary> /// Specifies port to which to open web browser on launch. /// </summary> public const string WebBrowserPortSetting = "WebBrowserPort"; /// <summary> /// Specifies URL to which to open web browser on launch. /// </summary> public const string WebBrowserUrlSetting = "WebBrowserUrl"; /// <summary> /// When True, prevents web projects from copying Cloud Service files /// into their bin directory. /// </summary> public const string SuppressCollectPythonCloudServiceFiles = "SuppressCollectPythonCloudServiceFiles"; /// <summary> /// Specifies local address for the web server to listen on. /// </summary> public const string WebServerHostSetting = "WebServerHost"; // Mixed-mode debugging project property public const string EnableNativeCodeDebugging = "EnableNativeCodeDebugging"; // Suppress the prompt for environment creation project property public const string SuppressEnvironmentCreationPrompt = "SuppressEnvironmentCreationPrompt"; // Suppress the prompt for package installation project property public const string SuppressPackageInstallationPrompt = "SuppressPackageInstallationPrompt"; // Suppress the prompt for pytest configuration project property public const string SuppressConfigureTestFrameworkPrompt = "SuppressConfigureTestFrameworkPrompt"; // Suppress the prompt for python version not supported property public const string SuppressPythonVersionNotSupportedPrompt = "SuppressPythonVersionNotSupportedPrompt"; // Launch option to ignore pause on exist settings internal const string NeverPauseOnExit = "NeverPauseOnExit"; public const string WorkingDirectorySetting = "WorkingDirectory"; public const string ProjectHomeSetting = "ProjectHome"; /// <summary> /// The canonical name of the debug launcher for web projects. /// </summary> public const string WebLauncherName = "Web launcher"; /// <summary> /// The settings collection where "Suppress{dialog}" settings are stored /// </summary> public const string DontShowUpgradeDialogAgainCollection = "PythonTools\\Dialogs"; internal const string PythonToolsProcessIdEnvironmentVariable = "_PTVS_PID"; internal const string UnitTestExecutorUriString = "executor://PythonUnitTestExecutor/v1"; internal const string PytestExecutorUriString = "executor://PythonPyTestExecutor/v1"; internal const string PythonProjectContainerDiscovererUriString = "executor://PythonProjectDiscoverer/v1"; internal const string PythonWorkspaceContainerDiscovererUriString = "executor://PythonWorkspaceDiscoverer/v1"; internal const string PythonCodeCoverageUriString = "datacollector://Microsoft/PythonCodeCoverage/1.0"; public static readonly Uri UnitTestExecutorUri = new Uri(UnitTestExecutorUriString); public static readonly Uri PytestExecutorUri = new Uri(PytestExecutorUriString); public static readonly Uri PythonProjectContainerDiscovererUri = new Uri(PythonProjectContainerDiscovererUriString); public static readonly Uri PythonWorkspaceContainerDiscovererUri = new Uri(PythonWorkspaceContainerDiscovererUriString); public static readonly Uri PythonCodeCoverageUri = new Uri(PythonCodeCoverageUriString); //Discovery internal const string PytestText = "pytest"; internal const string UnitTestText = "unittest"; internal const int DiscoveryTimeoutInSeconds = 60; } }
// created on 09/07/2003 at 20:20 // Npgsql.NpgsqlParameterCollection.cs // // Author: // Brar Piening (brar@gmx.de) // // Rewritten from the scratch to derive from MarshalByRefObject instead of ArrayList. // Recycled some parts of the original NpgsqlParameterCollection.cs // by Francisco Jr. (fxjrlists@yahoo.com.br) // // Copyright (C) 2002 The Npgsql Development Team // npgsql-general@gborg.postgresql.org // http://gborg.postgresql.org/project/npgsql/projdisplay.php // // Permission to use, copy, modify, and distribute this software and its // documentation for any purpose, without fee, and without a written // agreement is hereby granted, provided that the above copyright notice // and this paragraph and the following two paragraphs appear in all copies. // // IN NO EVENT SHALL THE NPGSQL DEVELOPMENT TEAM BE LIABLE TO ANY PARTY // FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, // INCLUDING LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS // DOCUMENTATION, EVEN IF THE NPGSQL DEVELOPMENT TEAM HAS BEEN ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // // THE NPGSQL DEVELOPMENT TEAM SPECIFICALLY DISCLAIMS ANY WARRANTIES, // INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY // AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS // ON AN "AS IS" BASIS, AND THE NPGSQL DEVELOPMENT TEAM HAS NO OBLIGATIONS // TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data.Common; using Revenj.DatabasePersistence.Postgres.NpgsqlTypes; namespace Revenj.DatabasePersistence.Postgres.Npgsql { /// <summary> /// Represents a collection of parameters relevant to a <see cref="Npgsql.NpgsqlCommand">NpgsqlCommand</see> /// as well as their respective mappings to columns in a <see cref="System.Data.DataSet">DataSet</see>. /// This class cannot be inherited. /// </summary> public sealed class NpgsqlParameterCollection : DbParameterCollection, IList<NpgsqlParameter> { private readonly List<NpgsqlParameter> InternalList = new List<NpgsqlParameter>(); /// <summary> /// Initializes a new instance of the NpgsqlParameterCollection class. /// </summary> internal NpgsqlParameterCollection() { } #region NpgsqlParameterCollection Member /// <summary> /// Gets the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> with the specified name. /// </summary> /// <param name="parameterName">The name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to retrieve.</param> /// <value>The <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> with the specified name, or a null reference if the parameter is not found.</value> public new NpgsqlParameter this[string parameterName] { get { return this.InternalList[IndexOf(parameterName)]; } set { this.InternalList[IndexOf(parameterName)] = value; } } /// <summary> /// Gets the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> at the specified index. /// </summary> /// <param name="index">The zero-based index of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to retrieve.</param> /// <value>The <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> at the specified index.</value> public new NpgsqlParameter this[int index] { get { return this.InternalList[index]; } set { this.InternalList[index] = value; } } /// <summary> /// Adds the specified <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see>. /// </summary> /// <param name="value">The <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to add to the collection.</param> /// <returns>The index of the new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.</returns> public NpgsqlParameter Add(NpgsqlParameter value) { // Do not allow parameters without name. this.InternalList.Add(value); // Check if there is a name. If not, add a name based in the index of parameter. if (value.ParameterName.Trim() == String.Empty || (value.ParameterName.Length == 1 && value.ParameterName[0] == ':')) { value.ParameterName = ":" + "Parameter" + (IndexOf(value) + 1); } return value; } public NpgsqlParameter AddWithValue(string parameterName, object value) { return this.Add(new NpgsqlParameter(parameterName, value)); } /// <summary> /// Adds a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see> given the parameter name and the data type. /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="parameterType">One of the DbType values.</param> /// <returns>The index of the new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.</returns> public NpgsqlParameter Add(string parameterName, NpgsqlDbType parameterType) { return this.Add(new NpgsqlParameter(parameterName, parameterType)); } /// <summary> /// Adds a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see> with the parameter name, the data type, and the column length. /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="parameterType">One of the DbType values.</param> /// <param name="size">The length of the column.</param> /// <returns>The index of the new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.</returns> public NpgsqlParameter Add(string parameterName, NpgsqlDbType parameterType, int size) { return this.Add(new NpgsqlParameter(parameterName, parameterType, size)); } /// <summary> /// Adds a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see> with the parameter name, the data type, the column length, and the source column name. /// </summary> /// <param name="parameterName">The name of the parameter.</param> /// <param name="parameterType">One of the DbType values.</param> /// <param name="size">The length of the column.</param> /// <param name="sourceColumn">The name of the source column.</param> /// <returns>The index of the new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.</returns> public NpgsqlParameter Add(string parameterName, NpgsqlDbType parameterType, int size, string sourceColumn) { return this.Add(new NpgsqlParameter(parameterName, parameterType, size, sourceColumn)); } #endregion #region IDataParameterCollection Member /// <summary> /// Removes the specified <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> from the collection using the parameter name. /// </summary> /// <param name="parameterName">The name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to retrieve.</param> public override void RemoveAt(string parameterName) { this.InternalList.RemoveAt(IndexOf(parameterName)); } /// <summary> /// Gets a value indicating whether a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> with the specified parameter name exists in the collection. /// </summary> /// <param name="parameterName">The name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to find.</param> /// <returns><b>true</b> if the collection contains the parameter; otherwise, <b>false</b>.</returns> public override bool Contains(string parameterName) { return (IndexOf(parameterName) != -1); } /// <summary> /// Gets the location of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> in the collection with a specific parameter name. /// </summary> /// <param name="parameterName">The name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to find.</param> /// <returns>The zero-based location of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> in the collection.</returns> public override int IndexOf(string parameterName) { // Iterate values to see what is the index of parameter. int index = 0; int bestChoose = -1; if ((parameterName[0] == ':') || (parameterName[0] == '@')) { parameterName = parameterName.Remove(0, 1); } foreach (NpgsqlParameter parameter in this) { // allow for optional use of ':' and '@' in the ParameterName property string cleanName = parameter.CleanName; if (cleanName == parameterName) { return index; } if (string.Compare(parameterName, cleanName, StringComparison.InvariantCultureIgnoreCase) == 0) { bestChoose = index; } index++; } return bestChoose; } #endregion #region IList Member public override bool IsReadOnly { get { return false; } } /// <summary> /// Removes the specified <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> from the collection using a specific index. /// </summary> /// <param name="index">The zero-based index of the parameter.</param> public override void RemoveAt(int index) { this.InternalList.RemoveAt(index); } /// <summary> /// Inserts a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> into the collection at the specified index. /// </summary> /// <param name="index">The zero-based index where the parameter is to be inserted within the collection.</param> /// <param name="value">The <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to add to the collection.</param> public override void Insert(int index, object value) { CheckType(value); this.InternalList.Insert(index, (NpgsqlParameter)value); } /// <summary> /// Removes the specified <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> from the collection. /// </summary> /// <param name="value">The <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to remove from the collection.</param> public override void Remove(object value) { CheckType(value); this.InternalList.Remove((NpgsqlParameter)value); } /// <summary> /// Gets a value indicating whether a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> exists in the collection. /// </summary> /// <param name="value">The value of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to find.</param> /// <returns>true if the collection contains the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object; otherwise, false.</returns> public override bool Contains(object value) { if (!(value is NpgsqlParameter)) { return false; } return this.InternalList.Contains((NpgsqlParameter)value); } /// <summary> /// Gets a value indicating whether a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> with the specified parameter name exists in the collection. /// </summary> /// <param name="parameterName">The name of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to find.</param> /// <param name="parameter">A reference to the requested parameter is returned in this out param if it is found in the list. This value is null if the parameter is not found.</param> /// <returns><b>true</b> if the collection contains the parameter and param will contain the parameter; otherwise, <b>false</b>.</returns> public bool TryGetValue(string parameterName, out NpgsqlParameter parameter) { int index = IndexOf(parameterName); if (index != -1) { parameter = this[index]; return true; } else { parameter = null; return false; } } /// <summary> /// Removes all items from the collection. /// </summary> public override void Clear() { this.InternalList.Clear(); } /// <summary> /// Gets the location of a <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> in the collection. /// </summary> /// <param name="value">The value of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to find.</param> /// <returns>The zero-based index of the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object in the collection.</returns> public override int IndexOf(object value) { CheckType(value); return this.InternalList.IndexOf((NpgsqlParameter)value); } /// <summary> /// Adds the specified <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object to the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see>. /// </summary> /// <param name="value">The <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> to add to the collection.</param> /// <returns>The zero-based index of the new <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> object.</returns> public override int Add(object value) { CheckType(value); this.Add((NpgsqlParameter)value); return IndexOf(value); } public override bool IsFixedSize { get { return false; } } #endregion #region ICollection Member public override bool IsSynchronized { get { return (InternalList as ICollection).IsSynchronized; } } /// <summary> /// Gets the number of <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> objects in the collection. /// </summary> /// <value>The number of <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> objects in the collection.</value> public override int Count { get { return this.InternalList.Count; } } /// <summary> /// Copies <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> objects from the <see cref="Npgsql.NpgsqlParameterCollection">NpgsqlParameterCollection</see> to the specified array. /// </summary> /// <param name="array">An <see cref="System.Array">Array</see> to which to copy the <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> objects in the collection.</param> /// <param name="index">The starting index of the array.</param> public override void CopyTo(Array array, int index) { (InternalList as ICollection).CopyTo(array, index); IRaiseItemChangedEvents x = InternalList as IRaiseItemChangedEvents; } public override object SyncRoot { get { return (InternalList as ICollection).SyncRoot; } } #endregion #region IEnumerable Member /// <summary> /// Returns an enumerator that can iterate through the collection. /// </summary> /// <returns>An <see cref="System.Collections.IEnumerator">IEnumerator</see> that can be used to iterate through the collection.</returns> public override IEnumerator GetEnumerator() { return this.InternalList.GetEnumerator(); } #endregion public override void AddRange(Array values) { foreach (NpgsqlParameter parameter in values) { Add(parameter); } } protected override DbParameter GetParameter(string parameterName) { return this[parameterName]; } protected override DbParameter GetParameter(int index) { return this[index]; } protected override void SetParameter(string parameterName, DbParameter value) { this[parameterName] = (NpgsqlParameter)value; } protected override void SetParameter(int index, DbParameter value) { this[index] = (NpgsqlParameter)value; } /// <summary> /// In methods taking an object as argument this method is used to verify /// that the argument has the type <see cref="Npgsql.NpgsqlParameter">NpgsqlParameter</see> /// </summary> /// <param name="Object">The object to verify</param> private void CheckType(object Object) { if (!(Object is NpgsqlParameter)) throw new InvalidCastException(string.Format("Can't cast {0} into NpgsqlParameter", Object.GetType())); } NpgsqlParameter IList<NpgsqlParameter>.this[int index] { get { return InternalList[index]; } set { InternalList[index] = value; } } public int IndexOf(NpgsqlParameter item) { return InternalList.IndexOf(item); } public void Insert(int index, NpgsqlParameter item) { InternalList.Insert(index, item); } public bool Contains(NpgsqlParameter item) { return InternalList.Contains(item); } public bool Remove(NpgsqlParameter item) { return Remove(item); } IEnumerator<NpgsqlParameter> IEnumerable<NpgsqlParameter>.GetEnumerator() { return InternalList.GetEnumerator(); } public void CopyTo(NpgsqlParameter[] array, int arrayIndex) { InternalList.CopyTo(array, arrayIndex); } void ICollection<NpgsqlParameter>.Add(NpgsqlParameter item) { Add(item); } } }
using OpenKh.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xe.BinaryMapper; namespace OpenKh.Kh2.Ard { public class SpawnPoint { public class Entity { private class Raw { [Data] public int ObjectId { get; set; } [Data] public float PositionX { get; set; } [Data] public float PositionY { get; set; } [Data] public float PositionZ { get; set; } [Data] public float RotationX { get; set; } [Data] public float RotationY { get; set; } [Data] public float RotationZ { get; set; } [Data] public byte SpawnType { get; set; } [Data] public byte SpawnArgument { get; set; } [Data] public short Serial { get; set; } [Data] public int Argument1 { get; set; } [Data] public int Argument2 { get; set; } [Data] public short ReactionCommand { get; set; } [Data] public short SpawnDelay { get; set; } [Data] public short Command { get; set; } [Data] public short SpawnRange { get; set; } [Data] public byte Level { get; set; } [Data] public byte Medal { get; set; } [Data] public short Reserved32 { get; set; } [Data] public int Reserved34 { get; set; } [Data] public int Reserved38 { get; set; } [Data] public int Reserved3c { get; set; } } public int ObjectId { get; set; } public float PositionX { get; set; } public float PositionY { get; set; } public float PositionZ { get; set; } public float RotationX { get; set; } public float RotationY { get; set; } public float RotationZ { get; set; } public byte SpawnType { get; set; } public byte SpawnArgument { get; set; } public short Serial { get; set; } public int Argument1 { get; set; } public int Argument2 { get; set; } public short ReactionCommand { get; set; } public short SpawnDelay { get; set; } public short Command { get; set; } public short SpawnRange { get; set; } public byte Level { get; set; } public byte Medal { get; set; } public static Entity Read(Stream stream) { var raw = BinaryMapping.ReadObject<Raw>(stream); return new Entity { ObjectId = raw.ObjectId, PositionX = raw.PositionX, PositionY = raw.PositionY, PositionZ = raw.PositionZ, RotationX = raw.RotationX, RotationY = raw.RotationY, RotationZ = raw.RotationZ, SpawnType = raw.SpawnType, SpawnArgument = raw.SpawnArgument, Serial = raw.Serial, Argument1 = raw.Argument1, Argument2 = raw.Argument2, ReactionCommand = raw.ReactionCommand, SpawnDelay = raw.SpawnDelay, Command = raw.Command, SpawnRange = raw.SpawnRange, Level = raw.Level, Medal = raw.Medal, }; } public static void Write(Stream stream, Entity entity) => BinaryMapping.WriteObject(stream, new Raw { ObjectId = entity.ObjectId, PositionX = entity.PositionX, PositionY = entity.PositionY, PositionZ = entity.PositionZ, RotationX = entity.RotationX, RotationY = entity.RotationY, RotationZ = entity.RotationZ, SpawnType = entity.SpawnType, SpawnArgument = entity.SpawnArgument, Serial = entity.Serial, Argument1 = entity.Argument1, Argument2 = entity.Argument2, ReactionCommand = entity.ReactionCommand, SpawnDelay = entity.SpawnDelay, Command = entity.Command, SpawnRange = entity.SpawnRange, Level = entity.Level, Medal = entity.Medal, }); public override string ToString() => $"ID {ObjectId} POS({PositionX:F0}, {PositionY:F0}, {PositionZ:F0}) ROT({RotationX:F0}, {RotationY:F0}, {RotationZ:F0})"; } public class EventActivator { private class Raw { [Data] public short Shape { get; set; } [Data] public short Option { get; set; } [Data] public float PositionX { get; set; } [Data] public float PositionY { get; set; } [Data] public float PositionZ { get; set; } [Data] public float ScaleX { get; set; } [Data] public float ScaleY { get; set; } [Data] public float ScaleZ { get; set; } [Data] public float RotationX { get; set; } [Data] public float RotationY { get; set; } [Data] public float RotationZ { get; set; } [Data] public int Flags { get; set; } [Data] public short Type { get; set; } [Data] public byte OnBgGroup { get; set; } [Data] public byte OffBgGroup { get; set; } [Data] public int Padding30 { get; set; } [Data] public int Padding34 { get; set; } [Data] public int Padding38 { get; set; } [Data] public int Padding3c { get; set; } } public short Shape { get; set; } public short Option { get; set; } public float PositionX { get; set; } public float PositionY { get; set; } public float PositionZ { get; set; } public float ScaleX { get; set; } public float ScaleY { get; set; } public float ScaleZ { get; set; } public float RotationX { get; set; } public float RotationY { get; set; } public float RotationZ { get; set; } public int Flags { get; set; } public short Type { get; set; } public byte OnBgGroup { get; set; } public byte OffBgGroup { get; set; } public static EventActivator Read(Stream stream) { var raw = BinaryMapping.ReadObject<Raw>(stream); return new EventActivator { Shape = raw.Shape, Option = raw.Option, PositionX = raw.PositionX, PositionY = raw.PositionY, PositionZ = raw.PositionZ, ScaleX = raw.ScaleX, ScaleY = raw.ScaleY, ScaleZ = raw.ScaleZ, RotationX = raw.RotationX, RotationY = raw.RotationY, RotationZ = raw.RotationZ, Flags = raw.Flags, Type = raw.Type, OnBgGroup = raw.OnBgGroup, OffBgGroup = raw.OffBgGroup, }; } public static void Write(Stream stream, EventActivator activator) => BinaryMapping.WriteObject(stream, new Raw { Shape = activator.Shape, Option = activator.Option, PositionX = activator.PositionX, PositionY = activator.PositionY, PositionZ = activator.PositionZ, ScaleX = activator.ScaleX, ScaleY = activator.ScaleY, ScaleZ = activator.ScaleZ, RotationX = activator.RotationX, RotationY = activator.RotationY, RotationZ = activator.RotationZ, Flags = activator.Flags, Type = activator.Type, OnBgGroup = activator.OnBgGroup, OffBgGroup = activator.OffBgGroup, }); public override string ToString() => $"Shape {Shape} Option {Option} POS({PositionX:F0}, {PositionY:F0}, {PositionZ:F0}) SCL({ScaleX:F0}, {ScaleY:F0}, {ScaleZ:F0}) ROT({RotationX:F0}, {RotationY:F0}, {RotationZ:F0}) " + $"Flags {Flags:X}, Type {Type}, OnBg {OnBgGroup:X}, OffBg {OffBgGroup:X}"; } public class WalkPathDesc { private class Raw { [Data] public short Serial { get; set; } [Data] public short Count { get; set; } [Data] public byte Flag { get; set; } [Data] public byte Id { get; set; } [Data] public short Reserved { get; set; } } public short Serial { get; set; } public byte Flag { get; set; } public byte Id { get; set; } public List<Position> Positions { get; set; } public static WalkPathDesc Read(Stream stream) { var header = BinaryMapping.ReadObject<Raw>(stream); return new WalkPathDesc { Serial = header.Serial, Flag = header.Flag, Id = header.Id, Positions = Enumerable.Range(0, header.Count) .Select(_ => BinaryMapping.ReadObject<Position>(stream)) .ToList() }; } public static void Write(Stream stream, WalkPathDesc entity) { BinaryMapping.WriteObject(stream, new Raw { Serial = entity.Serial, Flag = entity.Flag, Count = (short)entity.Positions.Count, Id = entity.Id, }); foreach (var position in entity.Positions) BinaryMapping.WriteObject(stream, position); } public override string ToString() => $"Serial {Serial:X} Flag {Flag:X} Id {Id:X}"; } public class Position { [Data] public float X { get; set; } [Data] public float Y { get; set; } [Data] public float Z { get; set; } public override string ToString() => $"{X:F0} {Y:F0} {Z:F0}"; } public class ReturnParameter { [Data] public byte Id { get; set; } [Data] public byte Type { get; set; } [Data] public byte Rate { get; set; } [Data] public byte EntryType { get; set; } [Data] public int Argument04 { get; set; } [Data] public int Argument08 { get; set; } [Data] public int Argument0c { get; set; } public static ReturnParameter Read(Stream stream) => BinaryMapping.ReadObject<ReturnParameter>(stream); public static void Write(Stream stream, ReturnParameter entity) => BinaryMapping.WriteObject(stream, entity); } public class Signal { [Data] public ushort SignalId { get; set; } [Data] public ushort Argument { get; set; } [Data] public byte Action { get; set; } [Data] public byte Padding05 { get; set; } [Data] public byte Padding06 { get; set; } [Data] public byte Padding07 { get; set; } public static Signal Read(Stream stream) => BinaryMapping.ReadObject<Signal>(stream); public static void Write(Stream stream, Signal entity) => BinaryMapping.WriteObject(stream, entity); } private class Raw { [Data] public byte Type { get; set; } [Data] public byte Flag { get; set; } [Data] public short Id { get; set; } [Data] public short EntityCount { get; set; } [Data] public short EventActivatorCount { get; set; } [Data] public short WalkPathCount { get; set; } [Data] public short ReturnParameterCount { get; set; } [Data] public short SignalCount { get; set; } [Data] public short Reserved0e { get; set; } [Data] public int Reserved10 { get; set; } [Data] public int Reserved14 { get; set; } [Data] public int Reserved18 { get; set; } [Data] public byte Place { get; set; } [Data] public byte Door { get; set; } [Data] public byte World { get; set; } [Data] public byte Unk1f { get; set; } [Data] public int Unk20 { get; set; } [Data] public int Unk24 { get; set; } [Data] public int Unk28 { get; set; } } public class TeleportDesc { public byte Place { get; set; } public byte Door { get; set; } public byte World { get; set; } public byte Unknown { get; set; } } public byte Type { get; set; } public byte Flag { get; set; } public short Id { get; set; } public TeleportDesc Teleport { get; set; } public int Unk20 { get; set; } public int Unk24 { get; set; } public List<Entity> Entities { get; set; } public List<EventActivator> EventActivators { get; set; } public List<WalkPathDesc> WalkPath { get; set; } public List<ReturnParameter> ReturnParameters { get; set; } public List<Signal> Signals { get; set; } public override string ToString() => $"Type {Type:X} Flag {Flag:X} {Id:X}\n{string.Join("\n", Entities.Select(x => x.ToString()))}"; public static bool IsValid(Stream stream) => stream.Length >= 4 && stream.PeekUInt32() == 0x2; public static List<SpawnPoint> Read(Stream stream) { var typeId = stream.ReadInt32(); var itemCount = stream.ReadInt32(); if (itemCount <= 0) return new List<SpawnPoint>(); return Enumerable.Range(0, itemCount) .Select(x => ReadSingle(stream)) .ToList(); } public static void Write(Stream stream, List<SpawnPoint> items) { stream.Write(2); stream.Write(items.Count); foreach (var item in items) { BinaryMapping.WriteObject(stream, new Raw { Type = item.Type, Flag = item.Flag, Id = item.Id, EntityCount = (short)item.Entities.Count, EventActivatorCount = (short)item.EventActivators.Count, WalkPathCount = (short)item.WalkPath.Count, ReturnParameterCount = (short)item.ReturnParameters.Count, SignalCount = (short)item.Signals.Count, Reserved10 = 0, Reserved14 = 0, Reserved18 = 0, Place = item.Teleport.Place, Door = item.Teleport.Door, World = item.Teleport.World, Unk1f = item.Teleport.Unknown, Unk20 = item.Unk20, Unk24 = item.Unk24, Unk28 = 0, }); foreach (var spawnPoint in item.Entities) Entity.Write(stream, spawnPoint); foreach (var unk in item.EventActivators) EventActivator.Write(stream, unk); foreach (var unk in item.WalkPath) WalkPathDesc.Write(stream, unk); foreach (var unk in item.ReturnParameters) ReturnParameter.Write(stream, unk); foreach (var unk in item.Signals) Signal.Write(stream, unk); } } private static SpawnPoint ReadSingle(Stream stream) { var raw = BinaryMapping.ReadObject<Raw>(stream); var spawn = new SpawnPoint { Type = raw.Type, Flag = raw.Flag, Id = raw.Id, Teleport = new TeleportDesc { Place = raw.Place, Door = raw.Door, World = raw.World, Unknown = raw.Unk1f }, Unk20 = raw.Unk20, Unk24 = raw.Unk24, }; spawn.Entities = ReadList(stream, raw.EntityCount, Entity.Read); spawn.EventActivators = ReadList(stream, raw.EventActivatorCount, EventActivator.Read); spawn.WalkPath = ReadList(stream, raw.WalkPathCount, WalkPathDesc.Read); spawn.ReturnParameters = ReadList(stream, raw.ReturnParameterCount, ReturnParameter.Read); spawn.Signals = ReadList(stream, raw.SignalCount, Signal.Read); return spawn; } private static List<T> ReadList<T>(Stream stream, int count, Func<Stream, T> reader) => Enumerable.Range(0, count).Select(x => reader(stream)).ToList(); } }
//------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------------------------ namespace Microsoft.Tools.ServiceModel.WsatConfig { using System; using System.Collections; using System.Collections.Generic; using System.Management; using System.Threading; using System.IO; using System.Runtime.InteropServices; class RemoteHelper { // the name of the remote machine on which the commands are executed string machineName; // the class that represnets the WMI Win32_Process ManagementClass processClass; ManagementScope managementScope; const int autoEventTimeout = 90000; // 90 secs const int delayInAutoEventTimeout = 400; // 400 milliseconds internal RemoteHelper(string machineName) { this.machineName = machineName; // establish connection ConnectionOptions co = new ConnectionOptions(); co.Authentication = AuthenticationLevel.PacketPrivacy; co.Impersonation = ImpersonationLevel.Impersonate; // define the management scope managementScope = new ManagementScope("\\\\" + machineName + "\\root\\cimv2", co); // define the path used ManagementPath path = new ManagementPath("Win32_Process"); ObjectGetOptions options = new ObjectGetOptions(new ManagementNamedValueCollection(), TimeSpan.FromSeconds(15), false); // get the object for the defined path in the defined scope // this object will be the object on which the InvokeMethod will be called processClass = new ManagementClass(managementScope, path, options); } const string MethodCreate = "Create"; const string QueryProcessExitEvent = "SELECT * FROM Win32_ProcessStopTrace"; static class InputParameters { public const string CommandLine = "CommandLine"; } static class OutputParameters { public const string ProcessId = "ProcessID"; public const string ReturnValue = "ReturnValue"; } internal void ExecuteWsatProcess(string arguments) { ProcessStopTraceHandler handler; Utilities.Log("ExecuteWsatProcess(" + arguments + ")"); try { ManagementBaseObject inParams = processClass.GetMethodParameters(MethodCreate); inParams[InputParameters.CommandLine] = GetDeploymentPath() + " " + arguments; WqlEventQuery wqlEventQuery = new WqlEventQuery(QueryProcessExitEvent); ManagementEventWatcher watcher = new ManagementEventWatcher(managementScope, wqlEventQuery); handler = new ProcessStopTraceHandler(); watcher.EventArrived += new EventArrivedEventHandler(handler.Arrived); watcher.Start(); ManagementBaseObject outParams = processClass.InvokeMethod( MethodCreate, inParams, null); if (outParams.Properties[OutputParameters.ProcessId].Value == null || outParams.Properties[OutputParameters.ReturnValue].Value == null) { throw new WsatAdminException(WsatAdminErrorCode.REMOTE_MISSING_WSAT, SR.GetString(SR.ErrorRemoteWSATMissing)); } // the process ID when executing a remote command uint processID = (uint)outParams.Properties[OutputParameters.ProcessId].Value; uint result = (uint)outParams.Properties[OutputParameters.ReturnValue].Value; if (result != 0) { throw new WsatAdminException(WsatAdminErrorCode.REMOTE_MISSING_WSAT, SR.GetString(SR.ErrorRemoteWSATMissing)); } handler.ProcessId = processID; int totalDelay = 0; while (!handler.IsArrived && totalDelay < autoEventTimeout) { totalDelay += delayInAutoEventTimeout; System.Threading.Thread.Sleep(delayInAutoEventTimeout); } watcher.Stop(); } catch (WsatAdminException) { throw; } #pragma warning suppress 56500 catch (Exception e) { if (Utilities.IsCriticalException(e)) { throw; } throw new WsatAdminException(WsatAdminErrorCode.REMOTE_EXECUTION_ATTEMPT_ERROR, SR.GetString(SR.ErrorAttemptRemoteExecution, e.Message)); } if (handler.IsArrived && handler.ReturnCode != 0) { throw new WsatAdminException((WsatAdminErrorCode)handler.ReturnCode, SR.GetString(SR.ErrorRemoteExecution, handler.ReturnCode)); } else if (!handler.IsArrived) { throw new WsatAdminException(WsatAdminErrorCode.REMOTE_TIMEOUT, SR.GetString(SR.ErrorRemoteTimeout)); } Utilities.Log("ExecuteWSATProcess successfully quitted."); } internal string GetDeploymentPath() { string path = null; try { //We first check if the 4.0 install path was available. RegistryConfigurationProvider reg = new RegistryConfigurationProvider(Microsoft.Win32.RegistryHive.LocalMachine, WsatKeys.WcfSetupKey40, machineName); path = reg.ReadString(WsatKeys.RuntimeInstallPath, null); if (string.IsNullOrEmpty(path)) { //If path under 4.0 doesnt exit, check under 3.0 RegistryConfigurationProvider reg2 = new RegistryConfigurationProvider(Microsoft.Win32.RegistryHive.LocalMachine, WsatKeys.WcfSetupKey, machineName); path = reg2.ReadString(WsatKeys.RuntimeInstallPath, null); if (string.IsNullOrEmpty(path)) { throw new WsatAdminException(WsatAdminErrorCode.CANNOT_GET_REMOTE_INSTALL_PATH, SR.GetString(SR.ErrorCannotGetRemoteInstallPath)); } } path = Path.Combine(path, "WsatConfig.exe"); } catch (WsatAdminException e) { throw new WsatAdminException(WsatAdminErrorCode.CANNOT_GET_REMOTE_INSTALL_PATH, SR.GetString(SR.ErrorCannotGetRemoteInstallPath), e); } catch (ArgumentException e) // if the path in the remote registry is invalid... { throw new WsatAdminException(WsatAdminErrorCode.CANNOT_GET_REMOTE_INSTALL_PATH, SR.GetString(SR.ErrorCannotGetRemoteInstallPath), e); } return path; } } class ProcessStopTraceHandler { bool isArrived = false; uint processID = 0; uint returnCode; Dictionary<uint, uint> processesExited = new Dictionary<uint, uint>(); public uint ProcessId { get { return processID; } set { processID = value; if (value > 0) { lock (processesExited) { uint exitCode = 0; if (processesExited.TryGetValue(value, out exitCode)) { isArrived = true; returnCode = exitCode; } } } } } //Handles the event when it arrives internal void Arrived(object sender, EventArrivedEventArgs e) { uint procID = (uint)e.NewEvent.Properties["ProcessID"].Value; uint exitCode = (uint)e.NewEvent.Properties["ExitStatus"].Value; if (ProcessId == 0) { lock (processesExited) { processesExited[procID] = exitCode; } } else if (procID == this.ProcessId) { this.returnCode = exitCode; isArrived = true; } } //Used to determine whether the event has arrived or not. internal bool IsArrived { get { return isArrived; } } internal uint ReturnCode { get { return returnCode; } } } }
// Python Tools for Visual Studio // 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, // MERCHANTABILITY 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.ComponentModel; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudioTools.Wpf; namespace Microsoft.PythonTools.EnvironmentsList { internal partial class ConfigurationExtension : UserControl { public static readonly ICommand Apply = new RoutedCommand(); public static readonly ICommand Reset = new RoutedCommand(); public static readonly ICommand AutoDetect = new RoutedCommand(); public static readonly ICommand Remove = new RoutedCommand(); private readonly ConfigurationExtensionProvider _provider; public ConfigurationExtension(ConfigurationExtensionProvider provider) { _provider = provider; DataContextChanged += ConfigurationExtension_DataContextChanged; InitializeComponent(); } void ConfigurationExtension_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e) { var view = e.NewValue as EnvironmentView; if (view != null) { var current = Subcontext.DataContext as ConfigurationEnvironmentView; if (current == null || current.EnvironmentView != view) { var cev = new ConfigurationEnvironmentView(view); _provider.ResetConfiguration(cev); Subcontext.DataContext = cev; } } } private void Apply_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null && _provider.CanApply(view) && _provider.IsConfigurationChanged(view); e.Handled = true; } private void Apply_Executed(object sender, ExecutedRoutedEventArgs e) { var cev = (ConfigurationEnvironmentView)e.Parameter; var id = _provider.ApplyConfiguration(cev); if (_provider._alwaysCreateNew) { ConfigurationEnvironmentView.Added.Execute(id); } e.Handled = true; } private void Reset_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null && _provider.IsConfigurationChanged(view); e.Handled = true; } private void Reset_Executed(object sender, ExecutedRoutedEventArgs e) { _provider.ResetConfiguration((ConfigurationEnvironmentView)e.Parameter); e.Handled = true; } private void Remove_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = !_provider._alwaysCreateNew && view != null; e.Handled = true; } private void Remove_Executed(object sender, ExecutedRoutedEventArgs e) { _provider.RemoveConfiguration((ConfigurationEnvironmentView)e.Parameter); e.Handled = true; } private void Browse_CanExecute(object sender, CanExecuteRoutedEventArgs e) { Commands.CanExecute(null, sender, e); } private void Browse_Executed(object sender, ExecutedRoutedEventArgs e) { Commands.Executed(null, sender, e); } private void SelectAllText(object sender, RoutedEventArgs e) { var tb = sender as TextBox; if (tb != null) { tb.SelectAll(); } } private void AutoDetect_CanExecute(object sender, CanExecuteRoutedEventArgs e) { var view = e.Parameter as ConfigurationEnvironmentView; e.CanExecute = view != null && !view.IsAutoDetectRunning && ( Directory.Exists(view.PrefixPath) || File.Exists(view.InterpreterPath) || File.Exists(view.WindowsInterpreterPath) ); } private async void AutoDetect_Executed(object sender, ExecutedRoutedEventArgs e) { var view = (ConfigurationEnvironmentView)e.Parameter; try { view.IsAutoDetectRunning = true; CommandManager.InvalidateRequerySuggested(); var newView = await AutoDetectAsync(view.Values); view.Values = newView; CommandManager.InvalidateRequerySuggested(); } finally { view.IsAutoDetectRunning = false; } } private async Task<ConfigurationValues> AutoDetectAsync(ConfigurationValues view) { if (!Directory.Exists(view.PrefixPath)) { if (File.Exists(view.InterpreterPath)) { view.PrefixPath = Path.GetDirectoryName(view.InterpreterPath); } else if (File.Exists(view.WindowsInterpreterPath)) { view.PrefixPath = Path.GetDirectoryName(view.WindowsInterpreterPath); } else { // Don't have enough information, so abort without changing // any settings. return view; } while (Directory.Exists(view.PrefixPath) && !File.Exists(PathUtils.FindFile(view.PrefixPath, "site.py"))) { view.PrefixPath = Path.GetDirectoryName(view.PrefixPath); } } if (!Directory.Exists(view.PrefixPath)) { // If view.PrefixPath is not valid by this point, we can't find anything // else, so abort withou changing any settings. return view; } if (string.IsNullOrEmpty(view.Description)) { view.Description = PathUtils.GetFileOrDirectoryName(view.PrefixPath); } if (!File.Exists(view.InterpreterPath)) { view.InterpreterPath = PathUtils.FindFile( view.PrefixPath, CPythonInterpreterFactoryConstants.ConsoleExecutable, firstCheck: new[] { "scripts" } ); } if (!File.Exists(view.WindowsInterpreterPath)) { view.WindowsInterpreterPath = PathUtils.FindFile( view.PrefixPath, CPythonInterpreterFactoryConstants.WindowsExecutable, firstCheck: new[] { "scripts" } ); } if (File.Exists(view.InterpreterPath)) { using (var output = ProcessOutput.RunHiddenAndCapture( view.InterpreterPath, "-c", "import sys; print('%s.%s' % (sys.version_info[0], sys.version_info[1]))" )) { var exitCode = await output; if (exitCode == 0) { view.VersionName = output.StandardOutputLines.FirstOrDefault() ?? view.VersionName; } } var arch = CPythonInterpreterFactoryProvider.ArchitectureFromExe(view.InterpreterPath); if (arch != InterpreterArchitecture.Unknown) { view.ArchitectureName = arch.ToString(); } } return view; } } sealed class ConfigurationExtensionProvider : IEnvironmentViewExtension { private FrameworkElement _wpfObject; private readonly IInterpreterOptionsService _interpreterOptions; internal readonly bool _alwaysCreateNew; internal ConfigurationExtensionProvider(IInterpreterOptionsService interpreterOptions, bool alwaysCreateNew) { _interpreterOptions = interpreterOptions; _alwaysCreateNew = alwaysCreateNew; } public string ApplyConfiguration(ConfigurationEnvironmentView view) { if (!_alwaysCreateNew) { var factory = view.EnvironmentView.Factory; if (view.Description != factory.Configuration.Description) { // We're renaming the interpreter, remove the old one... _interpreterOptions.RemoveConfigurableInterpreter(factory.Configuration.Id); } } if (!Version.TryParse(view.VersionName, out var version)) { version = null; } return _interpreterOptions.AddConfigurableInterpreter( view.Description, new VisualStudioInterpreterConfiguration( "", view.Description, view.PrefixPath, view.InterpreterPath, view.WindowsInterpreterPath, view.PathEnvironmentVariable, InterpreterArchitecture.TryParse(view.ArchitectureName ?? ""), version ) ); } public bool CanApply(ConfigurationEnvironmentView view) { if (string.IsNullOrEmpty(view.Description) || string.IsNullOrEmpty(view.InterpreterPath)) { return false; } return true; } public bool IsConfigurationChanged(ConfigurationEnvironmentView view) { if (_alwaysCreateNew) { return true; } var factory = view.EnvironmentView.Factory; return view.Description != factory.Configuration.Description || view.PrefixPath != factory.Configuration.GetPrefixPath() || view.InterpreterPath != factory.Configuration.InterpreterPath || view.WindowsInterpreterPath != factory.Configuration.GetWindowsInterpreterPath() || view.PathEnvironmentVariable != factory.Configuration.PathEnvironmentVariable || InterpreterArchitecture.TryParse(view.ArchitectureName) != factory.Configuration.Architecture || view.VersionName != factory.Configuration.Version.ToString(); } public void ResetConfiguration(ConfigurationEnvironmentView view) { var factory = view.EnvironmentView?.Factory; view.Description = factory?.Configuration.Description; view.PrefixPath = factory?.Configuration.GetPrefixPath(); view.InterpreterPath = factory?.Configuration.InterpreterPath; view.WindowsInterpreterPath = factory?.Configuration.GetWindowsInterpreterPath(); view.PathEnvironmentVariable = factory?.Configuration.PathEnvironmentVariable; view.ArchitectureName = factory?.Configuration.Architecture.ToString(); view.VersionName = factory?.Configuration.Version.ToString(); } public void RemoveConfiguration(ConfigurationEnvironmentView view) { if (_alwaysCreateNew) { return; } var factory = view.EnvironmentView.Factory; _interpreterOptions.RemoveConfigurableInterpreter(factory.Configuration.Id); } public int SortPriority { get { return -9; } } public string LocalizedDisplayName { get { return Resources.ConfigurationExtensionDisplayName; } } public FrameworkElement WpfObject { get { if (_wpfObject == null) { _wpfObject = new ConfigurationExtension(this); } return _wpfObject; } } public object HelpContent { get { return Resources.ConfigurationExtensionHelpContent; } } public string HelpText { get { return Resources.ConfigurationExtensionHelpContent; } } } struct ConfigurationValues { public string Description; public string PrefixPath; public string InterpreterPath; public string WindowsInterpreterPath; public string PathEnvironmentVariable; public string VersionName; public string ArchitectureName; } sealed class ConfigurationEnvironmentView : INotifyPropertyChanged { public static readonly ICommand Added = new RoutedCommand(); private static readonly string[] _architectureNames = new[] { InterpreterArchitecture.x86.ToString(), InterpreterArchitecture.x64.ToString() }; private static readonly string[] _versionNames = new[] { "2.5", "2.6", "2.7", "3.0", "3.1", "3.2", "3.3", "3.4", "3.5", "3.6", "3.7", "3.8", }; private readonly EnvironmentView _view; private bool _isAutoDetectRunning; private ConfigurationValues _values; public ConfigurationEnvironmentView(EnvironmentView view) { _view = view; } public EnvironmentView EnvironmentView => _view; public static IList<string> ArchitectureNames => _architectureNames; public static IList<string> VersionNames => _versionNames; public bool IsAutoDetectRunning { get { return _isAutoDetectRunning; } set { if (_isAutoDetectRunning != value) { _isAutoDetectRunning = value; OnPropertyChanged(); } } } public ConfigurationValues Values { get { return _values; } set { Description = value.Description; PrefixPath = value.PrefixPath; InterpreterPath = value.InterpreterPath; WindowsInterpreterPath = value.WindowsInterpreterPath; PathEnvironmentVariable = value.PathEnvironmentVariable; VersionName = value.VersionName; ArchitectureName = value.ArchitectureName; } } public string Description { get { return _values.Description; } set { if (_values.Description != value) { _values.Description = value; OnPropertyChanged(); } } } public string PrefixPath { get { return _values.PrefixPath; } set { if (_values.PrefixPath != value) { _values.PrefixPath = value; OnPropertyChanged(); } } } public string InterpreterPath { get { return _values.InterpreterPath; } set { if (_values.InterpreterPath != value) { _values.InterpreterPath = value; OnPropertyChanged(); } } } public string WindowsInterpreterPath { get { return _values.WindowsInterpreterPath; } set { if (_values.WindowsInterpreterPath != value) { _values.WindowsInterpreterPath = value; OnPropertyChanged(); } } } public string PathEnvironmentVariable { get { return _values.PathEnvironmentVariable; } set { if (_values.PathEnvironmentVariable != value) { _values.PathEnvironmentVariable = value; OnPropertyChanged(); } } } public string ArchitectureName { get { return _values.ArchitectureName; } set { if (_values.ArchitectureName != value) { _values.ArchitectureName = value; OnPropertyChanged(); } } } public string VersionName { get { return _values.VersionName; } set { if (_values.VersionName != value) { _values.VersionName = value; OnPropertyChanged(); } } } public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
using System.Collections.Generic; using System.Linq; using UnityEditor.Graphing; using UnityEditor.ShaderGraph; using UnityEngine.Experimental.Rendering.HDPipeline; using UnityEngine.Rendering; namespace UnityEditor.Experimental.Rendering.HDPipeline { [FormerName("UnityEditor.ShaderGraph.HDPBRSubShader")] class HDPBRSubShader : IPBRSubShader { Pass m_PassGBuffer = new Pass() { Name = "GBuffer", LightMode = "GBuffer", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ShaderPassName = "SHADERPASS_GBUFFER", ExtraDefines = new List<string>() { "#pragma multi_compile _ DEBUG_DISPLAY", "#pragma multi_compile _ LIGHTMAP_ON", "#pragma multi_compile _ DIRLIGHTMAP_COMBINED", "#pragma multi_compile _ DYNAMICLIGHTMAP_ON", "#pragma multi_compile _ SHADOWS_SHADOWMASK", "#pragma multi_compile DECALS_OFF DECALS_3RT DECALS_4RT", "#pragma multi_compile _ LIGHT_LAYERS", }, Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassGBuffer.hlsl\"", }, RequiredFields = new List<string>() { "FragInputs.worldToTangent", "FragInputs.positionRWS", "FragInputs.texCoord1", "FragInputs.texCoord2" }, PixelShaderSlots = new List<int>() { PBRMasterNode.AlbedoSlotId, PBRMasterNode.NormalSlotId, PBRMasterNode.MetallicSlotId, PBRMasterNode.SpecularSlotId, PBRMasterNode.EmissionSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.OcclusionSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId }, UseInPreview = true, OnGeneratePassImpl = (IMasterNode node, ref Pass pass) => { var masterNode = node as PBRMasterNode; HDSubShaderUtilities.GetStencilStateForGBuffer(true, false, ref pass); // When we have alpha test, we will force a depth prepass so we always bypass the clip instruction in the GBuffer // Don't do it with debug display mode as it is possible there is no depth prepass in this case // This remove is required otherwise the code generate several time the define... pass.ExtraDefines.Remove("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST\n#endif"); if (masterNode.surfaceType == SurfaceType.Opaque && (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId) || masterNode.GetInputSlots<Vector1MaterialSlot>().First(x => x.id == PBRMasterNode.AlphaThresholdSlotId).value > 0.0f)) { pass.ExtraDefines.Add("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST\n#endif"); pass.ZTestOverride = "ZTest Equal"; } else { pass.ZTestOverride = null; } } }; Pass m_PassMETA = new Pass() { Name = "META", LightMode = "META", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ShaderPassName = "SHADERPASS_LIGHT_TRANSPORT", CullOverride = "Cull Off", Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassLightTransport.hlsl\"", }, RequiredFields = new List<string>() { "AttributesMesh.normalOS", "AttributesMesh.tangentOS", // Always present as we require it also in case of anisotropic lighting "AttributesMesh.uv0", "AttributesMesh.uv1", "AttributesMesh.color", "AttributesMesh.uv2", // SHADERPASS_LIGHT_TRANSPORT always uses uv2 }, PixelShaderSlots = new List<int>() { PBRMasterNode.AlbedoSlotId, PBRMasterNode.NormalSlotId, PBRMasterNode.MetallicSlotId, PBRMasterNode.SpecularSlotId, PBRMasterNode.EmissionSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.OcclusionSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { //PBRMasterNode.PositionSlotId }, UseInPreview = false }; Pass m_PassShadowCaster = new Pass() { Name = "ShadowCaster", LightMode = "ShadowCaster", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ShaderPassName = "SHADERPASS_SHADOWS", BlendOverride = "Blend One Zero", ZWriteOverride = "ZWrite On", ColorMaskOverride = "ColorMask 0", Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"", }, PixelShaderSlots = new List<int>() { PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId }, UseInPreview = false }; Pass m_SceneSelectionPass = new Pass() { Name = "SceneSelectionPass", LightMode = "SceneSelectionPass", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ShaderPassName = "SHADERPASS_DEPTH_ONLY", ColorMaskOverride = "ColorMask 0", ExtraDefines = new List<string>() { "#define SCENESELECTIONPASS", }, Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"", }, PixelShaderSlots = new List<int>() { PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId }, UseInPreview = false }; Pass m_PassDepthOnly = new Pass() { Name = "DepthOnly", LightMode = "DepthOnly", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ZWriteOverride = "ZWrite On", ExtraDefines = HDSubShaderUtilities.s_ExtraDefinesDepthOrMotion, ShaderPassName = "SHADERPASS_DEPTH_ONLY", Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassDepthOnly.hlsl\"", }, PixelShaderSlots = new List<int>() { PBRMasterNode.NormalSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, RequiredFields = new List<string>() { "AttributesMesh.normalOS", "AttributesMesh.tangentOS", // Always present as we require it also in case of Variants lighting "AttributesMesh.uv0", "AttributesMesh.uv1", "AttributesMesh.color", "AttributesMesh.uv2", // SHADERPASS_LIGHT_TRANSPORT always uses uv2 "AttributesMesh.uv3", // DEBUG_DISPLAY "FragInputs.worldToTangent", "FragInputs.positionRWS", "FragInputs.texCoord0", "FragInputs.texCoord1", "FragInputs.texCoord2", "FragInputs.texCoord3", "FragInputs.color", }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId }, UseInPreview = true, OnGeneratePassImpl = (IMasterNode node, ref Pass pass) => { var masterNode = node as PBRMasterNode; HDSubShaderUtilities.GetStencilStateForDepthOrMV(false, true, false, ref pass); } }; Pass m_PassMotionVectors = new Pass() { Name = "MotionVectors", LightMode = "MotionVectors", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ShaderPassName = "SHADERPASS_MOTION_VECTORS", ExtraDefines = HDSubShaderUtilities.s_ExtraDefinesDepthOrMotion, Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassMotionVectors.hlsl\"", }, RequiredFields = new List<string>() { "FragInputs.positionRWS", }, PixelShaderSlots = new List<int>() { PBRMasterNode.NormalSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId }, UseInPreview = false, OnGeneratePassImpl = (IMasterNode node, ref Pass pass) => { var masterNode = node as PBRMasterNode; HDSubShaderUtilities.GetStencilStateForDepthOrMV(false, true, true, ref pass); } }; Pass m_PassForward = new Pass() { Name = "Forward", LightMode = "Forward", TemplateName = "HDPBRPass.template", MaterialName = "PBR", ShaderPassName = "SHADERPASS_FORWARD", // ExtraDefines are set when the pass is generated Includes = new List<string>() { "#include \"Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPassForward.hlsl\"", }, RequiredFields = new List<string>() { "FragInputs.worldToTangent", "FragInputs.positionRWS", // NOTE : world-space pos is necessary for any lighting pass "FragInputs.texCoord1", "FragInputs.texCoord2" }, PixelShaderSlots = new List<int>() { PBRMasterNode.AlbedoSlotId, PBRMasterNode.NormalSlotId, PBRMasterNode.MetallicSlotId, PBRMasterNode.SpecularSlotId, PBRMasterNode.EmissionSlotId, PBRMasterNode.SmoothnessSlotId, PBRMasterNode.OcclusionSlotId, PBRMasterNode.AlphaSlotId, PBRMasterNode.AlphaThresholdSlotId }, VertexShaderSlots = new List<int>() { PBRMasterNode.PositionSlotId }, OnGeneratePassImpl = (IMasterNode node, ref Pass pass) => { var masterNode = node as PBRMasterNode; HDSubShaderUtilities.GetStencilStateForForward(false, ref pass); pass.ExtraDefines.Remove("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST\n#endif"); if (masterNode.surfaceType == SurfaceType.Opaque && (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId) || masterNode.GetInputSlots<Vector1MaterialSlot>().First(x => x.id == PBRMasterNode.AlphaThresholdSlotId).value > 0.0f)) { // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI) // Don't do it with debug display mode as it is possible there is no depth prepass in this case pass.ExtraDefines.Add("#ifndef DEBUG_DISPLAY\n#define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST\n#endif"); pass.ZTestOverride = "ZTest Equal"; } else { pass.ZTestOverride = null; } }, UseInPreview = true }; public int GetPreviewPassIndex() { return 0; } private static HashSet<string> GetActiveFieldsFromMasterNode(AbstractMaterialNode iMasterNode, Pass pass) { HashSet<string> activeFields = new HashSet<string>(); PBRMasterNode masterNode = iMasterNode as PBRMasterNode; if (masterNode == null) { return activeFields; } if (masterNode.twoSided.isOn) { activeFields.Add("DoubleSided"); if (pass.ShaderPassName != "SHADERPASS_MOTION_VECTORS") // HACK to get around lack of a good interpolator dependency system { // we need to be able to build interpolators using multiple input structs // also: should only require isFrontFace if Normals are required... activeFields.Add("DoubleSided.Mirror"); // TODO: change this depending on what kind of normal flip you want.. activeFields.Add("FragInputs.isFrontFace"); // will need this for determining normal flip mode } } switch (masterNode.model) { case PBRMasterNode.Model.Metallic: break; case PBRMasterNode.Model.Specular: activeFields.Add("Material.SpecularColor"); break; default: // TODO: error! break; } if (masterNode.IsSlotConnected(PBRMasterNode.AlphaThresholdSlotId) || masterNode.GetInputSlots<Vector1MaterialSlot>().First(x => x.id == PBRMasterNode.AlphaThresholdSlotId).value > 0.0f) { activeFields.Add("AlphaTest"); } if (masterNode.surfaceType != SurfaceType.Opaque) { activeFields.Add("SurfaceType.Transparent"); if (masterNode.alphaMode == AlphaMode.Alpha) { activeFields.Add("BlendMode.Alpha"); } else if (masterNode.alphaMode == AlphaMode.Additive) { activeFields.Add("BlendMode.Add"); } // By default PBR node will take the fog activeFields.Add("AlphaFog"); } else { // opaque-only defines } return activeFields; } private static bool GenerateShaderPassLit(AbstractMaterialNode masterNode, Pass pass, GenerationMode mode, SurfaceMaterialOptions materialOptions, ShaderGenerator result, List<string> sourceAssetDependencyPaths) { if (mode == GenerationMode.ForReals || pass.UseInPreview) { pass.OnGeneratePass(masterNode as PBRMasterNode); // apply master node options to active fields HashSet<string> activeFields = GetActiveFieldsFromMasterNode(masterNode, pass); // use standard shader pass generation bool vertexActive = masterNode.IsSlotConnected(PBRMasterNode.PositionSlotId); return HDSubShaderUtilities.GenerateShaderPass(masterNode, pass, mode, materialOptions, activeFields, result, sourceAssetDependencyPaths, vertexActive); } else { return false; } } public string GetSubshader(IMasterNode iMasterNode, GenerationMode mode, List<string> sourceAssetDependencyPaths = null) { if (sourceAssetDependencyPaths != null) { // HDPBRSubShader.cs sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("8a6369cac4d1faf45b8715adbd364f13")); // HDSubShaderUtilities.cs sourceAssetDependencyPaths.Add(AssetDatabase.GUIDToAssetPath("713ced4e6eef4a44799a4dd59041484b")); } var masterNode = iMasterNode as PBRMasterNode; var subShader = new ShaderGenerator(); subShader.AddShaderChunk("SubShader", true); subShader.AddShaderChunk("{", true); subShader.Indent(); { HDMaterialTags materialTags = HDSubShaderUtilities.BuildMaterialTags(masterNode.surfaceType, 0, false); // Add tags at the SubShader level { var tagsVisitor = new ShaderStringBuilder(); materialTags.GetTags(tagsVisitor, HDRenderPipeline.k_ShaderTagName); subShader.AddShaderChunk(tagsVisitor.ToString(), false); } SurfaceMaterialOptions materialOptions = HDSubShaderUtilities.BuildMaterialOptions(masterNode.surfaceType, masterNode.alphaMode, masterNode.twoSided.isOn, false, false); // generate the necessary shader passes bool opaque = (masterNode.surfaceType == SurfaceType.Opaque); GenerateShaderPassLit(masterNode, m_PassMETA, mode, materialOptions, subShader, sourceAssetDependencyPaths); GenerateShaderPassLit(masterNode, m_PassShadowCaster, mode, materialOptions, subShader, sourceAssetDependencyPaths); GenerateShaderPassLit(masterNode, m_SceneSelectionPass, mode, materialOptions, subShader, sourceAssetDependencyPaths); if (opaque) { GenerateShaderPassLit(masterNode, m_PassDepthOnly, mode, materialOptions, subShader, sourceAssetDependencyPaths); GenerateShaderPassLit(masterNode, m_PassGBuffer, mode, materialOptions, subShader, sourceAssetDependencyPaths); GenerateShaderPassLit(masterNode, m_PassMotionVectors, mode, materialOptions, subShader, sourceAssetDependencyPaths); } // Assign define here based on opaque or transparent to save some variant m_PassForward.ExtraDefines = opaque ? HDSubShaderUtilities.s_ExtraDefinesForwardOpaque : HDSubShaderUtilities.s_ExtraDefinesForwardTransparent; GenerateShaderPassLit(masterNode, m_PassForward, mode, materialOptions, subShader, sourceAssetDependencyPaths); } subShader.Deindent(); subShader.AddShaderChunk("}", true); subShader.AddShaderChunk(@"CustomEditor ""UnityEditor.Experimental.Rendering.HDPipeline.HDLitGUI"""); return subShader.GetShaderString(0); } public bool IsPipelineCompatible(RenderPipelineAsset renderPipelineAsset) { return renderPipelineAsset is HDRenderPipelineAsset; } } }
using System.Collections.Generic; namespace Pathfinding { /** Stores temporary node data for a single pathfinding request. * Every node has one PathNode per thread used. * It stores e.g G score, H score and other temporary variables needed * for path calculation, but which are not part of the graph structure. * * \see Pathfinding.PathHandler */ public class PathNode { /** Reference to the actual graph node */ public GraphNode node; /** Parent node in the search tree */ public PathNode parent; /** The path request (in this thread, if multithreading is used) which last used this node */ public ushort pathID; /** Bitpacked variable which stores several fields */ private uint flags; /** Cost uses the first 28 bits */ private const uint CostMask = (1U << 28) - 1U; /** Flag 1 is at bit 28 */ private const int Flag1Offset = 28; private const uint Flag1Mask = (uint)(1 << Flag1Offset); /** Flag 2 is at bit 29 */ private const int Flag2Offset = 29; private const uint Flag2Mask = (uint)(1 << Flag2Offset); public uint cost { get { return flags & CostMask; } set { flags = (flags & ~CostMask) | value; } } /** Use as temporary flag during pathfinding. * Pathfinders (only) can use this during pathfinding to mark * nodes. When done, this flag should be reverted to its default state (false) to * avoid messing up other pathfinding requests. */ public bool flag1 { get { return (flags & Flag1Mask) != 0; } set { flags = (flags & ~Flag1Mask) | (value ? Flag1Mask : 0U); } } /** Use as temporary flag during pathfinding. * Pathfinders (only) can use this during pathfinding to mark * nodes. When done, this flag should be reverted to its default state (false) to * avoid messing up other pathfinding requests. */ public bool flag2 { get { return (flags & Flag2Mask) != 0; } set { flags = (flags & ~Flag2Mask) | (value ? Flag2Mask : 0U); } } /** Backing field for the G score */ private uint g; /** Backing field for the H score */ private uint h; /** G score, cost to get to this node */ public uint G {get { return g;} set{g = value;}} /** H score, estimated cost to get to to the target */ public uint H {get { return h;} set{h = value;}} /** F score. H score + G score */ public uint F {get { return g+h;}} } /** Handles thread specific path data. */ public class PathHandler { /** Current PathID. * \see #PathID */ private ushort pathID; /** Binary heap to keep nodes on the "Open list" */ private BinaryHeapM heap = new BinaryHeapM(128); /** ID for the path currently being calculated or last path that was calculated */ public ushort PathID {get { return pathID; }} /** Push a node to the heap */ public void PushNode (PathNode node) { heap.Add (node); } /** Pop the node with the lowest F score off the heap */ public PathNode PopNode () { return heap.Remove (); } /** Get the internal heap. * \note Most things can be accomplished with the methods on this class instead. */ public BinaryHeapM GetHeap () { return heap; } /** Rebuild the heap to account for changed node values. * Some path types change the target for the H score in the middle of the path calculation, * that requires rebuilding the heap to keep it correctly sorted */ public void RebuildHeap () { heap.Rebuild (); } /** True if the heap is empty */ public bool HeapEmpty () { return heap.numberOfItems <= 1; } /** Log2 size of buckets. * So 10 yields a real bucket size of 1024. * Be careful with large values. */ const int BucketSizeLog2 = 10; /** Real bucket size */ const int BucketSize = 1 << BucketSizeLog2; const int BucketIndexMask = (1 << BucketSizeLog2)-1; /** Array of buckets containing PathNodes */ public PathNode[][] nodes = new PathNode[0][]; private bool[] bucketNew = new bool[0]; private bool[] bucketCreated = new bool[0]; private Stack<PathNode[]> bucketCache = new Stack<PathNode[]> (); private int filledBuckets = 0; /** StringBuilder that paths can use to build debug strings. * Better to use a single StringBuilder instead of each path creating its own */ public readonly System.Text.StringBuilder DebugStringBuilder = new System.Text.StringBuilder(); public PathHandler () { } public void InitializeForPath (Path p) { pathID = p.pathID; heap.Clear (); } /** Internal method to clean up node data */ public void DestroyNode (GraphNode node) { PathNode pn = GetPathNode (node); //Clean up reference to help GC pn.node = null; } /** Internal method to initialize node data */ public void InitializeNode (GraphNode node) { //Get the index of the node int ind = node.NodeIndex; int bucketNumber = ind >> BucketSizeLog2; int bucketIndex = ind & BucketIndexMask; if (bucketNumber >= nodes.Length) { //At least increase the size to: //Current size * 1.5 //Current size + 2 or //bucketNumber PathNode[][] newNodes = new PathNode[System.Math.Max (System.Math.Max (nodes.Length*3 / 2,bucketNumber+1), nodes.Length+2)][]; for (int i=0;i<nodes.Length;i++) newNodes[i] = nodes[i]; //Debug.Log ("Resizing Bucket List from " + nodes.Length + " to " + newNodes.Length + " (bucketNumber="+bucketNumber+")"); bool[] newBucketNew = new bool[newNodes.Length]; for (int i=0;i<nodes.Length;i++) newBucketNew[i] = bucketNew[i]; bool[] newBucketCreated = new bool[newNodes.Length]; for (int i=0;i<nodes.Length;i++) newBucketCreated[i] = bucketCreated[i]; nodes = newNodes; bucketNew = newBucketNew; bucketCreated = newBucketCreated; } if (nodes[bucketNumber] == null) { PathNode[] ns; if (bucketCache.Count > 0) { ns = bucketCache.Pop(); } else { ns = new PathNode[BucketSize]; for (int i=0;i<BucketSize;i++) ns[i] = new PathNode (); } nodes[bucketNumber] = ns; if (!bucketCreated[bucketNumber]) { bucketNew[bucketNumber] = true; bucketCreated[bucketNumber] = true; } filledBuckets++; } PathNode pn = nodes[bucketNumber][bucketIndex]; pn.node = node; } public PathNode GetPathNode (GraphNode node) { //Get the index of the node int ind = node.NodeIndex; return nodes[ind >> BucketSizeLog2][ind & BucketIndexMask]; } /** Set all node's pathIDs to 0. * \see Pathfinding.PathNode.pathID */ public void ClearPathIDs () { for (int i=0;i<nodes.Length;i++) { PathNode[] ns = nodes[i]; if (nodes[i] != null) for (int j=0;j<BucketSize;j++) ns[j].pathID = 0; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using AspNetCoreTest.Models; using AspNetCoreTest.Models.AccountViewModels; using AspNetCoreTest.Services; namespace AspNetCoreTest.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> 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(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { 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 https://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 RedirectToLocal(returnUrl); } 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 Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } 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.Principal.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 (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 ApplicationUser { 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 https://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(string.Empty, "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 Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Linq; using UnityEngine; namespace Captury { /// <summary> /// Instantiates Captury Avatars and handles the user assignment /// </summary> [RequireComponent(typeof(CapturyNetworkPlugin), typeof(CapturyLeapIntegration))] public class CapturyAvatarManager : MonoBehaviour { [DllImport("Retargetery")] private static extern int liveGenerateMapping(System.IntPtr src, System.IntPtr tgt); [SerializeField] [Tooltip("Avatar prefabs for local players (without head). userAvatarID is set in the Captury config file (see CapturyConfigManager for more infos)")] private GameObject[] localAvatarPrefabs = new GameObject[] { }; [SerializeField] [Tooltip("Avatar prefabs for remote players (with head). userAvatarID is set in he Captury config file (see CapturyConfigManager for more infos)")] private GameObject[] remoteAvatarPrefabs = new GameObject[] { }; [SerializeField] [Tooltip("The default avatar prefab which will be instantiated if no user is assigned to a skeleton.")] private GameObject defaultAvatar; [SerializeField] [Tooltip("The TransformFollower which will be manipulated by the captury tracking (should be on a parent GameObject of the camera).")] private TransformFollower transformFollower; /// <summary> /// The <see cref="CapturyNetworkPlugin"/> which handles the connection to the captuy server /// </summary> private CapturyNetworkPlugin networkPlugin; /// <summary> /// The <see cref="CapturyLeapIntegration"/> which reads the leap input data /// </summary> private CapturyLeapIntegration capturyLeapIntegration; /// <summary> /// List of <see cref="CapturySkeleton"/> which will be instantiated in the next Update /// </summary> private List<CapturySkeleton> newSkeletons = new List<CapturySkeleton>(); /// <summary> /// List of <see cref="CapturySkeleton"/> which will be destroyed in the next Update /// </summary> private List<CapturySkeleton> lostSkeletons = new List<CapturySkeleton>(); /// <summary> /// List of <see cref="CapturySkeleton"/> which are currently tracked /// </summary> private List<CapturySkeleton> trackedSkeletons = new List<CapturySkeleton>(); /// <summary> /// The <see cref="CapturySkeleton"/> which is assigned to the local player. /// null if local player is not assigned to a skeleton yet. /// </summary> private CapturySkeleton playerSkeleton; /// <summary> /// The captury config will be loaded from <see cref="CapturyConfigManager.configFileName"/> /// </summary> private CapturyConfig capturyConfig; /// <summary> /// Avatar transform names, to find the right transforms of an instantiated avatar. /// </summary> private const string AVATAR_LEFT_HAND_TRANSFORM_NAME = "LeftFingerBase"; private const string AVATAR_RIGHT_HAND_TRANSFORM_NAME = "RightFingerBase"; private const string AVATAR_HEAD_TRANSFORM_NAME = "Head"; /// <summary> /// Player Assignment Changed is fired when the assignement of the local player with a skeleton changed /// skeleton is null if the assignment was cleared /// </summary> /// <param name="skeleton"></param> public delegate void PlayerAssignmentChangedDelegate(int skeletonID, bool isAssigned); public event PlayerAssignmentChangedDelegate PlayerAssignmentChanged; [SerializeField] [Tooltip("If set to true, AR Tags will be displayed as GameObjects")] private bool debugARTags = false; /// <summary> /// Used to determine if we didn't have ARTag updates between two frames and need to destroy the AR Tag GameObjects /// </summary> private bool arTagsUpdated = false; /// <summary> /// Debug GameObjects for ARTags /// </summary> private Dictionary<int, GameObject> arTagGameObjects = new Dictionary<int, GameObject>(); private void Start() { // get config capturyConfig = CapturyConfigManager.Config; networkPlugin = GetComponent<CapturyNetworkPlugin>(); capturyLeapIntegration = GetComponent<CapturyLeapIntegration>(); if (transformFollower == null) { transformFollower = FindObjectOfType<TransformFollower>(); if(transformFollower == null) { Debug.LogError("No TransformFollower found in Scene. Camera manipulation by Captury tracking won't work."); } } // check the avatar prefabs if(defaultAvatar == null) { Debug.LogError("defaultAvatar not set. Make sure you assign a Avatar prefab to CapturyAvatarManager.defaultAvatar"); }/* else ConvertGameObjectToCapturyActor(defaultAvatar);*/ if (localAvatarPrefabs.Length != remoteAvatarPrefabs.Length) { Debug.LogError("localAvatarPrefabs.Length != remoteAvatarPrefabs.Length. For every localAvatarPrefab (without head) there has to be a remoteAvatarPrefab (with head) which will be spawned on remote experiences"); } // keep the CapturyAvatarManager GameObject between scenes DontDestroyOnLoad(gameObject); // register for skeleton events networkPlugin.SkeletonFound += OnSkeletonFound; networkPlugin.SkeletonLost += OnSkeletonLost; // register for AR Tag (marker) events networkPlugin.ARTagsDetected += OnARTagsDetected; } private void OnDestroy() { // unregister from events if (networkPlugin != null) { networkPlugin.SkeletonFound -= OnSkeletonFound; networkPlugin.SkeletonLost -= OnSkeletonLost; networkPlugin.ARTagsDetected -= OnARTagsDetected; } } private void Update() { lock (newSkeletons) { InstantiateDefaultAvatars(newSkeletons); } lock (lostSkeletons) { DestroyAvatars(lostSkeletons); } if (debugARTags) { if (arTagsUpdated == false) { lock (arTagGameObjects) { foreach (var tag in arTagGameObjects) { DestroyImmediate(tag.Value); } arTagGameObjects.Clear(); } } arTagsUpdated = false; } } /// <summary> /// Can be called from a multiplayer manager to set the skeletons playerID /// </summary> /// <param name="skeletonID">Captury Skeleton id</param> /// <param name="playerID">Networking Player id</param> public void SetSkeletonPlayerID(int skeletonID, int playerID) { CapturySkeleton skel = trackedSkeletons.First(s => s.id == skeletonID); if (skel != null) { skel.playerID = playerID; } } /// <summary> /// Called when a new captury skeleton is found /// </summary> /// <param name="skeleton"></param> private void OnSkeletonFound(CapturySkeleton skeleton) { Debug.Log("CapturyAvatarManager found skeleton with id " + skeleton.id + " and name " + skeleton.name); lock (newSkeletons) { newSkeletons.Add(skeleton); } } /// <summary> /// Called when a captury skeleton is lost /// </summary> /// <param name="skeleton"></param> private void OnSkeletonLost(CapturySkeleton skeleton) { Debug.Log("CapturyAvatarManager lost skeleton with id " + skeleton.id + " and name " + skeleton.name); lock (lostSkeletons) { lostSkeletons.Add(skeleton); } // clear the assignment between local player and the skelton if it's lost if (IsLocalPlayer(skeleton)) { ClearPlayerAssignment(); } } /// <summary> /// Called when a Captury AR tags (markers) are detected /// </summary> /// <param name="tags"></param> private void OnARTagsDetected(ARTag[] tags) { // check player/skeleton assignment with AR tags if (playerSkeleton == null) { // get the AR tags which are assigned to the player List<ARTag> playerARTags = tags.Where(t => capturyConfig.arTagIDs.Contains(t.id)).ToList(); foreach (var tag in playerARTags) { CapturySkeleton skel = GetAttachedSkeleton(tag); if (skel != null) { if (skel.playerID == -1) { AssignPlayerToSkeleton(skel); } else { Debug.Log("Skeleton " + skel.id + " is already assigned to player " + skel.playerID); } } } } if (debugARTags) { ShowARTags(tags); arTagsUpdated = true; } } /// <summary> /// Shows AR Tags as flat cubes /// </summary> /// <param name="tags"></param> private void ShowARTags(ARTag[] tags) { lock (arTagGameObjects) { List<int> tagsToRemove = new List<int>(); foreach (var tag in arTagGameObjects) { bool isStillActive = tags.Any(item => item.id == tag.Key); if (isStillActive == false) { DestroyImmediate(tag.Value); tagsToRemove.Add(tag.Key); } } foreach (var id in tagsToRemove) { arTagGameObjects.Remove(id); } foreach (var tag in tags) { if (arTagGameObjects.ContainsKey(tag.id) == false) { // can be optimized with object pool GameObject gO = GameObject.CreatePrimitive(PrimitiveType.Cube); gO.name = "arTag " + tag.id; gO.transform.localScale = new Vector3(0.1f, 0.1f, 0.01f); arTagGameObjects.Add(tag.id, gO); } // update pose arTagGameObjects[tag.id].transform.position = tag.translation; arTagGameObjects[tag.id].transform.rotation = tag.rotation; } } } /// <summary> /// Returns the avatar prefab with the given avatarID from <see cref="localAvatarPrefabs"/> or <see cref="remoteAvatarPrefabs"/> depending on isLocal. /// If avatarID is invalid, <see cref="defaultAvatar"/> will be returned /// </summary> /// <param name="avatarID"></param> /// <param name="isLocal"></param> /// <returns>Avatar prefab</returns> private GameObject GetAvatarPrefab(int avatarID, bool isLocal) { GameObject[] avatars; if (isLocal) { avatars = localAvatarPrefabs; } else { avatars = remoteAvatarPrefabs; } if (avatarID < 0 || avatarID > avatars.Length) { Debug.LogError("Trying to get avatar for invalid id " + avatarID + ". returning defaultAvatar!"); return defaultAvatar; } return avatars[avatarID]; } /// <summary> /// Instantiates and sets the given avatarPrefab for the CapturySkeleton /// </summary> /// <param name="skel"></param> /// <param name="avatarPrefab"></param> private void SetAvatar(CapturySkeleton skel, GameObject avatarPrefab) { GameObject avatar = Instantiate(avatarPrefab); DontDestroyOnLoad(avatar); avatar.SetActive(true); if(skel.mesh != null) { // destroy old avatar DestroyImmediate(skel.mesh); } skel.mesh = avatar; skel.retargetTarget = ConvertGameObjectToCapturyActor(avatar); skel.originalMesh = avatarPrefab; /* CapturyActor actor = new CapturyActor(); actor = (CapturyActor)Marshal.PtrToStructure(x, typeof(CapturyActor)); // no? we need to convert it CapturySkeleton skeleton = new CapturySkeleton(); networkPlugin.ConvertActor(actor, x, ref skeleton); CapturyActor srcActor = new CapturyActor(); srcActor = (CapturyActor)Marshal.PtrToStructure(skel.rawData, typeof(CapturyActor)); CapturySkeleton srcSkel = new CapturySkeleton(); networkPlugin.ConvertActor(srcActor, skel.rawData, ref srcSkel); */ liveGenerateMapping(skel.rawData, skel.retargetTarget); } /// <summary> /// Instantiates default avatars for the given list of skeletons /// </summary> /// <param name="skeletons"></param> private void InstantiateDefaultAvatars(List<CapturySkeleton> skeletons) { lock (trackedSkeletons) { foreach (CapturySkeleton skel in skeletons) { Debug.Log("Instantiating avatar for skeleton with id " + skel.id + " and name " + skel.name); SetAvatar(skel, defaultAvatar); trackedSkeletons.Add(skel); } skeletons.Clear(); } } /// <summary> /// Destorys avatars for the given list of skeletons /// </summary> private void DestroyAvatars(List<CapturySkeleton> skeltons) { lock (trackedSkeletons) { foreach (CapturySkeleton skel in skeltons) { Debug.Log("Destroying avatar for skeleton with id " + skel.id + " and name " + skel.name); DestroyImmediate(skel.mesh); skel.mesh = null; trackedSkeletons.Remove(skel); } skeltons.Clear(); } } /// <summary> /// Checks if the <see cref="ARTag"/> is attached to the <see cref="CapturySkeleton"/> by comparing their positions /// </summary> /// <param name="tag"></param> /// <param name="skel"></param> /// <returns></returns> private bool IsAttachedToSkeleton(ARTag tag, CapturySkeleton skel) { float threshold = 0.5f; foreach(var joint in skel.joints) { if(joint != null && joint.transform != null) { // TODO check if local / global position if (Vector3.Distance(tag.translation, joint.transform.position) < threshold) { return true; } } } return false; } /// <summary> /// Checks if the given <see cref="ARTag"/> is attached to a <see cref="CapturySkeleton"/> in <see cref="trackedSkeletons"/> /// </summary> /// <param name="tag"></param> /// <returns>The skeleton which tag is attached to. null if there's none.</returns> private CapturySkeleton GetAttachedSkeleton(ARTag tag) { foreach(var skel in trackedSkeletons) { if (IsAttachedToSkeleton(tag, skel)) { return skel; } } return null; } /// <summary> /// Assigns the local player to the given <see cref="CapturySkeleton"/>. /// </summary> /// <param name="skeleton"></param> private void AssignPlayerToSkeleton(CapturySkeleton skeleton) { // instantiate the local player avatar GameObject avatarPrefab = GetAvatarPrefab(capturyConfig.avatarID, true); SetAvatar(skeleton, avatarPrefab); playerSkeleton = skeleton; Transform left = null; Transform right = null; Transform head = null; GameObject avatar = skeleton.mesh.gameObject; Component[] trafos = avatar.transform.GetComponentsInChildren<Transform>(); foreach (Transform child in trafos) { if (child.name.EndsWith(AVATAR_LEFT_HAND_TRANSFORM_NAME)) { left = child; } if (child.name.EndsWith(AVATAR_RIGHT_HAND_TRANSFORM_NAME)) { right = child; } if (child.name.EndsWith(AVATAR_HEAD_TRANSFORM_NAME)) { head = child; } } if (left != null && right != null) { capturyLeapIntegration.setTargetModel(left, right, skeleton.id); } else { Debug.Log("Cannot find hands on target avatar with name '" + AVATAR_LEFT_HAND_TRANSFORM_NAME + "' and '" + AVATAR_RIGHT_HAND_TRANSFORM_NAME + "'"); } if (head != null) { transformFollower.Target = head; } else { Debug.Log("Cannot find head on target avatar with name " + AVATAR_HEAD_TRANSFORM_NAME); } if (PlayerAssignmentChanged != null) { PlayerAssignmentChanged(playerSkeleton.id, true); } Debug.Log("Assigned local player to skeleton with name " + skeleton.name + " and id " + skeleton.id); } /// <summary> /// Clears the assignment of the local player with an skeleton /// </summary> private void ClearPlayerAssignment() { if(playerSkeleton == null) { Debug.LogError("Trying to clear player assignment, but playerSkeleton == null"); return; } if (PlayerAssignmentChanged != null) { PlayerAssignmentChanged(playerSkeleton.id, false); } playerSkeleton.playerID = -1; capturyLeapIntegration.setTargetModel(null, null, -1); transformFollower.Target = null; playerSkeleton = null; } /// <summary> /// Return true if the given skeleton is the local player skeleton /// </summary> /// <param name="skeleton"></param> /// <returns></returns> private bool IsLocalPlayer(CapturySkeleton skeleton) { return skeleton.Equals(playerSkeleton); } private System.IntPtr ConvertGameObjectToCapturyActor(GameObject g) { CapturyActor actor = new CapturyActor(); Transform[] trafos = g.GetComponentsInChildren<Transform>(); //Debug.Log("have " + (trafos.Length - 1) + " children"); actor.name = System.Text.Encoding.ASCII.GetBytes(g.name); actor.id = 17; actor.numJoints = trafos.Length - 1; System.IntPtr mem = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(CapturyActor)) + actor.numJoints * Marshal.SizeOf(typeof(CapturyJoint))); actor.joints = new System.IntPtr(mem.ToInt64() + Marshal.SizeOf(typeof(CapturyActor))); actor.numBlobs = 0; actor.blobs = System.IntPtr.Zero; Marshal.StructureToPtr(actor, mem, false); CapturyJoint[] joints = new CapturyJoint[trafos.Length - 1]; Vector3[] globalPositions = new Vector3[trafos.Length - 1]; Vector3[] globalPositionsUnity = new Vector3[trafos.Length - 1]; Vector3[] trafoPos = new Vector3[trafos.Length]; Dictionary<string, int> names = new Dictionary<string, int>(); names[trafos[0].name] = -1; // this is the overall parent System.IntPtr j = actor.joints; for (int i = 0; i < actor.numJoints; ++i) { names[trafos[i + 1].name] = i; joints[i].parent = names[trafos[i + 1].parent.name]; joints[i].name = System.Text.Encoding.ASCII.GetBytes(trafos[i + 1].name); Vector3 pos; int parent = joints[i].parent; if (parent != -1) pos = networkPlugin.ConvertPositionToLive(trafos[i + 1].position - trafos[i+1].parent.position); else pos = networkPlugin.ConvertPositionToLive(trafos[i + 1].position); joints[i].ox = pos.x; joints[i].oy = pos.y; joints[i].oz = pos.z; Quaternion delta = trafos[i + 1].rotation; Quaternion liveDelta = networkPlugin.ConvertRotationToLive(delta); Vector3 rot = networkPlugin.ConvertToEulerAngles(liveDelta); joints[i].rx = 0.0f;// rot.x; joints[i].ry = 0.0f;// rot.y; joints[i].rz = 0.0f;// rot.z; trafoPos[i] = trafos[i + 1].position; globalPositions[i] = new Vector3(joints[i].ox, joints[i].oy, joints[i].oz); int p = joints[i].parent; if (p > -1) globalPositions[i] += globalPositions[p]; globalPositionsUnity[i] = networkPlugin.ConvertPosition(globalPositions[i]) - trafoPos[i]; Marshal.StructureToPtr(joints[i], j, false); j = new System.IntPtr(j.ToInt64() + Marshal.SizeOf(typeof(CapturyJoint))); } return mem; } } }
using Generator.Core.Application.Customers.Requests; using Generator.Infrastructure.EntityFrameworkCore.Customers.Records; using Generator.Web.RestApi.IntegrationTest.Fixtures; using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using Xunit; namespace Generator.Web.RestApi.IntegrationTest { public class CustomersControllerTest : ControllerTest { private List<CustomerRecord> _customerRecords; public CustomersControllerTest(ControllerFixture fixture) : base(fixture) { _customerRecords = new List<CustomerRecord> { new CustomerRecord { FirstName = "Mary", LastName = "Smith", }, new CustomerRecord { FirstName = "John", LastName = "McDonald", } }; Fixture.Db.AddRange(_customerRecords); } [Fact] public async Task ListCustomers_OK() { var listRequest = new ListCustomersRequest { }; var actual = await Fixture.Api.Customers.ListCustomersAsync(listRequest); Assert.Equal(HttpStatusCode.OK, actual.StatusCode); var actualContent = actual.Data; Assert.Equal(2, actualContent.Records.Count); var expectedFirst = _customerRecords[0]; var actualFirst = actualContent.Records[0]; Assert.True(actualFirst.Id > 0); Assert.Equal(expectedFirst.FirstName, actualFirst.FirstName); Assert.Equal(expectedFirst.LastName, actualFirst.LastName); var expectedSecond = _customerRecords[1]; var actualSecond = actualContent.Records[1]; Assert.True(actualSecond.Id > 0); Assert.Equal(expectedSecond.FirstName, actualSecond.FirstName); Assert.Equal(expectedSecond.LastName, actualSecond.LastName); } [Fact] public async Task FindCustomer_Valid_OK() { var customerRecord = _customerRecords[0]; var id = customerRecord.Id; var findRequest = new FindCustomerRequest { Id = id }; var findResponse = await Fixture.Api.Customers.FindCustomerAsync(findRequest); Assert.Equal(HttpStatusCode.OK, findResponse.StatusCode); var findResponseContent = findResponse.Data; Assert.Equal(customerRecord.Id, findResponseContent.Id); Assert.Equal(customerRecord.FirstName, findResponseContent.FirstName); Assert.Equal(customerRecord.LastName, findResponseContent.LastName); } [Fact] public async Task FindCustomer_NotExist_NotFound() { var id = 999; var findRequest = new FindCustomerRequest { Id = id }; var findResponse = await Fixture.Api.Customers.FindCustomerAsync(findRequest); Assert.Equal(HttpStatusCode.NotFound, findResponse.StatusCode); } [Fact] public async Task CreateCustomer_Valid_Created() { var createRequest = new CreateCustomerRequest { FirstName = "First name 1", LastName = "Last name 1", }; var createResponse = await Fixture.Api.Customers.CreateCustomerAsync(createRequest); Assert.Equal(HttpStatusCode.Created, createResponse.StatusCode); var createResponseContent = createResponse.Data; Assert.True(createResponseContent.Id > 0); Assert.Equal(createRequest.FirstName, createResponseContent.FirstName); Assert.Equal(createRequest.LastName, createResponseContent.LastName); var findRequest = new FindCustomerRequest { Id = createResponseContent.Id }; var findResponse = await Fixture.Api.Customers.FindCustomerAsync(findRequest); Assert.Equal(HttpStatusCode.OK, findResponse.StatusCode); var findResponseContent = findResponse.Data; Assert.Equal(createResponseContent.Id, findResponseContent.Id); Assert.Equal(createRequest.FirstName, findResponseContent.FirstName); Assert.Equal(createRequest.LastName, findResponseContent.LastName); } [Fact] public async Task CreateCustomer_Invalid_UnprocessableEntity() { var createRequest = new CreateCustomerRequest { FirstName = null, LastName = "Last name 1", }; var createResponse = await Fixture.Api.Customers.CreateCustomerAsync(createRequest); Assert.Equal(HttpStatusCode.UnprocessableEntity, createResponse.StatusCode); var createResponseContent = createResponse.Data; var problemDetails = createResponse.ProblemDetails; Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails.Status); } [Fact] public async Task UpdateCustomer_Valid_OK() { var customerRecord = _customerRecords[0]; var updateRequest = new UpdateCustomerRequest { Id = customerRecord.Id, FirstName = "New first name", LastName = "New last name", }; var updateResponse = await Fixture.Api.Customers.UpdateCustomerAsync(updateRequest); Assert.Equal(HttpStatusCode.OK, updateResponse.StatusCode); var updateResponseContent = updateResponse.Data; Assert.Equal(updateRequest.Id, updateResponseContent.Id); Assert.Equal(updateRequest.FirstName, updateResponseContent.FirstName); Assert.Equal(updateRequest.LastName, updateResponseContent.LastName); } [Fact] public async Task UpdateCustomer_NotExist_NotFound() { var customerRecord = _customerRecords[0]; var updateRequest = new UpdateCustomerRequest { Id = 999, FirstName = "New first name", LastName = "New last name", }; var updateResponse = await Fixture.Api.Customers.UpdateCustomerAsync(updateRequest); Assert.Equal(HttpStatusCode.NotFound, updateResponse.StatusCode); } [Fact] public async Task UpdateCustomer_Invalid_UnprocessableEntity() { var customerRecord = _customerRecords[0]; var updateRequest = new UpdateCustomerRequest { Id = customerRecord.Id, FirstName = "New first name", LastName = null, }; var updateResponse = await Fixture.Api.Customers.UpdateCustomerAsync(updateRequest); Assert.Equal(HttpStatusCode.UnprocessableEntity, updateResponse.StatusCode); var problemDetails = updateResponse.ProblemDetails; Assert.Equal((int)HttpStatusCode.UnprocessableEntity, problemDetails.Status); } [Fact] public async Task DeleteCustomer_Valid_OK() { var customerRecord = _customerRecords[0]; var id = customerRecord.Id; var deleteRequest = new DeleteCustomerRequest { Id = id }; var deleteResponse = await Fixture.Api.Customers.DeleteCustomerAsync(deleteRequest); Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode); } [Fact] public async Task DeleteCustomer_NotExist_NotFound() { var id = 999; var deleteRequest = new DeleteCustomerRequest { Id = id }; var deleteResponse = await Fixture.Api.Customers.DeleteCustomerAsync(deleteRequest); Assert.Equal(HttpStatusCode.NotFound, deleteResponse.StatusCode); } } }
//============================================================================= // System : Sandcastle Help File Builder Utilities // File : BuildProcess.Namespaces.cs // Author : Eric Woodruff (Eric@EWoodruff.us) // Updated : 07/01/2008 // Note : Copyright 2006-2008, Eric Woodruff, All rights reserved // Compiler: Microsoft Visual C# // // This file contains the code used to generate the namespace summary file and // to purge the unwanted namespaces from the reflection information file. // // This code is published under the Microsoft Public License (Ms-PL). A copy // of the license should be distributed with the code. It can also be found // at the project website: http://SHFB.CodePlex.com. This notice, the // author's name, and all copyright notices must remain intact in all // applications, documentation, and source files. // // Version Date Who Comments // ============================================================================ // 1.2.0.0 09/04/2006 EFW Created the code // 1.3.1.0 09/29/2006 EFW Reworked to insert "missing summary" note for all // namespaces without a summary. // 1.3.2.0 11/10/2006 EFW Reworked to support external XML comments files // 1.4.0.2 05/11/2007 EFW Missing namespace messages are now optional // 1.5.0.2 07/19/2007 EFW Namespace removal is now handled by the MRefBuilder // ripping feature. // 1.5.2.0 09/13/2007 EFW Added support for calling plug-ins // 1.6.0.6 03/08/2008 EFW Added support for NamespaceDoc classes //============================================================================= using System; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Xml; using SandcastleBuilder.Utils.PlugIn; namespace SandcastleBuilder.Utils.BuildEngine { partial class BuildProcess { #region Private data members //===================================================================== // Private data members private XmlCommentsFileCollection commentsFiles; private static Regex reStripWhitespace = new Regex(@"\s"); #endregion #region Private data members //===================================================================== // Private data members /// <summary> /// This read-only property returns the XML comments files collection /// </summary> public XmlCommentsFileCollection CommentsFiles { get { return commentsFiles; } } #endregion /// <summary> /// This is called to generate the namespace summary file /// </summary> protected void GenerateNamespaceSummaries() { XmlNodeList nsElements; XmlNode member; NamespaceSummaryItem nsi; string nsName = null, summaryText; bool isDocumented; this.ReportProgress(BuildStep.GenerateNamespaceSummaries, "Generating namespace summary information..."); // Add a dummy file if there are no comments files specified. // This will contain the project and namespace summaries. if(commentsFiles.Count == 0) { nsName = workingFolder + "_ProjNS_.xml"; using(StreamWriter sw = new StreamWriter(nsName, false, Encoding.UTF8)) { sw.Write("<?xml version=\"1.0\"?>\r\n<doc>\r\n" + "<assembly>\r\n<name>_ProjNS_</name>\r\n" + "</assembly>\r\n<members/>\r\n</doc>\r\n"); } commentsFiles.Add(new XmlCommentsFile(nsName)); } // Replace any "NamespaceDoc" class IDs with their containing // namespace. The comments in these then become the comments // for the namespace. commentsFiles.ReplaceNamespaceDocEntries(); if(this.ExecutePlugIns(ExecutionBehaviors.InsteadOf)) return; this.ExecutePlugIns(ExecutionBehaviors.Before); // XML comments do not support summaries on namespace elements // by default. However, if Sandcastle finds them, it will add // them to the help file. The same holds true for project // comments on the root namespaces page (R:Project). We can // accomplish this by adding elements to the first comments // file or by supplying them in an external XML comments file. try { // Add the project comments if specified if(project.ProjectSummary.Length != 0) { nsName = "R:Project"; // Set name in case it isn't valid member = commentsFiles.FindMember(nsName); this.AddNamespaceComments(member, project.ProjectSummary); } // Get all the namespace nodes nsElements = apisNode.SelectNodes("api[starts-with(@id, 'N:')]"); // Add the namespace summaries foreach(XmlNode n in nsElements) { nsName = n.Attributes["id"].Value; nsi = project.NamespaceSummaries[nsName.Substring(2)]; if(nsi != null) { isDocumented = nsi.IsDocumented; summaryText = nsi.Summary; } else { // The global namespace is not documented by default isDocumented = (nsName != "N:"); summaryText = String.Empty; } // As of 1.5.0.2, namespace removal is handled by // the MRefBuilder ripping feature so we don't have // to deal with it here anymore. // MRefBuilder bug, June CTP and prior. If ripped, an // empty node still appears in the reflection file that // needs to go away when using /internal+. if(n.SelectSingleNode("elements").ChildNodes.Count == 0) n.ParentNode.RemoveChild(n); else if(isDocumented) { // If documented, add the summary text member = commentsFiles.FindMember(nsName); this.AddNamespaceComments(member, summaryText); } } } catch(Exception ex) { // Eat the error in a partial build so that the user can // get into the namespace comments editor to fix it. if(!isPartialBuild) throw new BuilderException("BE0012", String.Format( CultureInfo.InvariantCulture, "Error generating " + "namespace summaries (Namespace = {0}): {1}", nsName, ex.Message), ex); } this.ExecutePlugIns(ExecutionBehaviors.After); } /// <summary> /// Add project or namespace comments /// </summary> /// <param name="member">The member node to modify.</param> /// <param name="summaryText">The summary text to add.</param> private void AddNamespaceComments(XmlNode member, string summaryText) { string text; XmlNode tag = member.SelectSingleNode("summary"); if(tag == null) { tag = member.OwnerDocument.CreateNode(XmlNodeType.Element, "summary", null); member.AppendChild(tag); } text = reStripWhitespace.Replace(tag.InnerText, String.Empty); // NOTE: The text is not HTML encoded as it can contain HTML // tags. As such, entities such as "&" should be entered // in encoded form in the text (i.e. &amp;). if(!String.IsNullOrEmpty(text)) { if(!String.IsNullOrEmpty(summaryText)) tag.InnerXml += "<p/>" + summaryText; } else if(!String.IsNullOrEmpty(summaryText)) tag.InnerXml = summaryText; else if(!project.ShowMissingNamespaces) tag.InnerXml = "&#xA0;"; // The ShowMissingComponent handles adding the "missing" // error message to the topic. } } }
using System; using System.Collections.Generic; using System.Text; namespace ScintillaNet { public class Constants { public const int INVALID_POSITION = -1; public const uint SCI_START = 2000; public const uint SCI_OPTIONAL_START = 3000; public const uint SCI_LEXER_START = 4000; public const uint SCI_ADDTEXT = 2001; public const uint SCI_ADDSTYLEDTEXT = 2002; public const uint SCI_INSERTTEXT = 2003; public const uint SCI_CLEARALL = 2004; public const uint SCI_CLEARDOCUMENTSTYLE = 2005; public const uint SCI_GETLENGTH = 2006; public const uint SCI_GETCHARAT = 2007; public const uint SCI_GETCURRENTPOS = 2008; public const uint SCI_GETANCHOR = 2009; public const uint SCI_GETSTYLEAT = 2010; public const uint SCI_REDO = 2011; public const uint SCI_SETUNDOCOLLECTION = 2012; public const uint SCI_SELECTALL = 2013; public const uint SCI_SETSAVEPOINT = 2014; public const uint SCI_GETSTYLEDTEXT = 2015; public const uint SCI_CANREDO = 2016; public const uint SCI_MARKERLINEFROMHANDLE = 2017; public const uint SCI_MARKERDELETEHANDLE = 2018; public const uint SCI_GETUNDOCOLLECTION = 2019; public const uint SCWS_INVISIBLE = 0; public const uint SCWS_VISIBLEALWAYS = 1; public const uint SCWS_VISIBLEAFTERINDENT = 2; public const uint SCI_GETVIEWWS = 2020; public const uint SCI_SETVIEWWS = 2021; public const uint SCI_POSITIONFROMPOINT = 2022; public const uint SCI_POSITIONFROMPOINTCLOSE = 2023; public const uint SCI_GOTOLINE = 2024; public const uint SCI_GOTOPOS = 2025; public const uint SCI_SETANCHOR = 2026; public const uint SCI_GETCURLINE = 2027; public const uint SCI_GETENDSTYLED = 2028; public const uint SC_EOL_CRLF = 0; public const uint SC_EOL_CR = 1; public const uint SC_EOL_LF = 2; public const uint SCI_CONVERTEOLS = 2029; public const uint SCI_GETEOLMODE = 2030; public const uint SCI_SETEOLMODE = 2031; public const uint SCI_STARTSTYLING = 2032; public const uint SCI_SETSTYLING = 2033; public const uint SCI_GETBUFFEREDDRAW = 2034; public const uint SCI_SETBUFFEREDDRAW = 2035; public const uint SCI_SETTABWIDTH = 2036; public const uint SCI_GETTABWIDTH = 2121; public const uint SC_CP_UTF8 = 65001; public const uint SC_CP_DBCS = 1; public const uint SCI_SETCODEPAGE = 2037; public const uint SCI_SETUSEPALETTE = 2039; public const uint MARKER_MAX = 31; public const uint SC_MARK_CIRCLE = 0; public const uint SC_MARK_ROUNDRECT = 1; public const uint SC_MARK_ARROW = 2; public const uint SC_MARK_SMALLRECT = 3; public const uint SC_MARK_SHORTARROW = 4; public const uint SC_MARK_EMPTY = 5; public const uint SC_MARK_ARROWDOWN = 6; public const uint SC_MARK_MINUS = 7; public const uint SC_MARK_PLUS = 8; public const uint SC_MARK_VLINE = 9; public const uint SC_MARK_LCORNER = 10; public const uint SC_MARK_TCORNER = 11; public const uint SC_MARK_BOXPLUS = 12; public const uint SC_MARK_BOXPLUSCONNECTED = 13; public const uint SC_MARK_BOXMINUS = 14; public const uint SC_MARK_BOXMINUSCONNECTED = 15; public const uint SC_MARK_LCORNERCURVE = 16; public const uint SC_MARK_TCORNERCURVE = 17; public const uint SC_MARK_CIRCLEPLUS = 18; public const uint SC_MARK_CIRCLEPLUSCONNECTED = 19; public const uint SC_MARK_CIRCLEMINUS = 20; public const uint SC_MARK_CIRCLEMINUSCONNECTED = 21; public const uint SC_MARK_BACKGROUND = 22; public const uint SC_MARK_DOTDOTDOT = 23; public const uint SC_MARK_ARROWS = 24; public const uint SC_MARK_PIXMAP = 25; public const uint SC_MARK_FULLRECT = 26; public const uint SC_MARK_CHARACTER = 10000; public const int SC_MARKNUM_FOLDEREND = 25; public const int SC_MARKNUM_FOLDEROPENMID = 26; public const int SC_MARKNUM_FOLDERMIDTAIL = 27; public const int SC_MARKNUM_FOLDERTAIL = 28; public const int SC_MARKNUM_FOLDERSUB = 29; public const int SC_MARKNUM_FOLDER = 30; public const int SC_MARKNUM_FOLDEROPEN = 31; public const int SC_MASK_FOLDERS = -33554432; public const uint SCI_MARKERDEFINE = 2040; public const uint SCI_MARKERSETFORE = 2041; public const uint SCI_MARKERSETBACK = 2042; public const uint SCI_MARKERSETALPHA = 2476; public const uint SCI_MARKERADD = 2043; public const uint SCI_MARKERDELETE = 2044; public const uint SCI_MARKERDELETEALL = 2045; public const uint SCI_MARKERGET = 2046; public const uint SCI_MARKERNEXT = 2047; public const uint SCI_MARKERPREVIOUS = 2048; public const uint SCI_MARKERDEFINEPIXMAP = 2049; public const uint SCI_MARKERADDSET = 2466; public const uint SC_MARGIN_SYMBOL = 0; public const uint SC_MARGIN_NUMBER = 1; public const uint SCI_SETMARGINTYPEN = 2240; public const uint SCI_GETMARGINTYPEN = 2241; public const uint SCI_SETMARGINWIDTHN = 2242; public const uint SCI_GETMARGINWIDTHN = 2243; public const uint SCI_SETMARGINMASKN = 2244; public const uint SCI_GETMARGINMASKN = 2245; public const uint SCI_SETMARGINSENSITIVEN = 2246; public const uint SCI_GETMARGINSENSITIVEN = 2247; public const int STYLE_DEFAULT = 32; public const int STYLE_LINENUMBER = 33; public const int STYLE_BRACELIGHT = 34; public const int STYLE_BRACEBAD = 35; public const int STYLE_CONTROLCHAR = 36; public const int STYLE_INDENTGUIDE = 37; public const int STYLE_CALLTIP = 38; public const int STYLE_LASTPREDEFINED = 39; public const int STYLE_MAX = 127; public const int SC_CHARSET_ANSI = 0; public const int SC_CHARSET_DEFAULT = 1; public const int SC_CHARSET_BALTIC = 186; public const int SC_CHARSET_CHINESEBIG5 = 136; public const int SC_CHARSET_EASTEUROPE = 238; public const int SC_CHARSET_GB2312 = 134; public const int SC_CHARSET_GREEK = 161; public const int SC_CHARSET_HANGUL = 129; public const int SC_CHARSET_MAC = 77; public const int SC_CHARSET_OEM = 255; public const int SC_CHARSET_RUSSIAN = 204; public const int SC_CHARSET_CYRILLIC = 1251; public const int SC_CHARSET_SHIFTJIS = 128; public const int SC_CHARSET_SYMBOL = 2; public const int SC_CHARSET_TURKISH = 162; public const int SC_CHARSET_JOHAB = 130; public const int SC_CHARSET_HEBREW = 177; public const int SC_CHARSET_ARABIC = 178; public const int SC_CHARSET_VIETNAMESE = 163; public const int SC_CHARSET_THAI = 222; public const int SC_CHARSET_8859_15 = 1000; public const uint SCI_STYLECLEARALL = 2050; public const uint SCI_STYLESETFORE = 2051; public const uint SCI_STYLESETBACK = 2052; public const uint SCI_STYLESETBOLD = 2053; public const uint SCI_STYLESETITALIC = 2054; public const uint SCI_STYLESETSIZE = 2055; public const uint SCI_STYLESETFONT = 2056; public const uint SCI_STYLESETEOLFILLED = 2057; public const uint SCI_STYLERESETDEFAULT = 2058; public const uint SCI_STYLESETUNDERLINE = 2059; public const uint SC_CASE_MIXED = 0; public const uint SC_CASE_UPPER = 1; public const uint SC_CASE_LOWER = 2; public const uint SCI_STYLESETCASE = 2060; public const uint SCI_STYLESETCHARACTERSET = 2066; public const uint SCI_STYLESETHOTSPOT = 2409; public const uint SCI_SETSELFORE = 2067; public const uint SCI_SETSELBACK = 2068; public const uint SCI_SETCARETFORE = 2069; public const uint SCI_ASSIGNCMDKEY = 2070; public const uint SCI_CLEARCMDKEY = 2071; public const uint SCI_CLEARALLCMDKEYS = 2072; public const uint SCI_SETSTYLINGEX = 2073; public const uint SCI_STYLESETVISIBLE = 2074; public const uint SCI_GETCARETPERIOD = 2075; public const uint SCI_SETCARETPERIOD = 2076; public const uint SCI_SETWORDCHARS = 2077; public const uint SCI_BEGINUNDOACTION = 2078; public const uint SCI_ENDUNDOACTION = 2079; public const uint INDIC_MAX = 31; public const uint INDIC_PLAIN = 0; public const uint INDIC_SQUIGGLE = 1; public const uint INDIC_TT = 2; public const uint INDIC_DIAGONAL = 3; public const uint INDIC_STRIKE = 4; public const uint INDIC_HIDDEN = 5; public const uint INDIC_BOX = 6; public const uint INDIC_ROUNDBOX = 7; public const int INDIC0_MASK = 0x20; public const int INDIC1_MASK = 0x40; public const int INDIC2_MASK = 0x80; public const int INDICS_MASK = 0xE0; public const uint SCI_INDICSETSTYLE = 2080; public const uint SCI_INDICGETSTYLE = 2081; public const uint SCI_INDICSETFORE = 2082; public const uint SCI_INDICGETFORE = 2083; public const uint SCI_SETWHITESPACEFORE = 2084; public const uint SCI_SETWHITESPACEBACK = 2085; public const uint SCI_SETSTYLEBITS = 2090; public const uint SCI_GETSTYLEBITS = 2091; public const uint SCI_SETLINESTATE = 2092; public const uint SCI_GETLINESTATE = 2093; public const uint SCI_GETMAXLINESTATE = 2094; public const uint SCI_GETCARETLINEVISIBLE = 2095; public const uint SCI_SETCARETLINEVISIBLE = 2096; public const uint SCI_GETCARETLINEBACK = 2097; public const uint SCI_SETCARETLINEBACK = 2098; public const uint SCI_STYLESETCHANGEABLE = 2099; public const uint SCI_AUTOCSHOW = 2100; public const uint SCI_AUTOCCANCEL = 2101; public const uint SCI_AUTOCACTIVE = 2102; public const uint SCI_AUTOCPOSSTART = 2103; public const uint SCI_AUTOCCOMPLETE = 2104; public const uint SCI_AUTOCSTOPS = 2105; public const uint SCI_AUTOCSETSEPARATOR = 2106; public const uint SCI_AUTOCGETSEPARATOR = 2107; public const uint SCI_AUTOCSELECT = 2108; public const uint SCI_AUTOCSETCANCELATSTART = 2110; public const uint SCI_AUTOCGETCANCELATSTART = 2111; public const uint SCI_AUTOCSETFILLUPS = 2112; public const uint SCI_AUTOCSETCHOOSESINGLE = 2113; public const uint SCI_AUTOCGETCHOOSESINGLE = 2114; public const uint SCI_AUTOCSETIGNORECASE = 2115; public const uint SCI_AUTOCGETIGNORECASE = 2116; public const uint SCI_USERLISTSHOW = 2117; public const uint SCI_AUTOCSETAUTOHIDE = 2118; public const uint SCI_AUTOCGETAUTOHIDE = 2119; public const uint SCI_AUTOCSETDROPRESTOFWORD = 2270; public const uint SCI_AUTOCGETDROPRESTOFWORD = 2271; public const uint SCI_REGISTERIMAGE = 2405; public const uint SCI_CLEARREGISTEREDIMAGES = 2408; public const uint SCI_AUTOCGETTYPESEPARATOR = 2285; public const uint SCI_AUTOCSETTYPESEPARATOR = 2286; public const uint SCI_AUTOCSETMAXWIDTH = 2208; public const uint SCI_AUTOCGETMAXWIDTH = 2209; public const uint SCI_AUTOCSETMAXHEIGHT = 2210; public const uint SCI_AUTOCGETMAXHEIGHT = 2211; public const uint SCI_SETINDENT = 2122; public const uint SCI_GETINDENT = 2123; public const uint SCI_SETUSETABS = 2124; public const uint SCI_GETUSETABS = 2125; public const uint SCI_SETLINEINDENTATION = 2126; public const uint SCI_GETLINEINDENTATION = 2127; public const uint SCI_GETLINEINDENTPOSITION = 2128; public const uint SCI_GETCOLUMN = 2129; public const uint SCI_SETHSCROLLBAR = 2130; public const uint SCI_GETHSCROLLBAR = 2131; public const uint SCI_SETINDENTATIONGUIDES = 2132; public const uint SCI_GETINDENTATIONGUIDES = 2133; public const uint SCI_SETHIGHLIGHTGUIDE = 2134; public const uint SCI_GETHIGHLIGHTGUIDE = 2135; public const uint SCI_GETLINEENDPOSITION = 2136; public const uint SCI_GETCODEPAGE = 2137; public const uint SCI_GETCARETFORE = 2138; public const uint SCI_GETUSEPALETTE = 2139; public const uint SCI_GETREADONLY = 2140; public const uint SCI_SETCURRENTPOS = 2141; public const uint SCI_SETSELECTIONSTART = 2142; public const uint SCI_GETSELECTIONSTART = 2143; public const uint SCI_SETSELECTIONEND = 2144; public const uint SCI_GETSELECTIONEND = 2145; public const uint SCI_SETPRINTMAGNIFICATION = 2146; public const uint SCI_GETPRINTMAGNIFICATION = 2147; public const uint SC_PRINT_NORMAL = 0; public const uint SC_PRINT_INVERTLIGHT = 1; public const uint SC_PRINT_BLACKONWHITE = 2; public const uint SC_PRINT_COLOURONWHITE = 3; public const uint SC_PRINT_COLOURONWHITEDEFAULTBG = 4; public const uint SCI_SETPRINTCOLOURMODE = 2148; public const uint SCI_GETPRINTCOLOURMODE = 2149; public const uint SCFIND_WHOLEWORD = 2; public const uint SCFIND_MATCHCASE = 4; public const uint SCFIND_WORDSTART = 0x00100000; public const uint SCFIND_REGEXP = 0x00200000; public const uint SCFIND_POSIX = 0x00400000; public const uint SCI_FINDTEXT = 2150; public const uint SCI_FORMATRANGE = 2151; public const uint SCI_GETFIRSTVISIBLELINE = 2152; public const uint SCI_GETLINE = 2153; public const uint SCI_GETLINECOUNT = 2154; public const uint SCI_SETMARGINLEFT = 2155; public const uint SCI_GETMARGINLEFT = 2156; public const uint SCI_SETMARGINRIGHT = 2157; public const uint SCI_GETMARGINRIGHT = 2158; public const uint SCI_GETMODIFY = 2159; public const uint SCI_SETSEL = 2160; public const uint SCI_GETSELTEXT = 2161; public const uint SCI_GETTEXTRANGE = 2162; public const uint SCI_HIDESELECTION = 2163; public const uint SCI_POINTXFROMPOSITION = 2164; public const uint SCI_POINTYFROMPOSITION = 2165; public const uint SCI_LINEFROMPOSITION = 2166; public const uint SCI_POSITIONFROMLINE = 2167; public const uint SCI_LINESCROLL = 2168; public const uint SCI_SCROLLCARET = 2169; public const uint SCI_REPLACESEL = 2170; public const uint SCI_SETREADONLY = 2171; public const uint SCI_NULL = 2172; public const uint SCI_CANPASTE = 2173; public const uint SCI_CANUNDO = 2174; public const uint SCI_EMPTYUNDOBUFFER = 2175; public const uint SCI_UNDO = 2176; public const uint SCI_CUT = 2177; public const uint SCI_COPY = 2178; public const uint SCI_PASTE = 2179; public const uint SCI_CLEAR = 2180; public const uint SCI_SETTEXT = 2181; public const uint SCI_GETTEXT = 2182; public const uint SCI_GETTEXTLENGTH = 2183; public const uint SCI_GETDIRECTFUNCTION = 2184; public const uint SCI_GETDIRECTPOINTER = 2185; public const uint SCI_SETOVERTYPE = 2186; public const uint SCI_GETOVERTYPE = 2187; public const uint SCI_SETCARETWIDTH = 2188; public const uint SCI_GETCARETWIDTH = 2189; public const uint SCI_SETTARGETSTART = 2190; public const uint SCI_GETTARGETSTART = 2191; public const uint SCI_SETTARGETEND = 2192; public const uint SCI_GETTARGETEND = 2193; public const uint SCI_REPLACETARGET = 2194; public const uint SCI_REPLACETARGETRE = 2195; public const uint SCI_SEARCHINTARGET = 2197; public const uint SCI_SETSEARCHFLAGS = 2198; public const uint SCI_GETSEARCHFLAGS = 2199; public const uint SCI_CALLTIPSHOW = 2200; public const uint SCI_CALLTIPCANCEL = 2201; public const uint SCI_CALLTIPACTIVE = 2202; public const uint SCI_CALLTIPPOSSTART = 2203; public const uint SCI_CALLTIPSETHLT = 2204; public const uint SCI_CALLTIPSETBACK = 2205; public const uint SCI_CALLTIPSETFORE = 2206; public const uint SCI_CALLTIPSETFOREHLT = 2207; public const uint SCI_CALLTIPUSESTYLE = 2212; public const uint SCI_VISIBLEFROMDOCLINE = 2220; public const uint SCI_DOCLINEFROMVISIBLE = 2221; public const uint SCI_WRAPCOUNT = 2235; public const uint SC_FOLDLEVELBASE = 0x400; public const uint SC_FOLDLEVELWHITEFLAG = 0x1000; public const uint SC_FOLDLEVELHEADERFLAG = 0x2000; public const uint SC_FOLDLEVELBOXHEADERFLAG = 0x4000; public const uint SC_FOLDLEVELBOXFOOTERFLAG = 0x8000; public const uint SC_FOLDLEVELCONTRACTED = 0x10000; public const uint SC_FOLDLEVELUNINDENT = 0x20000; public const uint SC_FOLDLEVELNUMBERMASK = 0x0FFF; public const uint SCI_SETFOLDLEVEL = 2222; public const uint SCI_GETFOLDLEVEL = 2223; public const uint SCI_GETLASTCHILD = 2224; public const uint SCI_GETFOLDPARENT = 2225; public const uint SCI_SHOWLINES = 2226; public const uint SCI_HIDELINES = 2227; public const uint SCI_GETLINEVISIBLE = 2228; public const uint SCI_SETFOLDEXPANDED = 2229; public const uint SCI_GETFOLDEXPANDED = 2230; public const uint SCI_TOGGLEFOLD = 2231; public const uint SCI_ENSUREVISIBLE = 2232; public const uint SC_FOLDFLAG_LINEBEFORE_EXPANDED = 0x0002; public const uint SC_FOLDFLAG_LINEBEFORE_CONTRACTED = 0x0004; public const uint SC_FOLDFLAG_LINEAFTER_EXPANDED = 0x0008; public const uint SC_FOLDFLAG_LINEAFTER_CONTRACTED = 0x0010; public const uint SC_FOLDFLAG_LEVELNUMBERS = 0x0040; public const uint SC_FOLDFLAG_BOX = 0x0001; public const uint SCI_SETFOLDFLAGS = 2233; public const uint SCI_ENSUREVISIBLEENFORCEPOLICY = 2234; public const uint SCI_SETTABINDENTS = 2260; public const uint SCI_GETTABINDENTS = 2261; public const uint SCI_SETBACKSPACEUNINDENTS = 2262; public const uint SCI_GETBACKSPACEUNINDENTS = 2263; public const uint SC_TIME_FOREVER = 10000000; public const uint SCI_SETMOUSEDWELLTIME = 2264; public const uint SCI_GETMOUSEDWELLTIME = 2265; public const uint SCI_WORDSTARTPOSITION = 2266; public const uint SCI_WORDENDPOSITION = 2267; public const uint SC_WRAP_NONE = 0; public const uint SC_WRAP_WORD = 1; public const uint SC_WRAP_CHAR = 2; public const uint SCI_SETWRAPMODE = 2268; public const uint SCI_GETWRAPMODE = 2269; public const uint SC_WRAPVISUALFLAG_NONE = 0x0000; public const uint SC_WRAPVISUALFLAG_END = 0x0001; public const uint SC_WRAPVISUALFLAG_START = 0x0002; public const uint SCI_SETWRAPVISUALFLAGS = 2460; public const uint SCI_GETWRAPVISUALFLAGS = 2461; public const uint SC_WRAPVISUALFLAGLOC_DEFAULT = 0x0000; public const uint SC_WRAPVISUALFLAGLOC_END_BY_TEXT = 0x0001; public const uint SC_WRAPVISUALFLAGLOC_START_BY_TEXT = 0x0002; public const uint SCI_SETWRAPVISUALFLAGSLOCATION = 2462; public const uint SCI_GETWRAPVISUALFLAGSLOCATION = 2463; public const uint SCI_SETWRAPSTARTINDENT = 2464; public const uint SCI_GETWRAPSTARTINDENT = 2465; public const uint SC_CACHE_NONE = 0; public const uint SC_CACHE_CARET = 1; public const uint SC_CACHE_PAGE = 2; public const uint SC_CACHE_DOCUMENT = 3; public const uint SCI_SETLAYOUTCACHE = 2272; public const uint SCI_GETLAYOUTCACHE = 2273; public const uint SCI_SETSCROLLWIDTH = 2274; public const uint SCI_GETSCROLLWIDTH = 2275; public const uint SCI_TEXTWIDTH = 2276; public const uint SCI_SETENDATLASTLINE = 2277; public const uint SCI_GETENDATLASTLINE = 2278; public const uint SCI_TEXTHEIGHT = 2279; public const uint SCI_SETVSCROLLBAR = 2280; public const uint SCI_GETVSCROLLBAR = 2281; public const uint SCI_APPENDTEXT = 2282; public const uint SCI_GETTWOPHASEDRAW = 2283; public const uint SCI_SETTWOPHASEDRAW = 2284; public const uint SCI_TARGETFROMSELECTION = 2287; public const uint SCI_LINESJOIN = 2288; public const uint SCI_LINESSPLIT = 2289; public const uint SCI_SETFOLDMARGINCOLOUR = 2290; public const uint SCI_SETFOLDMARGINHICOLOUR = 2291; public const uint SCI_LINEDOWN = 2300; public const uint SCI_LINEDOWNEXTEND = 2301; public const uint SCI_LINEUP = 2302; public const uint SCI_LINEUPEXTEND = 2303; public const uint SCI_CHARLEFT = 2304; public const uint SCI_CHARLEFTEXTEND = 2305; public const uint SCI_CHARRIGHT = 2306; public const uint SCI_CHARRIGHTEXTEND = 2307; public const uint SCI_WORDLEFT = 2308; public const uint SCI_WORDLEFTEXTEND = 2309; public const uint SCI_WORDRIGHT = 2310; public const uint SCI_WORDRIGHTEXTEND = 2311; public const uint SCI_HOME = 2312; public const uint SCI_HOMEEXTEND = 2313; public const uint SCI_LINEEND = 2314; public const uint SCI_LINEENDEXTEND = 2315; public const uint SCI_DOCUMENTSTART = 2316; public const uint SCI_DOCUMENTSTARTEXTEND = 2317; public const uint SCI_DOCUMENTEND = 2318; public const uint SCI_DOCUMENTENDEXTEND = 2319; public const uint SCI_PAGEUP = 2320; public const uint SCI_PAGEUPEXTEND = 2321; public const uint SCI_PAGEDOWN = 2322; public const uint SCI_PAGEDOWNEXTEND = 2323; public const uint SCI_EDITTOGGLEOVERTYPE = 2324; public const uint SCI_CANCEL = 2325; public const uint SCI_DELETEBACK = 2326; public const uint SCI_TAB = 2327; public const uint SCI_BACKTAB = 2328; public const uint SCI_NEWLINE = 2329; public const uint SCI_FORMFEED = 2330; public const uint SCI_VCHOME = 2331; public const uint SCI_VCHOMEEXTEND = 2332; public const uint SCI_ZOOMIN = 2333; public const uint SCI_ZOOMOUT = 2334; public const uint SCI_DELWORDLEFT = 2335; public const uint SCI_DELWORDRIGHT = 2336; public const uint SCI_LINECUT = 2337; public const uint SCI_LINEDELETE = 2338; public const uint SCI_LINETRANSPOSE = 2339; public const uint SCI_LINEDUPLICATE = 2404; public const uint SCI_LOWERCASE = 2340; public const uint SCI_UPPERCASE = 2341; public const uint SCI_LINESCROLLDOWN = 2342; public const uint SCI_LINESCROLLUP = 2343; public const uint SCI_DELETEBACKNOTLINE = 2344; public const uint SCI_HOMEDISPLAY = 2345; public const uint SCI_HOMEDISPLAYEXTEND = 2346; public const uint SCI_LINEENDDISPLAY = 2347; public const uint SCI_LINEENDDISPLAYEXTEND = 2348; public const uint SCI_HOMEWRAP = 2349; public const uint SCI_HOMEWRAPEXTEND = 2450; public const uint SCI_LINEENDWRAP = 2451; public const uint SCI_LINEENDWRAPEXTEND = 2452; public const uint SCI_VCHOMEWRAP = 2453; public const uint SCI_VCHOMEWRAPEXTEND = 2454; public const uint SCI_LINECOPY = 2455; public const uint SCI_MOVECARETINSIDEVIEW = 2401; public const uint SCI_LINELENGTH = 2350; public const uint SCI_BRACEHIGHLIGHT = 2351; public const uint SCI_BRACEBADLIGHT = 2352; public const uint SCI_BRACEMATCH = 2353; public const uint SCI_GETVIEWEOL = 2355; public const uint SCI_SETVIEWEOL = 2356; public const uint SCI_GETDOCPOINTER = 2357; public const uint SCI_SETDOCPOINTER = 2358; public const uint SCI_SETMODEVENTMASK = 2359; public const uint EDGE_NONE = 0; public const uint EDGE_LINE = 1; public const uint EDGE_BACKGROUND = 2; public const uint SCI_GETEDGECOLUMN = 2360; public const uint SCI_SETEDGECOLUMN = 2361; public const uint SCI_GETEDGEMODE = 2362; public const uint SCI_SETEDGEMODE = 2363; public const uint SCI_GETEDGECOLOUR = 2364; public const uint SCI_SETEDGECOLOUR = 2365; public const uint SCI_SEARCHANCHOR = 2366; public const uint SCI_SEARCHNEXT = 2367; public const uint SCI_SEARCHPREV = 2368; public const uint SCI_LINESONSCREEN = 2370; public const uint SCI_USEPOPUP = 2371; public const uint SCI_SELECTIONISRECTANGLE = 2372; public const uint SCI_SETZOOM = 2373; public const uint SCI_GETZOOM = 2374; public const uint SCI_CREATEDOCUMENT = 2375; public const uint SCI_ADDREFDOCUMENT = 2376; public const uint SCI_RELEASEDOCUMENT = 2377; public const uint SCI_GETMODEVENTMASK = 2378; public const uint SCI_SETFOCUS = 2380; public const uint SCI_GETFOCUS = 2381; public const uint SCI_SETSTATUS = 2382; public const uint SCI_GETSTATUS = 2383; public const uint SCI_SETMOUSEDOWNCAPTURES = 2384; public const uint SCI_GETMOUSEDOWNCAPTURES = 2385; public const int SC_CURSORNORMAL = -1; public const int SC_CURSORWAIT = 4; public const uint SCI_SETCURSOR = 2386; public const uint SCI_GETCURSOR = 2387; public const uint SCI_SETCONTROLCHARSYMBOL = 2388; public const uint SCI_GETCONTROLCHARSYMBOL = 2389; public const uint SCI_WORDPARTLEFT = 2390; public const uint SCI_WORDPARTLEFTEXTEND = 2391; public const uint SCI_WORDPARTRIGHT = 2392; public const uint SCI_WORDPARTRIGHTEXTEND = 2393; public const uint VISIBLE_SLOP = 0x01; public const uint VISIBLE_STRICT = 0x04; public const uint SCI_SETVISIBLEPOLICY = 2394; public const uint SCI_DELLINELEFT = 2395; public const uint SCI_DELLINERIGHT = 2396; public const uint SCI_SETXOFFSET = 2397; public const uint SCI_GETXOFFSET = 2398; public const uint SCI_CHOOSECARETX = 2399; public const uint SCI_GRABFOCUS = 2400; public const uint CARET_SLOP = 0x01; public const uint CARET_STRICT = 0x04; public const uint CARET_JUMPS = 0x10; public const uint CARET_EVEN = 0x08; public const uint SCI_SETXCARETPOLICY = 2402; public const uint SCI_SETYCARETPOLICY = 2403; public const uint SCI_SETPRINTWRAPMODE = 2406; public const uint SCI_GETPRINTWRAPMODE = 2407; public const uint SCI_SETHOTSPOTACTIVEFORE = 2410; public const uint SCI_SETHOTSPOTACTIVEBACK = 2411; public const uint SCI_SETHOTSPOTACTIVEUNDERLINE = 2412; public const uint SCI_SETHOTSPOTSINGLELINE = 2421; public const uint SCI_PARADOWN = 2413; public const uint SCI_PARADOWNEXTEND = 2414; public const uint SCI_PARAUP = 2415; public const uint SCI_PARAUPEXTEND = 2416; public const uint SCI_POSITIONBEFORE = 2417; public const uint SCI_POSITIONAFTER = 2418; public const uint SCI_COPYRANGE = 2419; public const uint SCI_COPYTEXT = 2420; public const uint SC_SEL_STREAM = 0; public const uint SC_SEL_RECTANGLE = 1; public const uint SC_SEL_LINES = 2; public const uint SCI_SETSELECTIONMODE = 2422; public const uint SCI_GETSELECTIONMODE = 2423; public const uint SCI_GETLINESELSTARTPOSITION = 2424; public const uint SCI_GETLINESELENDPOSITION = 2425; public const uint SCI_LINEDOWNRECTEXTEND = 2426; public const uint SCI_LINEUPRECTEXTEND = 2427; public const uint SCI_CHARLEFTRECTEXTEND = 2428; public const uint SCI_CHARRIGHTRECTEXTEND = 2429; public const uint SCI_HOMERECTEXTEND = 2430; public const uint SCI_VCHOMERECTEXTEND = 2431; public const uint SCI_LINEENDRECTEXTEND = 2432; public const uint SCI_PAGEUPRECTEXTEND = 2433; public const uint SCI_PAGEDOWNRECTEXTEND = 2434; public const uint SCI_STUTTEREDPAGEUP = 2435; public const uint SCI_STUTTEREDPAGEUPEXTEND = 2436; public const uint SCI_STUTTEREDPAGEDOWN = 2437; public const uint SCI_STUTTEREDPAGEDOWNEXTEND = 2438; public const uint SCI_WORDLEFTEND = 2439; public const uint SCI_WORDLEFTENDEXTEND = 2440; public const uint SCI_WORDRIGHTEND = 2441; public const uint SCI_WORDRIGHTENDEXTEND = 2442; public const uint SCI_SETWHITESPACECHARS = 2443; public const uint SCI_SETCHARSDEFAULT = 2444; public const uint SCI_AUTOCGETCURRENT = 2445; public const uint SCI_ALLOCATE = 2446; public const uint SCI_TARGETASUTF8 = 2447; public const uint SCI_SETLENGTHFORENCODE = 2448; public const uint SCI_ENCODEDFROMUTF8 = 2449; public const uint SCI_FINDCOLUMN = 2456; public const uint SCI_GETCARETSTICKY = 2457; public const uint SCI_SETCARETSTICKY = 2458; public const uint SCI_TOGGLECARETSTICKY = 2459; public const uint SCI_SETPASTECONVERTENDINGS = 2467; public const uint SCI_GETPASTECONVERTENDINGS = 2468; public const uint SCI_SELECTIONDUPLICATE = 2469; public const uint SC_ALPHA_TRANSPARENT = 0; public const uint SC_ALPHA_OPAQUE = 255; public const uint SC_ALPHA_NOALPHA = 256; public const uint SCI_SETCARETLINEBACKALPHA = 2470; public const uint SCI_GETCARETLINEBACKALPHA = 2471; public const uint SCI_STARTRECORD = 3001; public const uint SCI_STOPRECORD = 3002; public const uint SCI_SETLEXER = 4001; public const uint SCI_GETLEXER = 4002; public const uint SCI_COLOURISE = 4003; public const uint SCI_SETPROPERTY = 4004; public const uint KEYWORDSET_MAX = 8; public const uint SCI_SETKEYWORDS = 4005; public const uint SCI_SETLEXERLANGUAGE = 4006; public const uint SCI_LOADLEXERLIBRARY = 4007; public const uint SCI_GETPROPERTY = 4008; public const uint SCI_GETPROPERTYEXPANDED = 4009; public const uint SCI_GETPROPERTYINT = 4010; public const uint SCI_GETSTYLEBITSNEEDED = 4011; public const uint SC_MOD_INSERTTEXT = 0x1; public const uint SC_MOD_DELETETEXT = 0x2; public const uint SC_MOD_CHANGESTYLE = 0x4; public const uint SC_MOD_CHANGEFOLD = 0x8; public const uint SC_PERFORMED_USER = 0x10; public const uint SC_PERFORMED_UNDO = 0x20; public const uint SC_PERFORMED_REDO = 0x40; public const uint SC_MULTISTEPUNDOREDO = 0x80; public const uint SC_LASTSTEPINUNDOREDO = 0x100; public const uint SC_MOD_CHANGEMARKER = 0x200; public const uint SC_MOD_BEFOREINSERT = 0x400; public const uint SC_MOD_BEFOREDELETE = 0x800; public const uint SC_MULTILINEUNDOREDO = 0x1000; public const int SC_MODEVENTMASKALL = 0x6FFF; public const uint SCEN_CHANGE = 768; public const uint SCEN_SETFOCUS = 512; public const uint SCEN_KILLFOCUS = 256; public const uint SCK_DOWN = 300; public const uint SCK_UP = 301; public const uint SCK_LEFT = 302; public const uint SCK_RIGHT = 303; public const uint SCK_HOME = 304; public const uint SCK_END = 305; public const uint SCK_PRIOR = 306; public const uint SCK_NEXT = 307; public const uint SCK_DELETE = 308; public const uint SCK_INSERT = 309; public const uint SCK_ESCAPE = 7; public const uint SCK_BACK = 8; public const uint SCK_TAB = 9; public const uint SCK_RETURN = 13; public const uint SCK_ADD = 310; public const uint SCK_SUBTRACT = 311; public const uint SCK_DIVIDE = 312; public const uint SCMOD_NORM = 0; public const uint SCMOD_SHIFT = 1; public const uint SCMOD_CTRL = 2; public const uint SCMOD_ALT = 4; public const uint SCN_STYLENEEDED = 2000; public const uint SCN_CHARADDED = 2001; public const uint SCN_SAVEPOINTREACHED = 2002; public const uint SCN_SAVEPOINTLEFT = 2003; public const uint SCN_MODIFYATTEMPTRO = 2004; public const uint SCN_KEY = 2005; public const uint SCN_DOUBLECLICK = 2006; public const uint SCN_UPDATEUI = 2007; public const uint SCN_MODIFIED = 2008; public const uint SCN_MACRORECORD = 2009; public const uint SCN_MARGINCLICK = 2010; public const uint SCN_NEEDSHOWN = 2011; public const uint SCN_PAINTED = 2013; public const uint SCN_USERLISTSELECTION = 2014; public const uint SCN_URIDROPPED = 2015; public const uint SCN_DWELLSTART = 2016; public const uint SCN_DWELLEND = 2017; public const uint SCN_ZOOM = 2018; public const uint SCN_HOTSPOTCLICK = 2019; public const uint SCN_HOTSPOTDOUBLECLICK = 2020; public const uint SCN_CALLTIPCLICK = 2021; public const uint SCN_AUTOCSELECTION = 2022; public const uint SCI_STYLEGETFORE = 2481; public const uint SCI_STYLEGETBACK = 2482; public const uint SCI_STYLEGETBOLD = 2483; public const uint SCI_STYLEGETITALIC = 2484; public const uint SCI_STYLEGETSIZE = 2485; public const uint SCI_STYLEGETFONT = 2486; public const uint SCI_STYLEGETEOLFILLED = 2487; public const uint SCI_STYLEGETUNDERLINE = 2488; public const uint SCI_STYLEGETCASE = 2489; public const uint SCI_STYLEGETCHARACTERSET = 2490; public const uint SCI_STYLEGETVISIBLE = 2491; public const uint SCI_STYLEGETCHANGEABLE = 2492; public const uint SCI_STYLEGETHOTSPOT = 2493; public const uint INDIC_CONTAINER = 8; public const uint SCI_INDICSETUNDER = 2510; public const uint SCI_INDICGETUNDER = 2511; public const uint SCI_GETHOTSPOTACTIVEFORE = 2494; public const uint SCI_GETHOTSPOTACTIVEBACK = 2495; public const uint SCI_GETHOTSPOTACTIVEUNDERLINE = 2496; public const uint SCI_GETHOTSPOTSINGLELINE = 2497; public const uint CARETSTYLE_INVISIBLE = 0; public const uint CARETSTYLE_LINE = 1; public const uint CARETSTYLE_BLOCK = 2; public const uint SCI_SETCARETSTYLE = 2512; public const uint SCI_GETCARETSTYLE = 2513; public const uint SCI_SETINDICATORCURRENT = 2500; public const uint SCI_GETINDICATORCURRENT = 2501; public const uint SCI_SETINDICATORVALUE = 2502; public const uint SCI_GETINDICATORVALUE = 2503; public const uint SCI_INDICATORFILLRANGE = 2504; public const uint SCI_INDICATORCLEARRANGE = 2505; public const uint SCI_INDICATORALLONFOR = 2506; public const uint SCI_INDICATORVALUEAT = 2507; public const uint SCI_INDICATORSTART = 2508; public const uint SCI_INDICATOREND = 2509; public const uint SCI_SETPOSITIONCACHE = 2514; public const uint SCI_GETPOSITIONCACHE = 2515; public const uint SC_MOD_CHANGEINDICATOR = 0x4000; public const uint SCN_INDICATORCLICK = 2023; public const uint SCN_INDICATORRELEASE = 2024; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ArtOfTest.WebAii.Controls.HtmlControls; using ArtOfTest.WebAii.Controls.HtmlControls.HtmlAsserts; using ArtOfTest.WebAii.Core; using ArtOfTest.WebAii.ObjectModel; using ArtOfTest.WebAii.TestAttributes; using ArtOfTest.WebAii.TestTemplates; using ArtOfTest.WebAii.Win32.Dialogs; using ArtOfTest.WebAii.Silverlight; using ArtOfTest.WebAii.Silverlight.UI; using Microsoft.VisualStudio.TestTools.UnitTesting; using Telerik.WebAii.Controls.Html; namespace TelerikAcademyTestProject { /// <summary> /// Summary description for TelerikVSUnitTest1 /// </summary> [TestClass] public class TelerikVSUnitTest1 : BaseTest { #region [Setup / TearDown] private TestContext testContextInstance = null; /// <summary> ///Gets or sets the VS test context which provides ///information about and functionality for the ///current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } //Use ClassInitialize to run code before running the first test in the class [ClassInitialize()] public static void MyClassInitialize(TestContext testContext) { } // Use TestInitialize to run code before running each test [TestInitialize()] public void MyTestInitialize() { #region WebAii Initialization // Initializes WebAii manager to be used by the test case. // If a WebAii configuration section exists, settings will be // loaded from it. Otherwise, will create a default settings // object with system defaults. // // Note: We are passing in a delegate to the VisualStudio // testContext.WriteLine() method in addition to the Visual Studio // TestLogs directory as our log location. This way any logging // done from WebAii (i.e. Manager.Log.WriteLine()) is // automatically logged to the VisualStudio test log and // the WebAii log file is placed in the same location as VS logs. // // If you do not care about unifying the log, then you can simply // initialize the test by calling Initialize() with no parameters; // that will cause the log location to be picked up from the config // file if it exists or will use the default system settings (C:\WebAiiLog\) // You can also use Initialize(LogLocation) to set a specific log // location for this test. // Pass in 'true' to recycle the browser between test methods Settings settings = GetSettings(); settings.Web.DefaultBrowser = BrowserType.InternetExplorer; settings.Web.RecycleBrowser = true; //True is needed because of the execution of ShutDown() in ClassCleanUp(). False means that each test will be run in a separate browser settings.ClientReadyTimeout = 60000; settings.ExecuteCommandTimeout = 60000; settings.ExecutionDelay = 200; settings.AnnotateExecution = true; settings.AnnotationMode = AnnotationMode.All; Initialize(settings, new TestContextWriteLine(this.TestContext.WriteLine)); // If you need to override any other settings coming from the // config section you can comment the 'Initialize' line above and instead // use the following: /* // This will get a new Settings object. If a configuration // section exists, then settings from that section will be // loaded Settings settings = GetSettings(); // Override the settings you want. For example: settings.DefaultBrowser = BrowserType.FireFox; // Now call Initialize again with your updated settings object Initialize(settings, new TestContextWriteLine(this.TestContext.WriteLine)); */ // Set the current test method. This is needed for WebAii to discover // its custom TestAttributes set on methods and classes. // This method should always exist in [TestInitialize()] method. SetTestMethod(this, (string)TestContext.Properties["TestName"]); #endregion // // Place any additional initialization here // } // Use TestCleanup to run code after each test has run [TestCleanup()] public void MyTestCleanup() { // // Place any additional cleanup here // #region WebAii CleanUp // Shuts down WebAii manager and closes all browsers currently running // after each test. This call is ignored if recycleBrowser is set this.CleanUp(); #endregion } //Use ClassCleanup to run code after all tests in a class have run [ClassCleanup()] public static void MyClassCleanup() { // This will shut down all browsers if // recycleBrowser is turned on. Else // will do nothing. ShutDown(); } #endregion [TestMethod] public void SampleWebAiiTest() { // Launch a browser instance Manager.LaunchNewBrowser(BrowserType.InternetExplorer); // Navigate the active browser to www.wikipedia.org ActiveBrowser.NavigateTo("http://www.wikipedia.org/"); // Find the wikipedia search box and set it to "Telerik Test Studio"; Find.ById<HtmlInputSearch>("searchInput").Text = "Telerik Test Studio"; // Click the search arrow button Find.ByName<HtmlButton>("go").Click(); // Validate that search contains 'Telerik Test Studio' Assert.IsTrue(ActiveBrowser.ContainsText("Telerik Test Studio")); //Read more here: //http://www.telerik.com/automated-testing-tools/support/documentation/user-guide/write-tests-in-code/intermediate-topics/element-identification/finding-page-elements.aspx } [TestMethod] [DataSource("BoundaryValuesDatasource")] [DeploymentItem("TelerikAcademyTestProject\\Data.xlsx")] public void Slider_DataBinding() { string minimumValue = TestContext.DataRow["MinimumValue"].ToString(); string maximumValue = TestContext.DataRow["MaximumValue"].ToString(); string selectionStart = TestContext.DataRow["SelectionStart"].ToString(); string selectionEnd = TestContext.DataRow["SelectionEnd"].ToString(); string expectedSliderStart = TestContext.DataRow["ExpectedSliderStart"].ToString(); string expectedSliderEnd = TestContext.DataRow["ExpectedSliderEnd"].ToString(); string configuratorId = "ctl00_ConfiguratorPlaceholder_ConfigurationPanel1"; Manager.LaunchNewBrowser(); Manager.ActiveBrowser.Window.Maximize(); ActiveBrowser.NavigateTo("http://demos.telerik.com/aspnet-ajax/slider/examples/clientsideapi/defaultcs.aspx"); HtmlDiv configurator = Find.ByAttributes<HtmlDiv>("class=panel configurator"); //Find.ByAttributes<HtmlDiv>("class=demo-containers").ScrollToVisible(); Manager.ActiveBrowser.ScrollBy(0, 150); Find.ById<HtmlInputText>(configuratorId + "_SmallChangeNtb").MouseClick(); Find.ById<HtmlInputText>(configuratorId + "_SmallChangeNtb").Value = "1"; Find.ById<HtmlInputText>(configuratorId + "_MinValueNtb").MouseClick(); Find.ById<HtmlInputText>(configuratorId + "_MinValueNtb").Value = minimumValue; Find.ById<HtmlInputText>(configuratorId + "_MaxValueNtb").MouseClick(); Find.ById<HtmlInputText>(configuratorId + "_MaxValueNtb").Value = maximumValue; Find.ById<HtmlInputText>(configuratorId + "_SelectionStartNtb").MouseClick(); Find.ById<HtmlInputText>(configuratorId + "_SelectionStartNtb").Value = selectionStart; Find.ById<HtmlInputText>(configuratorId + "_SelectionEndNtb").MouseClick(); Find.ById<HtmlInputText>(configuratorId + "_SelectionEndNtb").Value = selectionEnd; Find.ById<HtmlInputText>(configuratorId + "_SelectionStartNtb").MouseClick(); RadSlider slider = Find.ById<RadSlider>("RadSliderWrapper_ctl00_ContentPlaceholder1_RadSlider1"); Assert.AreEqual(expectedSliderStart, slider.SelectionStart.ToString()); Assert.AreEqual(expectedSliderEnd, slider.SelectionEnd.ToString()); } } }
namespace DynamicLinqWithExpressionTree.Database { using System; using System.Data.Entity; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; public partial class AdventureWorks2014Context : DbContext { public AdventureWorks2014Context() : base("name=AdventureWorksContext") { } public virtual DbSet<AWBuildVersion> AWBuildVersions { get; set; } public virtual DbSet<DatabaseLog> DatabaseLogs { get; set; } public virtual DbSet<ErrorLog> ErrorLogs { get; set; } public virtual DbSet<Department> Departments { get; set; } public virtual DbSet<Employee> Employees { get; set; } public virtual DbSet<EmployeeDepartmentHistory> EmployeeDepartmentHistories { get; set; } public virtual DbSet<EmployeePayHistory> EmployeePayHistories { get; set; } public virtual DbSet<JobCandidate> JobCandidates { get; set; } public virtual DbSet<Shift> Shifts { get; set; } public virtual DbSet<Address> Addresses { get; set; } public virtual DbSet<AddressType> AddressTypes { get; set; } public virtual DbSet<BusinessEntity> BusinessEntities { get; set; } public virtual DbSet<BusinessEntityAddress> BusinessEntityAddresses { get; set; } public virtual DbSet<BusinessEntityContact> BusinessEntityContacts { get; set; } public virtual DbSet<ContactType> ContactTypes { get; set; } public virtual DbSet<CountryRegion> CountryRegions { get; set; } public virtual DbSet<EmailAddress> EmailAddresses { get; set; } public virtual DbSet<Password> Passwords { get; set; } public virtual DbSet<Person> People { get; set; } public virtual DbSet<PersonPhone> PersonPhones { get; set; } public virtual DbSet<PhoneNumberType> PhoneNumberTypes { get; set; } public virtual DbSet<StateProvince> StateProvinces { get; set; } public virtual DbSet<BillOfMaterial> BillOfMaterials { get; set; } public virtual DbSet<Culture> Cultures { get; set; } public virtual DbSet<Illustration> Illustrations { get; set; } public virtual DbSet<Location> Locations { get; set; } public virtual DbSet<Product> Products { get; set; } public virtual DbSet<ProductCategory> ProductCategories { get; set; } public virtual DbSet<ProductCostHistory> ProductCostHistories { get; set; } public virtual DbSet<ProductDescription> ProductDescriptions { get; set; } public virtual DbSet<ProductInventory> ProductInventories { get; set; } public virtual DbSet<ProductListPriceHistory> ProductListPriceHistories { get; set; } public virtual DbSet<ProductModel> ProductModels { get; set; } public virtual DbSet<ProductModelIllustration> ProductModelIllustrations { get; set; } public virtual DbSet<ProductModelProductDescriptionCulture> ProductModelProductDescriptionCultures { get; set; } public virtual DbSet<ProductPhoto> ProductPhotoes { get; set; } public virtual DbSet<ProductProductPhoto> ProductProductPhotoes { get; set; } public virtual DbSet<ProductReview> ProductReviews { get; set; } public virtual DbSet<ProductSubcategory> ProductSubcategories { get; set; } public virtual DbSet<ScrapReason> ScrapReasons { get; set; } public virtual DbSet<TransactionHistory> TransactionHistories { get; set; } public virtual DbSet<TransactionHistoryArchive> TransactionHistoryArchives { get; set; } public virtual DbSet<UnitMeasure> UnitMeasures { get; set; } public virtual DbSet<WorkOrder> WorkOrders { get; set; } public virtual DbSet<WorkOrderRouting> WorkOrderRoutings { get; set; } public virtual DbSet<ProductVendor> ProductVendors { get; set; } public virtual DbSet<PurchaseOrderDetail> PurchaseOrderDetails { get; set; } public virtual DbSet<PurchaseOrderHeader> PurchaseOrderHeaders { get; set; } public virtual DbSet<ShipMethod> ShipMethods { get; set; } public virtual DbSet<Vendor> Vendors { get; set; } public virtual DbSet<CountryRegionCurrency> CountryRegionCurrencies { get; set; } public virtual DbSet<CreditCard> CreditCards { get; set; } public virtual DbSet<Currency> Currencies { get; set; } public virtual DbSet<CurrencyRate> CurrencyRates { get; set; } public virtual DbSet<Customer> Customers { get; set; } public virtual DbSet<PersonCreditCard> PersonCreditCards { get; set; } public virtual DbSet<SalesOrderDetail> SalesOrderDetails { get; set; } public virtual DbSet<SalesOrderHeader> SalesOrderHeaders { get; set; } public virtual DbSet<SalesOrderHeaderSalesReason> SalesOrderHeaderSalesReasons { get; set; } public virtual DbSet<SalesPerson> SalesPersons { get; set; } public virtual DbSet<SalesPersonQuotaHistory> SalesPersonQuotaHistories { get; set; } public virtual DbSet<SalesReason> SalesReasons { get; set; } public virtual DbSet<SalesTaxRate> SalesTaxRates { get; set; } public virtual DbSet<SalesTerritory> SalesTerritories { get; set; } public virtual DbSet<SalesTerritoryHistory> SalesTerritoryHistories { get; set; } public virtual DbSet<ShoppingCartItem> ShoppingCartItems { get; set; } public virtual DbSet<SpecialOffer> SpecialOffers { get; set; } public virtual DbSet<SpecialOfferProduct> SpecialOfferProducts { get; set; } public virtual DbSet<Store> Stores { get; set; } public virtual DbSet<ProductDocument> ProductDocuments { get; set; } public virtual DbSet<vEmployee> vEmployees { get; set; } public virtual DbSet<vEmployeeDepartment> vEmployeeDepartments { get; set; } public virtual DbSet<vEmployeeDepartmentHistory> vEmployeeDepartmentHistories { get; set; } public virtual DbSet<vJobCandidate> vJobCandidates { get; set; } public virtual DbSet<vJobCandidateEducation> vJobCandidateEducations { get; set; } public virtual DbSet<vJobCandidateEmployment> vJobCandidateEmployments { get; set; } public virtual DbSet<vAdditionalContactInfo> vAdditionalContactInfoes { get; set; } public virtual DbSet<vStateProvinceCountryRegion> vStateProvinceCountryRegions { get; set; } public virtual DbSet<vProductAndDescription> vProductAndDescriptions { get; set; } public virtual DbSet<vProductModelCatalogDescription> vProductModelCatalogDescriptions { get; set; } public virtual DbSet<vProductModelInstruction> vProductModelInstructions { get; set; } public virtual DbSet<vVendorWithAddress> vVendorWithAddresses { get; set; } public virtual DbSet<vVendorWithContact> vVendorWithContacts { get; set; } public virtual DbSet<vIndividualCustomer> vIndividualCustomers { get; set; } public virtual DbSet<vPersonDemographic> vPersonDemographics { get; set; } public virtual DbSet<vSalesPerson> vSalesPersons { get; set; } public virtual DbSet<vSalesPersonSalesByFiscalYear> vSalesPersonSalesByFiscalYears { get; set; } public virtual DbSet<vStoreWithAddress> vStoreWithAddresses { get; set; } public virtual DbSet<vStoreWithContact> vStoreWithContacts { get; set; } public virtual DbSet<vStoreWithDemographic> vStoreWithDemographics { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Department>() .HasMany(e => e.EmployeeDepartmentHistories) .WithRequired(e => e.Department) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .Property(e => e.MaritalStatus) .IsFixedLength(); modelBuilder.Entity<Employee>() .Property(e => e.Gender) .IsFixedLength(); modelBuilder.Entity<Employee>() .HasMany(e => e.EmployeeDepartmentHistories) .WithRequired(e => e.Employee) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .HasMany(e => e.EmployeePayHistories) .WithRequired(e => e.Employee) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .HasMany(e => e.PurchaseOrderHeaders) .WithRequired(e => e.Employee) .HasForeignKey(e => e.EmployeeID) .WillCascadeOnDelete(false); modelBuilder.Entity<Employee>() .HasOptional(e => e.SalesPerson) .WithRequired(e => e.Employee); modelBuilder.Entity<EmployeePayHistory>() .Property(e => e.Rate) .HasPrecision(19, 4); modelBuilder.Entity<Shift>() .HasMany(e => e.EmployeeDepartmentHistories) .WithRequired(e => e.Shift) .WillCascadeOnDelete(false); modelBuilder.Entity<Address>() .HasMany(e => e.BusinessEntityAddresses) .WithRequired(e => e.Address) .WillCascadeOnDelete(false); modelBuilder.Entity<Address>() .HasMany(e => e.SalesOrderHeaders) .WithRequired(e => e.Address) .HasForeignKey(e => e.BillToAddressID) .WillCascadeOnDelete(false); modelBuilder.Entity<Address>() .HasMany(e => e.SalesOrderHeaders1) .WithRequired(e => e.Address1) .HasForeignKey(e => e.ShipToAddressID) .WillCascadeOnDelete(false); modelBuilder.Entity<AddressType>() .HasMany(e => e.BusinessEntityAddresses) .WithRequired(e => e.AddressType) .WillCascadeOnDelete(false); modelBuilder.Entity<BusinessEntity>() .HasMany(e => e.BusinessEntityAddresses) .WithRequired(e => e.BusinessEntity) .WillCascadeOnDelete(false); modelBuilder.Entity<BusinessEntity>() .HasMany(e => e.BusinessEntityContacts) .WithRequired(e => e.BusinessEntity) .WillCascadeOnDelete(false); modelBuilder.Entity<BusinessEntity>() .HasOptional(e => e.Person) .WithRequired(e => e.BusinessEntity); modelBuilder.Entity<BusinessEntity>() .HasOptional(e => e.Store) .WithRequired(e => e.BusinessEntity); modelBuilder.Entity<BusinessEntity>() .HasOptional(e => e.Vendor) .WithRequired(e => e.BusinessEntity); modelBuilder.Entity<ContactType>() .HasMany(e => e.BusinessEntityContacts) .WithRequired(e => e.ContactType) .WillCascadeOnDelete(false); modelBuilder.Entity<CountryRegion>() .HasMany(e => e.CountryRegionCurrencies) .WithRequired(e => e.CountryRegion) .WillCascadeOnDelete(false); modelBuilder.Entity<CountryRegion>() .HasMany(e => e.SalesTerritories) .WithRequired(e => e.CountryRegion) .WillCascadeOnDelete(false); modelBuilder.Entity<CountryRegion>() .HasMany(e => e.StateProvinces) .WithRequired(e => e.CountryRegion) .WillCascadeOnDelete(false); modelBuilder.Entity<Password>() .Property(e => e.PasswordHash) .IsUnicode(false); modelBuilder.Entity<Password>() .Property(e => e.PasswordSalt) .IsUnicode(false); modelBuilder.Entity<Person>() .Property(e => e.PersonType) .IsFixedLength(); modelBuilder.Entity<Person>() .HasOptional(e => e.Employee) .WithRequired(e => e.Person); modelBuilder.Entity<Person>() .HasMany(e => e.BusinessEntityContacts) .WithRequired(e => e.Person) .HasForeignKey(e => e.PersonID) .WillCascadeOnDelete(false); modelBuilder.Entity<Person>() .HasMany(e => e.EmailAddresses) .WithRequired(e => e.Person) .WillCascadeOnDelete(false); modelBuilder.Entity<Person>() .HasOptional(e => e.Password) .WithRequired(e => e.Person); modelBuilder.Entity<Person>() .HasMany(e => e.Customers) .WithOptional(e => e.Person) .HasForeignKey(e => e.PersonID); modelBuilder.Entity<Person>() .HasMany(e => e.PersonCreditCards) .WithRequired(e => e.Person) .WillCascadeOnDelete(false); modelBuilder.Entity<Person>() .HasMany(e => e.PersonPhones) .WithRequired(e => e.Person) .WillCascadeOnDelete(false); modelBuilder.Entity<PhoneNumberType>() .HasMany(e => e.PersonPhones) .WithRequired(e => e.PhoneNumberType) .WillCascadeOnDelete(false); modelBuilder.Entity<StateProvince>() .Property(e => e.StateProvinceCode) .IsFixedLength(); modelBuilder.Entity<StateProvince>() .HasMany(e => e.Addresses) .WithRequired(e => e.StateProvince) .WillCascadeOnDelete(false); modelBuilder.Entity<StateProvince>() .HasMany(e => e.SalesTaxRates) .WithRequired(e => e.StateProvince) .WillCascadeOnDelete(false); modelBuilder.Entity<BillOfMaterial>() .Property(e => e.UnitMeasureCode) .IsFixedLength(); modelBuilder.Entity<BillOfMaterial>() .Property(e => e.PerAssemblyQty) .HasPrecision(8, 2); modelBuilder.Entity<Culture>() .Property(e => e.CultureID) .IsFixedLength(); modelBuilder.Entity<Culture>() .HasMany(e => e.ProductModelProductDescriptionCultures) .WithRequired(e => e.Culture) .WillCascadeOnDelete(false); modelBuilder.Entity<Illustration>() .HasMany(e => e.ProductModelIllustrations) .WithRequired(e => e.Illustration) .WillCascadeOnDelete(false); modelBuilder.Entity<Location>() .Property(e => e.CostRate) .HasPrecision(10, 4); modelBuilder.Entity<Location>() .Property(e => e.Availability) .HasPrecision(8, 2); modelBuilder.Entity<Location>() .HasMany(e => e.ProductInventories) .WithRequired(e => e.Location) .WillCascadeOnDelete(false); modelBuilder.Entity<Location>() .HasMany(e => e.WorkOrderRoutings) .WithRequired(e => e.Location) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .Property(e => e.StandardCost) .HasPrecision(19, 4); modelBuilder.Entity<Product>() .Property(e => e.ListPrice) .HasPrecision(19, 4); modelBuilder.Entity<Product>() .Property(e => e.SizeUnitMeasureCode) .IsFixedLength(); modelBuilder.Entity<Product>() .Property(e => e.WeightUnitMeasureCode) .IsFixedLength(); modelBuilder.Entity<Product>() .Property(e => e.Weight) .HasPrecision(8, 2); modelBuilder.Entity<Product>() .Property(e => e.ProductLine) .IsFixedLength(); modelBuilder.Entity<Product>() .Property(e => e.Class) .IsFixedLength(); modelBuilder.Entity<Product>() .Property(e => e.Style) .IsFixedLength(); modelBuilder.Entity<Product>() .HasMany(e => e.BillOfMaterials) .WithRequired(e => e.Product) .HasForeignKey(e => e.ComponentID) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.BillOfMaterials1) .WithOptional(e => e.Product1) .HasForeignKey(e => e.ProductAssemblyID); modelBuilder.Entity<Product>() .HasMany(e => e.ProductCostHistories) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasOptional(e => e.ProductDocument) .WithRequired(e => e.Product); modelBuilder.Entity<Product>() .HasMany(e => e.ProductInventories) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.ProductListPriceHistories) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.ProductProductPhotoes) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.ProductReviews) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.ProductVendors) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.PurchaseOrderDetails) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.ShoppingCartItems) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.SpecialOfferProducts) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.TransactionHistories) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<Product>() .HasMany(e => e.WorkOrders) .WithRequired(e => e.Product) .WillCascadeOnDelete(false); modelBuilder.Entity<ProductCategory>() .HasMany(e => e.ProductSubcategories) .WithRequired(e => e.ProductCategory) .WillCascadeOnDelete(false); modelBuilder.Entity<ProductCostHistory>() .Property(e => e.StandardCost) .HasPrecision(19, 4); modelBuilder.Entity<ProductDescription>() .HasMany(e => e.ProductModelProductDescriptionCultures) .WithRequired(e => e.ProductDescription) .WillCascadeOnDelete(false); modelBuilder.Entity<ProductListPriceHistory>() .Property(e => e.ListPrice) .HasPrecision(19, 4); modelBuilder.Entity<ProductModel>() .HasMany(e => e.ProductModelIllustrations) .WithRequired(e => e.ProductModel) .WillCascadeOnDelete(false); modelBuilder.Entity<ProductModel>() .HasMany(e => e.ProductModelProductDescriptionCultures) .WithRequired(e => e.ProductModel) .WillCascadeOnDelete(false); modelBuilder.Entity<ProductModelProductDescriptionCulture>() .Property(e => e.CultureID) .IsFixedLength(); modelBuilder.Entity<ProductPhoto>() .HasMany(e => e.ProductProductPhotoes) .WithRequired(e => e.ProductPhoto) .WillCascadeOnDelete(false); modelBuilder.Entity<TransactionHistory>() .Property(e => e.TransactionType) .IsFixedLength(); modelBuilder.Entity<TransactionHistory>() .Property(e => e.ActualCost) .HasPrecision(19, 4); modelBuilder.Entity<TransactionHistoryArchive>() .Property(e => e.TransactionType) .IsFixedLength(); modelBuilder.Entity<TransactionHistoryArchive>() .Property(e => e.ActualCost) .HasPrecision(19, 4); modelBuilder.Entity<UnitMeasure>() .Property(e => e.UnitMeasureCode) .IsFixedLength(); modelBuilder.Entity<UnitMeasure>() .HasMany(e => e.BillOfMaterials) .WithRequired(e => e.UnitMeasure) .WillCascadeOnDelete(false); modelBuilder.Entity<UnitMeasure>() .HasMany(e => e.Products) .WithOptional(e => e.UnitMeasure) .HasForeignKey(e => e.SizeUnitMeasureCode); modelBuilder.Entity<UnitMeasure>() .HasMany(e => e.Products1) .WithOptional(e => e.UnitMeasure1) .HasForeignKey(e => e.WeightUnitMeasureCode); modelBuilder.Entity<UnitMeasure>() .HasMany(e => e.ProductVendors) .WithRequired(e => e.UnitMeasure) .WillCascadeOnDelete(false); modelBuilder.Entity<WorkOrder>() .HasMany(e => e.WorkOrderRoutings) .WithRequired(e => e.WorkOrder) .WillCascadeOnDelete(false); modelBuilder.Entity<WorkOrderRouting>() .Property(e => e.ActualResourceHrs) .HasPrecision(9, 4); modelBuilder.Entity<WorkOrderRouting>() .Property(e => e.PlannedCost) .HasPrecision(19, 4); modelBuilder.Entity<WorkOrderRouting>() .Property(e => e.ActualCost) .HasPrecision(19, 4); modelBuilder.Entity<ProductVendor>() .Property(e => e.StandardPrice) .HasPrecision(19, 4); modelBuilder.Entity<ProductVendor>() .Property(e => e.LastReceiptCost) .HasPrecision(19, 4); modelBuilder.Entity<ProductVendor>() .Property(e => e.UnitMeasureCode) .IsFixedLength(); modelBuilder.Entity<PurchaseOrderDetail>() .Property(e => e.UnitPrice) .HasPrecision(19, 4); modelBuilder.Entity<PurchaseOrderDetail>() .Property(e => e.LineTotal) .HasPrecision(19, 4); modelBuilder.Entity<PurchaseOrderDetail>() .Property(e => e.ReceivedQty) .HasPrecision(8, 2); modelBuilder.Entity<PurchaseOrderDetail>() .Property(e => e.RejectedQty) .HasPrecision(8, 2); modelBuilder.Entity<PurchaseOrderDetail>() .Property(e => e.StockedQty) .HasPrecision(9, 2); modelBuilder.Entity<PurchaseOrderHeader>() .Property(e => e.SubTotal) .HasPrecision(19, 4); modelBuilder.Entity<PurchaseOrderHeader>() .Property(e => e.TaxAmt) .HasPrecision(19, 4); modelBuilder.Entity<PurchaseOrderHeader>() .Property(e => e.Freight) .HasPrecision(19, 4); modelBuilder.Entity<PurchaseOrderHeader>() .Property(e => e.TotalDue) .HasPrecision(19, 4); modelBuilder.Entity<PurchaseOrderHeader>() .HasMany(e => e.PurchaseOrderDetails) .WithRequired(e => e.PurchaseOrderHeader) .WillCascadeOnDelete(false); modelBuilder.Entity<ShipMethod>() .Property(e => e.ShipBase) .HasPrecision(19, 4); modelBuilder.Entity<ShipMethod>() .Property(e => e.ShipRate) .HasPrecision(19, 4); modelBuilder.Entity<ShipMethod>() .HasMany(e => e.PurchaseOrderHeaders) .WithRequired(e => e.ShipMethod) .WillCascadeOnDelete(false); modelBuilder.Entity<ShipMethod>() .HasMany(e => e.SalesOrderHeaders) .WithRequired(e => e.ShipMethod) .WillCascadeOnDelete(false); modelBuilder.Entity<Vendor>() .HasMany(e => e.ProductVendors) .WithRequired(e => e.Vendor) .WillCascadeOnDelete(false); modelBuilder.Entity<Vendor>() .HasMany(e => e.PurchaseOrderHeaders) .WithRequired(e => e.Vendor) .HasForeignKey(e => e.VendorID) .WillCascadeOnDelete(false); modelBuilder.Entity<CountryRegionCurrency>() .Property(e => e.CurrencyCode) .IsFixedLength(); modelBuilder.Entity<CreditCard>() .HasMany(e => e.PersonCreditCards) .WithRequired(e => e.CreditCard) .WillCascadeOnDelete(false); modelBuilder.Entity<Currency>() .Property(e => e.CurrencyCode) .IsFixedLength(); modelBuilder.Entity<Currency>() .HasMany(e => e.CountryRegionCurrencies) .WithRequired(e => e.Currency) .WillCascadeOnDelete(false); modelBuilder.Entity<Currency>() .HasMany(e => e.CurrencyRates) .WithRequired(e => e.Currency) .HasForeignKey(e => e.FromCurrencyCode) .WillCascadeOnDelete(false); modelBuilder.Entity<Currency>() .HasMany(e => e.CurrencyRates1) .WithRequired(e => e.Currency1) .HasForeignKey(e => e.ToCurrencyCode) .WillCascadeOnDelete(false); modelBuilder.Entity<CurrencyRate>() .Property(e => e.FromCurrencyCode) .IsFixedLength(); modelBuilder.Entity<CurrencyRate>() .Property(e => e.ToCurrencyCode) .IsFixedLength(); modelBuilder.Entity<CurrencyRate>() .Property(e => e.AverageRate) .HasPrecision(19, 4); modelBuilder.Entity<CurrencyRate>() .Property(e => e.EndOfDayRate) .HasPrecision(19, 4); modelBuilder.Entity<Customer>() .Property(e => e.AccountNumber) .IsUnicode(false); modelBuilder.Entity<Customer>() .HasMany(e => e.SalesOrderHeaders) .WithRequired(e => e.Customer) .WillCascadeOnDelete(false); modelBuilder.Entity<SalesOrderDetail>() .Property(e => e.UnitPrice) .HasPrecision(19, 4); modelBuilder.Entity<SalesOrderDetail>() .Property(e => e.UnitPriceDiscount) .HasPrecision(19, 4); modelBuilder.Entity<SalesOrderDetail>() .Property(e => e.LineTotal) .HasPrecision(38, 6); modelBuilder.Entity<SalesOrderHeader>() .Property(e => e.CreditCardApprovalCode) .IsUnicode(false); modelBuilder.Entity<SalesOrderHeader>() .Property(e => e.SubTotal) .HasPrecision(19, 4); modelBuilder.Entity<SalesOrderHeader>() .Property(e => e.TaxAmt) .HasPrecision(19, 4); modelBuilder.Entity<SalesOrderHeader>() .Property(e => e.Freight) .HasPrecision(19, 4); modelBuilder.Entity<SalesOrderHeader>() .Property(e => e.TotalDue) .HasPrecision(19, 4); modelBuilder.Entity<SalesPerson>() .Property(e => e.SalesQuota) .HasPrecision(19, 4); modelBuilder.Entity<SalesPerson>() .Property(e => e.Bonus) .HasPrecision(19, 4); modelBuilder.Entity<SalesPerson>() .Property(e => e.CommissionPct) .HasPrecision(10, 4); modelBuilder.Entity<SalesPerson>() .Property(e => e.SalesYTD) .HasPrecision(19, 4); modelBuilder.Entity<SalesPerson>() .Property(e => e.SalesLastYear) .HasPrecision(19, 4); modelBuilder.Entity<SalesPerson>() .HasMany(e => e.SalesOrderHeaders) .WithOptional(e => e.SalesPerson) .HasForeignKey(e => e.SalesPersonID); modelBuilder.Entity<SalesPerson>() .HasMany(e => e.SalesPersonQuotaHistories) .WithRequired(e => e.SalesPerson) .WillCascadeOnDelete(false); modelBuilder.Entity<SalesPerson>() .HasMany(e => e.SalesTerritoryHistories) .WithRequired(e => e.SalesPerson) .WillCascadeOnDelete(false); modelBuilder.Entity<SalesPerson>() .HasMany(e => e.Stores) .WithOptional(e => e.SalesPerson) .HasForeignKey(e => e.SalesPersonID); modelBuilder.Entity<SalesPersonQuotaHistory>() .Property(e => e.SalesQuota) .HasPrecision(19, 4); modelBuilder.Entity<SalesReason>() .HasMany(e => e.SalesOrderHeaderSalesReasons) .WithRequired(e => e.SalesReason) .WillCascadeOnDelete(false); modelBuilder.Entity<SalesTaxRate>() .Property(e => e.TaxRate) .HasPrecision(10, 4); modelBuilder.Entity<SalesTerritory>() .Property(e => e.SalesYTD) .HasPrecision(19, 4); modelBuilder.Entity<SalesTerritory>() .Property(e => e.SalesLastYear) .HasPrecision(19, 4); modelBuilder.Entity<SalesTerritory>() .Property(e => e.CostYTD) .HasPrecision(19, 4); modelBuilder.Entity<SalesTerritory>() .Property(e => e.CostLastYear) .HasPrecision(19, 4); modelBuilder.Entity<SalesTerritory>() .HasMany(e => e.StateProvinces) .WithRequired(e => e.SalesTerritory) .WillCascadeOnDelete(false); modelBuilder.Entity<SalesTerritory>() .HasMany(e => e.SalesTerritoryHistories) .WithRequired(e => e.SalesTerritory) .WillCascadeOnDelete(false); modelBuilder.Entity<SpecialOffer>() .Property(e => e.DiscountPct) .HasPrecision(10, 4); modelBuilder.Entity<SpecialOffer>() .HasMany(e => e.SpecialOfferProducts) .WithRequired(e => e.SpecialOffer) .WillCascadeOnDelete(false); modelBuilder.Entity<SpecialOfferProduct>() .HasMany(e => e.SalesOrderDetails) .WithRequired(e => e.SpecialOfferProduct) .HasForeignKey(e => new { e.SpecialOfferID, e.ProductID }) .WillCascadeOnDelete(false); modelBuilder.Entity<Store>() .HasMany(e => e.Customers) .WithOptional(e => e.Store) .HasForeignKey(e => e.StoreID); modelBuilder.Entity<vStateProvinceCountryRegion>() .Property(e => e.StateProvinceCode) .IsFixedLength(); modelBuilder.Entity<vProductAndDescription>() .Property(e => e.CultureID) .IsFixedLength(); modelBuilder.Entity<vProductModelInstruction>() .Property(e => e.SetupHours) .HasPrecision(9, 4); modelBuilder.Entity<vProductModelInstruction>() .Property(e => e.MachineHours) .HasPrecision(9, 4); modelBuilder.Entity<vProductModelInstruction>() .Property(e => e.LaborHours) .HasPrecision(9, 4); modelBuilder.Entity<vPersonDemographic>() .Property(e => e.TotalPurchaseYTD) .HasPrecision(19, 4); modelBuilder.Entity<vSalesPerson>() .Property(e => e.SalesQuota) .HasPrecision(19, 4); modelBuilder.Entity<vSalesPerson>() .Property(e => e.SalesYTD) .HasPrecision(19, 4); modelBuilder.Entity<vSalesPerson>() .Property(e => e.SalesLastYear) .HasPrecision(19, 4); modelBuilder.Entity<vSalesPersonSalesByFiscalYear>() .Property(e => e.C2002) .HasPrecision(19, 4); modelBuilder.Entity<vSalesPersonSalesByFiscalYear>() .Property(e => e.C2003) .HasPrecision(19, 4); modelBuilder.Entity<vSalesPersonSalesByFiscalYear>() .Property(e => e.C2004) .HasPrecision(19, 4); modelBuilder.Entity<vStoreWithDemographic>() .Property(e => e.AnnualSales) .HasPrecision(19, 4); modelBuilder.Entity<vStoreWithDemographic>() .Property(e => e.AnnualRevenue) .HasPrecision(19, 4); } } }