context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// 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.Text; using System; using System.Diagnostics; namespace System.Text { // A Decoder is used to decode a sequence of blocks of bytes into a // sequence of blocks of characters. Following instantiation of a decoder, // sequential blocks of bytes are converted into blocks of characters through // calls to the GetChars method. The decoder maintains state between the // conversions, allowing it to correctly decode byte sequences that span // adjacent blocks. // // Instances of specific implementations of the Decoder abstract base // class are typically obtained through calls to the GetDecoder method // of Encoding objects. // public abstract class Decoder { internal DecoderFallback _fallback = null; internal DecoderFallbackBuffer _fallbackBuffer = null; protected Decoder() { // We don't call default reset because default reset probably isn't good if we aren't initialized. } public DecoderFallback Fallback { get { return _fallback; } set { if (value == null) throw new ArgumentNullException(nameof(value)); // Can't change fallback if buffer is wrong if (_fallbackBuffer != null && _fallbackBuffer.Remaining > 0) throw new ArgumentException( SR.Argument_FallbackBufferNotEmpty, nameof(value)); _fallback = value; _fallbackBuffer = null; } } // Note: we don't test for threading here because async access to Encoders and Decoders // doesn't work anyway. public DecoderFallbackBuffer FallbackBuffer { get { if (_fallbackBuffer == null) { if (_fallback != null) _fallbackBuffer = _fallback.CreateFallbackBuffer(); else _fallbackBuffer = DecoderFallback.ReplacementFallback.CreateFallbackBuffer(); } return _fallbackBuffer; } } internal bool InternalHasFallbackBuffer { get { return _fallbackBuffer != null; } } // Reset the Decoder // // Normally if we call GetChars() and an error is thrown we don't change the state of the Decoder. This // would allow the caller to correct the error condition and try again (such as if they need a bigger buffer.) // // If the caller doesn't want to try again after GetChars() throws an error, then they need to call Reset(). // // Virtual implementation has to call GetChars with flush and a big enough buffer to clear a 0 byte string // We avoid GetMaxCharCount() because a) we can't call the base encoder and b) it might be really big. public virtual void Reset() { byte[] byteTemp = Array.Empty<byte>(); char[] charTemp = new char[GetCharCount(byteTemp, 0, 0, true)]; GetChars(byteTemp, 0, 0, charTemp, 0, true); _fallbackBuffer?.Reset(); } // Returns the number of characters the next call to GetChars will // produce if presented with the given range of bytes. The returned value // takes into account the state in which the decoder was left following the // last call to GetChars. The state of the decoder is not affected // by a call to this method. // public abstract int GetCharCount(byte[] bytes, int index, int count); public virtual int GetCharCount(byte[] bytes, int index, int count, bool flush) { return GetCharCount(bytes, index, count); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) [CLSCompliant(false)] public virtual unsafe int GetCharCount(byte* bytes, int count, bool flush) { // Validate input parameters if (bytes == null) throw new ArgumentNullException(nameof(bytes), SR.ArgumentNull_Array); if (count < 0) throw new ArgumentOutOfRangeException(nameof(count), SR.ArgumentOutOfRange_NeedNonNegNum); byte[] arrbyte = new byte[count]; int index; for (index = 0; index < count; index++) arrbyte[index] = bytes[index]; return GetCharCount(arrbyte, 0, count); } public virtual unsafe int GetCharCount(ReadOnlySpan<byte> bytes, bool flush) { fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) { return GetCharCount(bytesPtr, bytes.Length, flush); } } // Decodes a range of bytes in a byte array into a range of characters // in a character array. The method decodes byteCount bytes from // bytes starting at index byteIndex, storing the resulting // characters in chars starting at index charIndex. The // decoding takes into account the state in which the decoder was left // following the last call to this method. // // An exception occurs if the character array is not large enough to // hold the complete decoding of the bytes. The GetCharCount method // can be used to determine the exact number of characters that will be // produced for a given range of bytes. Alternatively, the // GetMaxCharCount method of the Encoding that produced this // decoder can be used to determine the maximum number of characters that // will be produced for a given number of bytes, regardless of the actual // byte values. // public abstract int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public virtual int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, bool flush) { return GetChars(bytes, byteIndex, byteCount, chars, charIndex); } // We expect this to be the workhorse for NLS Encodings, but for existing // ones we need a working (if slow) default implementation) // // WARNING WARNING WARNING // // WARNING: If this breaks it could be a security threat. Obviously we // call this internally, so you need to make sure that your pointers, counts // and indexes are correct when you call this method. // // In addition, we have internal code, which will be marked as "safe" calling // this code. However this code is dependent upon the implementation of an // external GetChars() method, which could be overridden by a third party and // the results of which cannot be guaranteed. We use that result to copy // the char[] to our char* output buffer. If the result count was wrong, we // could easily overflow our output buffer. Therefore we do an extra test // when we copy the buffer so that we don't overflow charCount either. [CLSCompliant(false)] public virtual unsafe int GetChars(byte* bytes, int byteCount, char* chars, int charCount, bool flush) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Get the byte array to convert byte[] arrByte = new byte[byteCount]; int index; for (index = 0; index < byteCount; index++) arrByte[index] = bytes[index]; // Get the char array to fill char[] arrChar = new char[charCount]; // Do the work int result = GetChars(arrByte, 0, byteCount, arrChar, 0, flush); Debug.Assert(result <= charCount, "Returned more chars than we have space for"); // Copy the char array // WARNING: We MUST make sure that we don't copy too many chars. We can't // rely on result because it could be a 3rd party implementation. We need // to make sure we never copy more than charCount chars no matter the value // of result if (result < charCount) charCount = result; // We check both result and charCount so that we don't accidentally overrun // our pointer buffer just because of an issue in GetChars for (index = 0; index < charCount; index++) chars[index] = arrChar[index]; return charCount; } public virtual unsafe int GetChars(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush) { fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) fixed (char* charsPtr = &chars.DangerousGetPinnableReference()) { return GetChars(bytesPtr, bytes.Length, charsPtr, chars.Length, flush); } } // This method is used when the output buffer might not be large enough. // It will decode until it runs out of bytes, and then it will return // true if it the entire input was converted. In either case it // will also return the number of converted bytes and output characters used. // It will only throw a buffer overflow exception if the entire lenght of chars[] is // too small to store the next char. (like 0 or maybe 1 or 4 for some encodings) // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) public virtual void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate parameters if (bytes == null || chars == null) throw new ArgumentNullException((bytes == null ? nameof(bytes) : nameof(chars)), SR.ArgumentNull_Array); if (byteIndex < 0 || byteCount < 0) throw new ArgumentOutOfRangeException((byteIndex < 0 ? nameof(byteIndex) : nameof(byteCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (charIndex < 0 || charCount < 0) throw new ArgumentOutOfRangeException((charIndex < 0 ? nameof(charIndex) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); if (bytes.Length - byteIndex < byteCount) throw new ArgumentOutOfRangeException(nameof(bytes), SR.ArgumentOutOfRange_IndexCountBuffer); if (chars.Length - charIndex < charCount) throw new ArgumentOutOfRangeException(nameof(chars), SR.ArgumentOutOfRange_IndexCountBuffer); bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, byteIndex, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, byteIndex, bytesUsed, chars, charIndex, flush); completed = (bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } // This is the version that uses *. // We're done processing this buffer only if completed returns true. // // Might consider checking Max...Count to avoid the extra counting step. // // Note that if all of the input bytes are not consumed, then we'll do a /2, which means // that its likely that we didn't consume as many bytes as we could have. For some // applications this could be slow. (Like trying to exactly fill an output buffer from a bigger stream) [CLSCompliant(false)] public virtual unsafe void Convert(byte* bytes, int byteCount, char* chars, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { // Validate input parameters if (chars == null || bytes == null) throw new ArgumentNullException(chars == null ? nameof(chars) : nameof(bytes), SR.ArgumentNull_Array); if (byteCount < 0 || charCount < 0) throw new ArgumentOutOfRangeException((byteCount < 0 ? nameof(byteCount) : nameof(charCount)), SR.ArgumentOutOfRange_NeedNonNegNum); // Get ready to do it bytesUsed = byteCount; // Its easy to do if it won't overrun our buffer. while (bytesUsed > 0) { if (GetCharCount(bytes, bytesUsed, flush) <= charCount) { charsUsed = GetChars(bytes, bytesUsed, chars, charCount, flush); completed = (bytesUsed == byteCount && (_fallbackBuffer == null || _fallbackBuffer.Remaining == 0)); return; } // Try again with 1/2 the count, won't flush then 'cause won't read it all flush = false; bytesUsed /= 2; } // Oops, we didn't have anything, we'll have to throw an overflow throw new ArgumentException(SR.Argument_ConversionOverflow); } public virtual unsafe void Convert(ReadOnlySpan<byte> bytes, Span<char> chars, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { fixed (byte* bytesPtr = &bytes.DangerousGetPinnableReference()) fixed (char* charsPtr = &chars.DangerousGetPinnableReference()) { Convert(bytesPtr, bytes.Length, charsPtr, chars.Length, flush, out bytesUsed, out charsUsed, out completed); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure; using Microsoft.Azure.Management.Automation; using Microsoft.Azure.Management.Automation.Models; namespace Microsoft.Azure.Management.Automation { public static partial class ModuleOperationsExtensions { /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create or update parameters for module. /// </param> /// <returns> /// The response model for the create or update module operation. /// </returns> public static ModuleCreateOrUpdateResponse CreateOrUpdate(this IModuleOperations operations, string resourceGroupName, string automationAccount, ModuleCreateOrUpdateParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The create or update parameters for module. /// </param> /// <returns> /// The response model for the create or update module operation. /// </returns> public static Task<ModuleCreateOrUpdateResponse> CreateOrUpdateAsync(this IModuleOperations operations, string resourceGroupName, string automationAccount, ModuleCreateOrUpdateParameters parameters) { return operations.CreateOrUpdateAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } /// <summary> /// Delete the module by name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static AzureOperationResponse Delete(this IModuleOperations operations, string resourceGroupName, string automationAccount, string moduleName) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).DeleteAsync(resourceGroupName, automationAccount, moduleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Delete the module by name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public static Task<AzureOperationResponse> DeleteAsync(this IModuleOperations operations, string resourceGroupName, string automationAccount, string moduleName) { return operations.DeleteAsync(resourceGroupName, automationAccount, moduleName, CancellationToken.None); } /// <summary> /// Retrieve the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static ModuleGetResponse Get(this IModuleOperations operations, string resourceGroupName, string automationAccount, string moduleName) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).GetAsync(resourceGroupName, automationAccount, moduleName); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='moduleName'> /// Required. The module name. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static Task<ModuleGetResponse> GetAsync(this IModuleOperations operations, string resourceGroupName, string automationAccount, string moduleName) { return operations.GetAsync(resourceGroupName, automationAccount, moduleName, CancellationToken.None); } /// <summary> /// Retrieve a list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static ModuleListResponse List(this IModuleOperations operations, string resourceGroupName, string automationAccount) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).ListAsync(resourceGroupName, automationAccount); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve a list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static Task<ModuleListResponse> ListAsync(this IModuleOperations operations, string resourceGroupName, string automationAccount) { return operations.ListAsync(resourceGroupName, automationAccount, CancellationToken.None); } /// <summary> /// Retrieve next list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static ModuleListResponse ListNext(this IModuleOperations operations, string nextLink) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).ListNextAsync(nextLink); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Retrieve next list of modules. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='nextLink'> /// Required. The link to retrieve next set of items. /// </param> /// <returns> /// The response model for the list module operation. /// </returns> public static Task<ModuleListResponse> ListNextAsync(this IModuleOperations operations, string nextLink) { return operations.ListNextAsync(nextLink, CancellationToken.None); } /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The patch parameters for module. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static ModuleGetResponse Patch(this IModuleOperations operations, string resourceGroupName, string automationAccount, ModulePatchParameters parameters) { return Task.Factory.StartNew((object s) => { return ((IModuleOperations)s).PatchAsync(resourceGroupName, automationAccount, parameters); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Create the module identified by module name. (see /// http://aka.ms/azureautomationsdk/moduleoperations for more /// information) /// </summary> /// <param name='operations'> /// Reference to the /// Microsoft.Azure.Management.Automation.IModuleOperations. /// </param> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='automationAccount'> /// Required. The automation account name. /// </param> /// <param name='parameters'> /// Required. The patch parameters for module. /// </param> /// <returns> /// The response model for the get module operation. /// </returns> public static Task<ModuleGetResponse> PatchAsync(this IModuleOperations operations, string resourceGroupName, string automationAccount, ModulePatchParameters parameters) { return operations.PatchAsync(resourceGroupName, automationAccount, parameters, CancellationToken.None); } } }
// Copyright (C) 2014 dot42 // // Original filename: corlib.cs // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Reflection; using System.Runtime.CompilerServices; [assembly: Dot42.FrameworkLibrary] [assembly: AssemblyFlags(AssemblyNameFlags.Retargetable)] [assembly: AssemblyTitle("mscorlib.dll")] [assembly: AssemblyDescription("mscorlib.dll")] [assembly: AssemblyDefaultAlias("mscorlib.dll")] [assembly: TypeForwardedTo(typeof(System.Action))] [assembly: TypeForwardedTo(typeof(System.Action<>))] [assembly: TypeForwardedTo(typeof(System.Action<,>))] [assembly: TypeForwardedTo(typeof(System.Action<,,>))] [assembly: TypeForwardedTo(typeof(System.Action<,,,>))] [assembly: TypeForwardedTo(typeof(System.Action<,,,,>))] [assembly: TypeForwardedTo(typeof(System.Action<,,,,,>))] [assembly: TypeForwardedTo(typeof(System.Action<,,,,,,>))] [assembly: TypeForwardedTo(typeof(System.Action<,,,,,,,>))] [assembly: TypeForwardedTo(typeof(System.Activator))] [assembly: TypeForwardedTo(typeof(System.AggregateException))] [assembly: TypeForwardedTo(typeof(System.ApplicationException))] [assembly: TypeForwardedTo(typeof(System.ArgumentException))] [assembly: TypeForwardedTo(typeof(System.ArgumentNullException))] [assembly: TypeForwardedTo(typeof(System.ArgumentOutOfRangeException))] [assembly: TypeForwardedTo(typeof(System.ArithmeticException))] [assembly: TypeForwardedTo(typeof(System.Array))] [assembly: TypeForwardedTo(typeof(System.ArrayTypeMismatchException))] [assembly: TypeForwardedTo(typeof(System.AsyncCallback))] [assembly: TypeForwardedTo(typeof(System.Attribute))] [assembly: TypeForwardedTo(typeof(System.AttributeTargets))] [assembly: TypeForwardedTo(typeof(System.AttributeUsageAttribute))] [assembly: TypeForwardedTo(typeof(System.Base64FormattingOptions))] [assembly: TypeForwardedTo(typeof(System.BitConverter))] [assembly: TypeForwardedTo(typeof(System.Boolean))] [assembly: TypeForwardedTo(typeof(System.Buffer))] [assembly: TypeForwardedTo(typeof(System.Byte))] [assembly: TypeForwardedTo(typeof(System.Char))] [assembly: TypeForwardedTo(typeof(System.CLSCompliantAttribute))] [assembly: TypeForwardedTo(typeof(System.Console))] [assembly: TypeForwardedTo(typeof(System.Convert))] [assembly: TypeForwardedTo(typeof(System.DateTime))] [assembly: TypeForwardedTo(typeof(System.DateTimeKind))] [assembly: TypeForwardedTo(typeof(System.DayOfWeek))] [assembly: TypeForwardedTo(typeof(System.DBNull))] [assembly: TypeForwardedTo(typeof(System.Decimal))] [assembly: TypeForwardedTo(typeof(System.Delegate))] [assembly: TypeForwardedTo(typeof(System.DivideByZeroException))] [assembly: TypeForwardedTo(typeof(System.Double))] [assembly: TypeForwardedTo(typeof(System.Enum))] [assembly: TypeForwardedTo(typeof(System.Environment))] [assembly: TypeForwardedTo(typeof(System.EventArgs))] [assembly: TypeForwardedTo(typeof(System.EventHandler))] [assembly: TypeForwardedTo(typeof(System.EventHandler<>))] [assembly: TypeForwardedTo(typeof(System.Exception))] [assembly: TypeForwardedTo(typeof(System.FlagsAttribute))] [assembly: TypeForwardedTo(typeof(System.FormatException))] [assembly: TypeForwardedTo(typeof(System.Func<>))] [assembly: TypeForwardedTo(typeof(System.Func<,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,,,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,,,,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,,,,,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,,,,,,>))] [assembly: TypeForwardedTo(typeof(System.Func<,,,,,,,,>))] [assembly: TypeForwardedTo(typeof(System.GC))] [assembly: TypeForwardedTo(typeof(System.Guid))] [assembly: TypeForwardedTo(typeof(System.IAsyncResult))] [assembly: TypeForwardedTo(typeof(System.ICloneable))] [assembly: TypeForwardedTo(typeof(System.IComparable))] [assembly: TypeForwardedTo(typeof(System.IComparable<>))] [assembly: TypeForwardedTo(typeof(System.IConvertible))] [assembly: TypeForwardedTo(typeof(System.ICustomFormatter))] [assembly: TypeForwardedTo(typeof(System.IDisposable))] [assembly: TypeForwardedTo(typeof(System.IEquatable<>))] [assembly: TypeForwardedTo(typeof(System.IFormatProvider))] [assembly: TypeForwardedTo(typeof(System.IFormattable))] [assembly: TypeForwardedTo(typeof(System.Int16))] [assembly: TypeForwardedTo(typeof(System.Int32))] [assembly: TypeForwardedTo(typeof(System.Int64))] [assembly: TypeForwardedTo(typeof(System.IntPtr))] [assembly: TypeForwardedTo(typeof(System.IndexOutOfRangeException))] [assembly: TypeForwardedTo(typeof(System.InvalidCastException))] [assembly: TypeForwardedTo(typeof(System.InvalidOperationException))] [assembly: TypeForwardedTo(typeof(System.IServiceProvider))] [assembly: TypeForwardedTo(typeof(System.MarshalByRefObject))] [assembly: TypeForwardedTo(typeof(System.Math))] [assembly: TypeForwardedTo(typeof(System.MidpointRounding))] [assembly: TypeForwardedTo(typeof(System.MissingFieldException))] [assembly: TypeForwardedTo(typeof(System.MissingMethodException))] [assembly: TypeForwardedTo(typeof(System.MulticastDelegate))] [assembly: TypeForwardedTo(typeof(System.NonSerializedAttribute))] [assembly: TypeForwardedTo(typeof(System.NotImplementedException))] [assembly: TypeForwardedTo(typeof(System.NotSupportedException))] [assembly: TypeForwardedTo(typeof(System.Nullable))] [assembly: TypeForwardedTo(typeof(System.Nullable<>))] [assembly: TypeForwardedTo(typeof(System.NullReferenceException))] [assembly: TypeForwardedTo(typeof(System.Object))] [assembly: TypeForwardedTo(typeof(System.ObjectDisposedException))] [assembly: TypeForwardedTo(typeof(System.ObsoleteAttribute))] [assembly: TypeForwardedTo(typeof(System.OperationCanceledException))] [assembly: TypeForwardedTo(typeof(System.OutOfMemoryException))] [assembly: TypeForwardedTo(typeof(System.OverflowException))] [assembly: TypeForwardedTo(typeof(System.ParamArrayAttribute))] [assembly: TypeForwardedTo(typeof(System.PlatformID))] [assembly: TypeForwardedTo(typeof(System.Predicate<>))] [assembly: TypeForwardedTo(typeof(System.Random))] [assembly: TypeForwardedTo(typeof(System.RankException))] [assembly: TypeForwardedTo(typeof(System.RuntimeArgumentHandle))] [assembly: TypeForwardedTo(typeof(System.RuntimeFieldHandle))] [assembly: TypeForwardedTo(typeof(System.RuntimeMethodHandle))] [assembly: TypeForwardedTo(typeof(System.RuntimeTypeHandle))] [assembly: TypeForwardedTo(typeof(System.SByte))] [assembly: TypeForwardedTo(typeof(System.SerializableAttribute))] [assembly: TypeForwardedTo(typeof(System.Single))] [assembly: TypeForwardedTo(typeof(System.StackOverflowException))] [assembly: TypeForwardedTo(typeof(System.String))] [assembly: TypeForwardedTo(typeof(System.StringComparison))] [assembly: TypeForwardedTo(typeof(System.StringSplitOptions))] [assembly: TypeForwardedTo(typeof(System.SystemException))] [assembly: TypeForwardedTo(typeof(System.ThreadStaticAttribute))] [assembly: TypeForwardedTo(typeof(System.TimeSpan))] [assembly: TypeForwardedTo(typeof(System.Type))] [assembly: TypeForwardedTo(typeof(System.TypeCode))] [assembly: TypeForwardedTo(typeof(System.UInt16))] [assembly: TypeForwardedTo(typeof(System.UInt32))] [assembly: TypeForwardedTo(typeof(System.UInt64))] [assembly: TypeForwardedTo(typeof(System.UIntPtr))] [assembly: TypeForwardedTo(typeof(System.UnauthorizedAccessException))] [assembly: TypeForwardedTo(typeof(System.ValueType))] [assembly: TypeForwardedTo(typeof(System.Version))] [assembly: TypeForwardedTo(typeof(System.WeakReference))] [assembly: TypeForwardedTo(typeof(void))] [assembly: TypeForwardedTo(typeof(System.Collections.ArrayList))] [assembly: TypeForwardedTo(typeof(System.Collections.Comparer))] [assembly: TypeForwardedTo(typeof(System.Collections.DictionaryEntry))] [assembly: TypeForwardedTo(typeof(System.Collections.Hashtable))] [assembly: TypeForwardedTo(typeof(System.Collections.ICollection))] [assembly: TypeForwardedTo(typeof(System.Collections.IComparer))] [assembly: TypeForwardedTo(typeof(System.Collections.IDictionary))] [assembly: TypeForwardedTo(typeof(System.Collections.IDictionaryEnumerator))] [assembly: TypeForwardedTo(typeof(System.Collections.IEnumerable))] [assembly: TypeForwardedTo(typeof(System.Collections.IEnumerator))] [assembly: TypeForwardedTo(typeof(System.Collections.IEqualityComparer))] [assembly: TypeForwardedTo(typeof(System.Collections.IHashCodeProvider))] [assembly: TypeForwardedTo(typeof(System.Collections.IList))] [assembly: TypeForwardedTo(typeof(System.Collections.SortedList))] [assembly: TypeForwardedTo(typeof(System.Collections.Stack))] [assembly: TypeForwardedTo(typeof(System.Collections.Concurrent.ConcurrentDictionary<,>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.Comparer<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.Dictionary<,>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.EqualityComparer<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.ICollection<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IComparer<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IEnumerable<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IEnumerator<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IEqualityComparer<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IList<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.IReadOnlyList<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.ISet<>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.KeyNotFoundException))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.KeyValuePair<,>))] [assembly: TypeForwardedTo(typeof(System.Collections.Generic.List<>))] [assembly: TypeForwardedTo(typeof(System.Collections.ObjectModel.ReadOnlyCollection<>))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.ConditionalAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggableAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerBrowsableAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerBrowsableState))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerDisplayAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerHiddenAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerNonUserCodeAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerStepperBoundaryAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerStepThroughAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerTypeProxyAttribute))] [assembly: TypeForwardedTo(typeof(System.Diagnostics.DebuggerVisualizerAttribute))] [assembly: TypeForwardedTo(typeof(System.Globalization.CultureInfo))] [assembly: TypeForwardedTo(typeof(System.Globalization.DateTimeFormatInfo))] [assembly: TypeForwardedTo(typeof(System.Globalization.NumberFormatInfo))] [assembly: TypeForwardedTo(typeof(System.Globalization.NumberStyles))] [assembly: TypeForwardedTo(typeof(System.IO.BinaryReader))] [assembly: TypeForwardedTo(typeof(System.IO.BinaryWriter))] [assembly: TypeForwardedTo(typeof(System.IO.BufferedStream))] [assembly: TypeForwardedTo(typeof(System.IO.Directory))] [assembly: TypeForwardedTo(typeof(System.IO.DirectoryInfo))] [assembly: TypeForwardedTo(typeof(System.IO.DirectoryNotFoundException))] [assembly: TypeForwardedTo(typeof(System.IO.EndOfStreamException))] [assembly: TypeForwardedTo(typeof(System.IO.File))] [assembly: TypeForwardedTo(typeof(System.IO.FileAccess))] [assembly: TypeForwardedTo(typeof(System.IO.FileInfo))] [assembly: TypeForwardedTo(typeof(System.IO.FileNotFoundException))] [assembly: TypeForwardedTo(typeof(System.IO.FileMode))] [assembly: TypeForwardedTo(typeof(System.IO.FileShare))] [assembly: TypeForwardedTo(typeof(System.IO.FileStream))] [assembly: TypeForwardedTo(typeof(System.IO.FileSystemInfo))] [assembly: TypeForwardedTo(typeof(System.IO.IOException))] [assembly: TypeForwardedTo(typeof(System.IO.MemoryStream))] [assembly: TypeForwardedTo(typeof(System.IO.Path))] [assembly: TypeForwardedTo(typeof(System.IO.SeekOrigin))] [assembly: TypeForwardedTo(typeof(System.IO.Stream))] [assembly: TypeForwardedTo(typeof(System.IO.StreamReader))] [assembly: TypeForwardedTo(typeof(System.IO.StreamWriter))] [assembly: TypeForwardedTo(typeof(System.IO.StringWriter))] [assembly: TypeForwardedTo(typeof(System.IO.TextReader))] [assembly: TypeForwardedTo(typeof(System.IO.TextWriter))] [assembly: TypeForwardedTo(typeof(System.Reflection.Assembly))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyCompanyAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyConfigurationAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyCopyrightAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyCultureAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyDefaultAliasAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyDelaySignAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyDescriptionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyFileVersionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyFlagsAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyInformationalVersionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyKeyFileAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyKeyNameAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyNameFlags))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyProductAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyTitleAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyTrademarkAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.AssemblyVersionAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.BindingFlags))] [assembly: TypeForwardedTo(typeof(System.Reflection.ConstructorInfo))] [assembly: TypeForwardedTo(typeof(System.Reflection.DefaultMemberAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.FieldInfo))] [assembly: TypeForwardedTo(typeof(System.Reflection.ICustomAttributeProvider))] [assembly: TypeForwardedTo(typeof(System.Reflection.MemberInfo))] [assembly: TypeForwardedTo(typeof(System.Reflection.MethodInfo))] [assembly: TypeForwardedTo(typeof(System.Reflection.ObfuscateAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.ObfuscationAttribute))] [assembly: TypeForwardedTo(typeof(System.Reflection.PropertyInfo))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncStateMachineAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncTaskMethodBuilder<>))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.AsyncVoidMethodBuilder))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilationRelaxations))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilationRelaxationsAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.CompilerGeneratedAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConfiguredTaskAwaitable))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ConfiguredTaskAwaitable<>))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.DecimalConstantAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ExtensionAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IAsyncStateMachine))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ICriticalNotifyCompletion))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IndexerNameAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.INotifyCompletion))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.InternalsVisibleToAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsBoxed))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsByValue))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsConst))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsCopyConstructed))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsExplicitlyDereferenced))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsImplicitlyDereferenced))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsJitIntrinsic))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsLong))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsPinned))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsSignUnspecifiedByte))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsUdtReturn))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.IsVolatile))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.MethodCodeType))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.MethodImplAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.MethodImplOptions))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.ReferenceAssemblyAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.RuntimeCompatibilityAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.RuntimeHelpers))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.StateMachineAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.TaskAwaiter))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.TaskAwaiter<>))] [assembly: TypeForwardedTo(typeof(System.Runtime.CompilerServices.TypeForwardedToAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.ConstrainedExecution.Cer))] [assembly: TypeForwardedTo(typeof(System.Runtime.ConstrainedExecution.Consistency))] [assembly: TypeForwardedTo(typeof(System.Runtime.ConstrainedExecution.ReliabilityContractAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.ExceptionServices.ExceptionDispatchInfo))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.CallingConvention))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.CharSet))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.ComVisibleAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.DllImportAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.FieldOffsetAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.GuidAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.InAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.LayoutKind))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.OutAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.InteropServices.StructLayoutAttribute))] [assembly: TypeForwardedTo(typeof(System.Runtime.Serialization.IObjectReference))] [assembly: TypeForwardedTo(typeof(System.Runtime.Serialization.ISerializable))] [assembly: TypeForwardedTo(typeof(System.Runtime.Serialization.SerializationException))] [assembly: TypeForwardedTo(typeof(System.Runtime.Serialization.SerializationInfo))] [assembly: TypeForwardedTo(typeof(System.Runtime.Serialization.StreamingContext))] [assembly: TypeForwardedTo(typeof(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter))] [assembly: TypeForwardedTo(typeof(System.Runtime.Versioning.TargetFrameworkAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.AllowPartiallyTrustedCallersAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.PartialTrustVisibilityLevel))] [assembly: TypeForwardedTo(typeof(System.Security.SecurityException))] [assembly: TypeForwardedTo(typeof(System.Security.SecuritySafeCriticalAttribute))] [assembly: TypeForwardedTo(typeof(System.Security.Cryptography.ICryptoTransform))] [assembly: TypeForwardedTo(typeof(System.Security.Principal.TokenImpersonationLevel))] [assembly: TypeForwardedTo(typeof(System.Text.ASCIIEncoding))] [assembly: TypeForwardedTo(typeof(System.Text.Decoder))] [assembly: TypeForwardedTo(typeof(System.Text.DecoderFallbackException))] [assembly: TypeForwardedTo(typeof(System.Text.Encoder))] [assembly: TypeForwardedTo(typeof(System.Text.Encoding))] [assembly: TypeForwardedTo(typeof(System.Text.EncoderFallbackException))] [assembly: TypeForwardedTo(typeof(System.Text.StringBuilder))] [assembly: TypeForwardedTo(typeof(System.Text.UnicodeEncoding))] [assembly: TypeForwardedTo(typeof(System.Text.UTF8Encoding))] [assembly: TypeForwardedTo(typeof(System.Text.UTF32Encoding))] [assembly: TypeForwardedTo(typeof(System.Threading.CancellationToken))] [assembly: TypeForwardedTo(typeof(System.Threading.CancellationTokenRegistration))] [assembly: TypeForwardedTo(typeof(System.Threading.CancellationTokenSource))] [assembly: TypeForwardedTo(typeof(System.Threading.EventResetMode))] [assembly: TypeForwardedTo(typeof(System.Threading.EventWaitHandle))] [assembly: TypeForwardedTo(typeof(System.Threading.ManualResetEvent))] [assembly: TypeForwardedTo(typeof(System.Threading.Monitor))] [assembly: TypeForwardedTo(typeof(System.Threading.ParameterizedThreadStart))] [assembly: TypeForwardedTo(typeof(System.Threading.SendOrPostCallback))] [assembly: TypeForwardedTo(typeof(System.Threading.SynchronizationContext))] [assembly: TypeForwardedTo(typeof(System.Threading.Thread))] [assembly: TypeForwardedTo(typeof(System.Threading.ThreadStart))] [assembly: TypeForwardedTo(typeof(System.Threading.Timeout))] [assembly: TypeForwardedTo(typeof(System.Threading.WaitHandle))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.Task))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.Task<>))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskCanceledException))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskCompletionSource<>))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskContinuationOptions))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskCreationOptions))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskFactory))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskFactory<>))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskScheduler))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskSchedulerException))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.TaskStatus))] [assembly: TypeForwardedTo(typeof(System.Threading.Tasks.UnobservedTaskExceptionEventArgs))]
/* * Copyright (c) 2008, openmetaverse.org * 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. * - Neither the name of the openmetaverse.org nor the names * of its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ using System; using System.IO; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using OpenMetaverse.Assets; using OpenMetaverse.StructuredData; // The common elements shared between rendering plugins are defined here namespace OpenMetaverse.Rendering { #region Enums public enum FaceType : ushort { PathBegin = 0x1 << 0, PathEnd = 0x1 << 1, InnerSide = 0x1 << 2, ProfileBegin = 0x1 << 3, ProfileEnd = 0x1 << 4, OuterSide0 = 0x1 << 5, OuterSide1 = 0x1 << 6, OuterSide2 = 0x1 << 7, OuterSide3 = 0x1 << 8 } [Flags] public enum FaceMask { Single = 0x0001, Cap = 0x0002, End = 0x0004, Side = 0x0008, Inner = 0x0010, Outer = 0x0020, Hollow = 0x0040, Open = 0x0080, Flat = 0x0100, Top = 0x0200, Bottom = 0x0400 } public enum DetailLevel { Low = 0, Medium = 1, High = 2, Highest = 3 } #endregion Enums #region Structs [StructLayout(LayoutKind.Explicit)] public struct Vertex { [FieldOffset(0)] public Vector3 Position; [FieldOffset(12)] public Vector3 Normal; [FieldOffset(24)] public Vector2 TexCoord; public override string ToString() { return String.Format("P: {0} N: {1} T: {2}", Position, Normal, TexCoord); } } public struct ProfileFace { public int Index; public int Count; public float ScaleU; public bool Cap; public bool Flat; public FaceType Type; public override string ToString() { return Type.ToString(); } }; public struct Profile { public float MinX; public float MaxX; public bool Open; public bool Concave; public int TotalOutsidePoints; public List<Vector3> Positions; public List<ProfileFace> Faces; } public struct PathPoint { public Vector3 Position; public Vector2 Scale; public Quaternion Rotation; public float TexT; } public struct Path { public List<PathPoint> Points; public bool Open; } public struct Face { // Only used for Inner/Outer faces public int BeginS; public int BeginT; public int NumS; public int NumT; public int ID; public Vector3 Center; public Vector3 MinExtent; public Vector3 MaxExtent; public List<Vertex> Vertices; public List<ushort> Indices; public List<int> Edge; public FaceMask Mask; public Primitive.TextureEntryFace TextureFace; public object UserData; public override string ToString() { return Mask.ToString(); } } #endregion Structs #region Exceptions public class RenderingException : Exception { public RenderingException(string message) : base(message) { } public RenderingException(string message, Exception innerException) : base(message, innerException) { } } #endregion Exceptions #region Mesh Classes public class Mesh { public Primitive Prim; public Path Path; public Profile Profile; public override string ToString() { if (Prim.Properties != null && !String.IsNullOrEmpty(Prim.Properties.Name)) { return Prim.Properties.Name; } else { return String.Format("{0} ({1})", Prim.LocalID, Prim.PrimData); } } } /// <summary> /// Contains all mesh faces that belong to a prim /// </summary> public class FacetedMesh : Mesh { /// <summary>List of primitive faces</summary> public List<Face> Faces; /// <summary> /// Decodes mesh asset into FacetedMesh /// </summary> /// <param name="prim">Mesh primitive</param> /// <param name="meshAsset">Asset retrieved from the asset server</param> /// <param name="LOD">Level of detail</param> /// <param name="mesh">Resulting decoded FacetedMesh</param> /// <returns>True if mesh asset decoding was successful</returns> public static bool TryDecodeFromAsset(Primitive prim, AssetMesh meshAsset, DetailLevel LOD, out FacetedMesh mesh) { mesh = null; try { if (!meshAsset.Decode()) { return false; } OSDMap MeshData = meshAsset.MeshData; mesh = new FacetedMesh(); mesh.Faces = new List<Face>(); mesh.Prim = prim; mesh.Profile.Faces = new List<ProfileFace>(); mesh.Profile.Positions = new List<Vector3>(); mesh.Path.Points = new List<PathPoint>(); OSD facesOSD = null; switch (LOD) { default: case DetailLevel.Highest: facesOSD = MeshData["high_lod"]; break; case DetailLevel.High: facesOSD = MeshData["medium_lod"]; break; case DetailLevel.Medium: facesOSD = MeshData["low_lod"]; break; case DetailLevel.Low: facesOSD = MeshData["lowest_lod"]; break; } if (facesOSD == null || !(facesOSD is OSDArray)) { return false; } OSDArray decodedMeshOsdArray = (OSDArray)facesOSD; for (int faceNr = 0; faceNr < decodedMeshOsdArray.Count; faceNr++) { OSD subMeshOsd = decodedMeshOsdArray[faceNr]; // Decode each individual face if (subMeshOsd is OSDMap) { Face oface = new Face(); oface.ID = faceNr; oface.Vertices = new List<Vertex>(); oface.Indices = new List<ushort>(); oface.TextureFace = prim.Textures.GetFace((uint)faceNr); OSDMap subMeshMap = (OSDMap)subMeshOsd; Vector3 posMax; Vector3 posMin; // If PositionDomain is not specified, the default is from -0.5 to 0.5 if (subMeshMap.ContainsKey("PositionDomain")) { posMax = ((OSDMap)subMeshMap["PositionDomain"])["Max"]; posMin = ((OSDMap)subMeshMap["PositionDomain"])["Min"]; } else { posMax = new Vector3(0.5f, 0.5f, 0.5f); posMin = new Vector3(-0.5f, -0.5f, -0.5f); } // Vertex positions byte[] posBytes = subMeshMap["Position"]; // Normals byte[] norBytes = null; if (subMeshMap.ContainsKey("Normal")) { norBytes = subMeshMap["Normal"]; } // UV texture map Vector2 texPosMax = Vector2.Zero; Vector2 texPosMin = Vector2.Zero; byte[] texBytes = null; if (subMeshMap.ContainsKey("TexCoord0")) { texBytes = subMeshMap["TexCoord0"]; texPosMax = ((OSDMap)subMeshMap["TexCoord0Domain"])["Max"]; texPosMin = ((OSDMap)subMeshMap["TexCoord0Domain"])["Min"]; } // Extract the vertex position data // If present normals and texture coordinates too for (int i = 0; i < posBytes.Length; i += 6) { ushort uX = Utils.BytesToUInt16(posBytes, i); ushort uY = Utils.BytesToUInt16(posBytes, i + 2); ushort uZ = Utils.BytesToUInt16(posBytes, i + 4); Vertex vx = new Vertex(); vx.Position = new Vector3( Utils.UInt16ToFloat(uX, posMin.X, posMax.X), Utils.UInt16ToFloat(uY, posMin.Y, posMax.Y), Utils.UInt16ToFloat(uZ, posMin.Z, posMax.Z)); if (norBytes != null && norBytes.Length >= i + 4) { ushort nX = Utils.BytesToUInt16(norBytes, i); ushort nY = Utils.BytesToUInt16(norBytes, i + 2); ushort nZ = Utils.BytesToUInt16(norBytes, i + 4); vx.Normal = new Vector3( Utils.UInt16ToFloat(nX, posMin.X, posMax.X), Utils.UInt16ToFloat(nY, posMin.Y, posMax.Y), Utils.UInt16ToFloat(nZ, posMin.Z, posMax.Z)); } var vertexIndexOffset = oface.Vertices.Count * 4; if (texBytes != null && texBytes.Length >= vertexIndexOffset + 4) { ushort tX = Utils.BytesToUInt16(texBytes, vertexIndexOffset); ushort tY = Utils.BytesToUInt16(texBytes, vertexIndexOffset + 2); vx.TexCoord = new Vector2( Utils.UInt16ToFloat(tX, texPosMin.X, texPosMax.X), Utils.UInt16ToFloat(tY, texPosMin.Y, texPosMax.Y)); } oface.Vertices.Add(vx); } byte[] triangleBytes = subMeshMap["TriangleList"]; for (int i = 0; i < triangleBytes.Length; i += 6) { ushort v1 = (ushort)(Utils.BytesToUInt16(triangleBytes, i)); oface.Indices.Add(v1); ushort v2 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 2)); oface.Indices.Add(v2); ushort v3 = (ushort)(Utils.BytesToUInt16(triangleBytes, i + 4)); oface.Indices.Add(v3); } mesh.Faces.Add(oface); } } } catch (Exception ex) { Logger.Log("Failed to decode mesh asset: " + ex.Message, Helpers.LogLevel.Warning); return false; } return true; } } public class SimpleMesh : Mesh { public List<Vertex> Vertices; public List<ushort> Indices; public SimpleMesh() { } public SimpleMesh(SimpleMesh mesh) { this.Indices = new List<ushort>(mesh.Indices); this.Path.Open = mesh.Path.Open; this.Path.Points = new List<PathPoint>(mesh.Path.Points); this.Prim = mesh.Prim; this.Profile.Concave = mesh.Profile.Concave; this.Profile.Faces = new List<ProfileFace>(mesh.Profile.Faces); this.Profile.MaxX = mesh.Profile.MaxX; this.Profile.MinX = mesh.Profile.MinX; this.Profile.Open = mesh.Profile.Open; this.Profile.Positions = new List<Vector3>(mesh.Profile.Positions); this.Profile.TotalOutsidePoints = mesh.Profile.TotalOutsidePoints; this.Vertices = new List<Vertex>(mesh.Vertices); } } #endregion Mesh Classes #region Plugin Loading public static class RenderingLoader { public static List<string> ListRenderers(string path) { List<string> plugins = new List<string>(); string[] files = Directory.GetFiles(path, "OpenMetaverse.Rendering.*.dll"); foreach (string f in files) { try { Assembly a = Assembly.LoadFrom(f); System.Type[] types = a.GetTypes(); foreach (System.Type type in types) { if (type.GetInterface("IRendering") != null) { if (type.GetCustomAttributes(typeof(RendererNameAttribute), false).Length == 1) { plugins.Add(f); } else { Logger.Log("Rendering plugin does not support the [RendererName] attribute: " + f, Helpers.LogLevel.Warning); } break; } } } catch (Exception e) { Logger.Log(String.Format("Unrecognized rendering plugin {0}: {1}", f, e.Message), Helpers.LogLevel.Warning, e); } } return plugins; } public static IRendering LoadRenderer(string filename) { try { Assembly a = Assembly.LoadFrom(filename); System.Type[] types = a.GetTypes(); foreach (System.Type type in types) { if (type.GetInterface("IRendering") != null) { if (type.GetCustomAttributes(typeof(RendererNameAttribute), false).Length == 1) { return (IRendering)Activator.CreateInstance(type); } else { throw new RenderingException( "Rendering plugin does not support the [RendererName] attribute"); } } } throw new RenderingException( "Rendering plugin does not support the IRendering interface"); } catch (Exception e) { throw new RenderingException("Failed loading rendering plugin: " + e.Message, e); } } } #endregion Plugin Loading }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; /// <summary> /// This class holds a heat value for each cell in your map; /// critters can then move towards the hotter cells. This uses /// a spare storage strategy, so you can set any cell's value and /// not sweat the memory wastage. /// </summary> public sealed class Heatmap : LocationMap<Heatmap.Slot> { public Heatmap() { this.name = ""; } public Heatmap(IEnumerable<KeyValuePair<Location, Slot>> source) : base(source) { this.name = ""; } /// <summary> /// This name has no effect on heatmap behavior, but /// can be used to idenitfy it. /// </summary> public string name { get; set; } public int GetSourceInfoCount() { var buffer = new List<SourceInfo>(); foreach (var pair in this) { SourceInfo si = pair.Value.source; if (si != null) { buffer.RemoveAll(s => s == si); buffer.Add(si); } } return buffer.Count; } public int GetDistinctSourceInfoCount() { var buffer = new HashSet<SourceInfo>(); foreach (var pair in this) { SourceInfo si = pair.Value.source; if (si != null) buffer.Add(si); } return buffer.Count; } /// <summary> /// Picks the best move from the candidates given; that is, it picks /// the cell with the largest heat value. If a tie for hottest cell is /// found, this picks one of the best randomly. This method will not /// pick a location whose heat is 0. /// /// This method returns false if all candiates have a heat of 0, or if there /// are no candidates at all. Otherwise, it places the result in 'picked' and returns true. /// </summary> public bool TryPickMove(IEnumerable<Location> candidates, out Location picked) { IEnumerable<Location> moves = (from d in candidates let heat = this[d].heat where heat != 0 group d by heat into g orderby g.Key descending select g).FirstOrDefault(); if (moves != null) { int index = UnityEngine.Random.Range(0, moves.Count()); picked = moves.ElementAt(index); return true; } else { picked = new Location(); return false; } } /// <summary> /// This returns a crude string representation of the heatmap content; /// this is not very good or fast and should be used for debugging only. /// </summary> public override string ToString() { var byMap = Locations().GroupBy(l => l.mapIndex); var b = new StringBuilder(); foreach (var grp in byMap) { b.AppendLine("Map #: " + grp.Key); int minX = grp.Min(loc => loc.x); int minY = grp.Min(loc => loc.y); int maxX = grp.Max(loc => loc.x); int maxY = grp.Max(loc => loc.y); for (int y = minY; y <= maxY; ++y) { for (int x = minX; x <= maxX; ++x) { int heat = this[new Location(x, y, grp.Key)].heat; int reducedHeat = heat == int.MinValue ? 0xFF : Math.Abs(heat) >> 23; b.AppendFormat("{0:X2}", reducedHeat); } b.AppendLine(); } } return b.ToString().Trim(); } #region Heat and Cool /// <summary> /// TrimExcess() removes blocks from the heatmap that /// contain only 0 heat values. /// </summary> public void TrimExcess() { RemoveBlocksWhere(delegate (Slot[] slots) { foreach (Slot slot in slots) if (slot.heat != 0) return false; return true; }); } /// <summary> /// This method reduces every value by 'amount', but won't flip the sign /// of any value- it stops at 0. Cells that contain 0 will not be changed. /// /// This method updates the heatmap in place. /// </summary> public void Reduce(int amount = 1) { ForEachBlock(delegate (Location upperLeft, Slot[] slots) { for (int i = 0; i < slots.Length; ++i) if (slots[i].heat != 0) slots[i] = slots[i].ToReduced(amount); }); } /// <summary> /// This delegate type is used to for the function that determines /// which cells are 'next to' a location; we spread head into these /// cells. /// /// As an optimization, this function places its results in a collection /// you provide; we can then reuse this collection efficiently and avoid /// allocations. /// </summary> public delegate void AdjacencySelector(Location where, ICollection<Location> adjacentLocations); /// <summary> /// This returns a heatmap that has had its heat values propagated; /// each cell in the new heatmap has a value that is the maximum of /// its old value, and one less than the values of the adjacent cells. /// /// We can't easily do this in place, so this returns a new heatmap that /// has been updated. /// /// You provide a delegate that provides the locaitons 'adjacent' to /// any given position; we call this to figure out where to spread heat to. /// /// As an optimization, you can return a shared buffer from this call; /// we will not hold into the array or use it again after making a second /// call to 'adjacency'. The the vast majority of locaitons have 4 /// neighbors, but occasional 'door' cells have more. /// /// Cells like walls may be omitted from the adjacency result; we return /// an ArraySegment so the buffer can still be shared. /// /// You also provide a delegate that indicates which cells are passable; /// impassible cells don't get heated, which can block the spread of /// heat through the map. This lets us skep locations returned by /// 'adjacency' without needing to allocate a smaller array. /// </summary> public void Heat(AdjacencySelector adjacency) { var heater = Heater.Create(); heater.Heat(this, adjacency); heater.Recycle(); } /// <summary> /// This method applies multiple rounds of heat; as many as 'repeat' indicated. /// this returns a new heatmap containing the result. /// </summary> public void Heat(int repeats, AdjacencySelector adjacency) { var heater = Heater.Create(); for (int i = 0; i < repeats; ++i) { if (!heater.Heat(this, adjacency)) { // If heating did nothing, heating again won't either, // so we can just bail. break; } } heater.Recycle(); } /// <summary> /// This structure is a utility to make heatmap heatings faster; /// this holds onto various buffers so they can be reused, and /// caches passability data. /// </summary> private sealed class Heater { private readonly List<Location> adjacencyBuffer = new List<Location>(6); private readonly LocationMap<Slot> original = new LocationMap<Slot>(); private static Heater recycledInstance; /// <summary> /// Create() constructs a heater and returns it. This will reuse /// a recycled heater if one is available. /// </summary> public static Heater Create() { return Interlocked.Exchange(ref recycledInstance, null) ?? new Heater(); } /// <summary> /// Recycle() stores this as a recycled heater, so it can be reused by /// the next call to Create(). Don't continue to use the heater after /// this call. /// </summary> public void Recycle() { Interlocked.Exchange(ref recycledInstance, this); } /// <summary> /// Heat() applies heat to the heatmap given. The resulting /// values are queued and applied only at the end, so /// the order of changes is not signficiant. /// /// This method returns true if it found any changes to make, /// and false if it did nothing. /// </summary> public bool Heat(Heatmap heatmap, AdjacencySelector adjacency) { bool changed = false; heatmap.CopyTo(original); original.ForEachBlock(delegate (Location upperLeft, Slot[] slots) { int lx = 0, ly = 0; for (int slotIndex = 0; slotIndex < slots.Length; ++slotIndex) { if (slots[slotIndex].heat != 0) { Slot min = slots[slotIndex].ToReduced(1); if (min.heat != 0) { Location srcLoc = upperLeft.WithOffset(lx, ly); adjacencyBuffer.Clear(); adjacency(srcLoc, adjacencyBuffer); foreach (Location adj in adjacencyBuffer) { Slot oldSlot = original[adj]; Slot newSlot = Slot.Max(oldSlot, min); if (oldSlot.heat != newSlot.heat) { heatmap[adj] = newSlot; changed = true; } }; } } ++lx; if (lx >= blockSize) { lx = 0; ++ly; } } }); return changed; } } #endregion /// <summary> /// This structure describes the data held in one cell of /// the heatmap. /// </summary> public struct Slot : IEquatable<Slot> { public readonly SourceInfo source; public readonly int heat; public Slot(UnityEngine.GameObject source, int heat) : this(new SourceInfo(source).Intern(), heat) { } public Slot(SourceInfo source, int heat) { this.source = source; this.heat = heat; } public override string ToString() { if (source == null) return heat.ToString(); else return string.Format("{0} (from {1})", heat, source); } /// <summary> /// This method returns the slot (of the two given) that has the /// larger heat value. We use absolute value, so a large negatve /// value may be 'greater' than a small positive one. /// </summary> public static Slot Max(Slot left, Slot right) { // We treak int.Minvalue specially because Math.Abs(int.MinValue) // will throw; 2s complement arithmetic is a little funny this way, // as -int.MinValue is not representable. if (right.heat == int.MinValue) return right; else if (left.heat == int.MinValue) return left; else if (Math.Abs(left.heat) < Math.Abs(right.heat)) return right; else return left; } /// <summary> /// This method computes a new slot, by reduign this one. /// </summary> public Slot ToReduced(int amount) { int newHeat = heat; if (heat > 0) newHeat = Math.Max(0, heat - amount); else if (heat < 0) newHeat = Math.Min(0, heat + amount); else newHeat = 0; if (newHeat == 0) return new Slot(); else return new Slot(source, newHeat); } #region IEquatable implementation public bool Equals(Slot other) { return this.heat == other.heat && EqualityComparer<SourceInfo>.Default.Equals(this.source, other.source); } public override bool Equals(object obj) { return obj is Slot && Equals((Slot)obj); } public override int GetHashCode() { return heat.GetHashCode(); } #endregion } /// <summary> /// This class holds the identifying data for the source of /// the heat in the heatmap; each cell contains a refertence to /// an immutable source-info, which can then be shared by many /// cells. /// /// We cannot just use the GameObject directly here; it might be /// destroyed while the heatmap is still in use. So we copy what /// we need. /// </summary> public sealed class SourceInfo : IEquatable<SourceInfo> { public SourceInfo(UnityEngine.GameObject source) { this.Name = source.name; this.Tag = source.tag; this.Disposition = GetDisposition(source); } public SourceInfo(string name, string tag, SourceDisposition? disposition) { this.Name = name; this.Tag = tag; this.Disposition = disposition; } public string Name { get; private set; } public string Tag { get; private set; } public SourceDisposition? Disposition { get; private set; } public override string ToString() { return string.Format("{0} {1}", Name, Disposition).Trim(); } /// <summary> /// GetDisposition() works out the disposition of a given /// game object. We use this when generating a SourceInfo for /// a game object. /// </summary> public static SourceDisposition? GetDisposition(UnityEngine.GameObject source) { var ic = source.GetComponent<ItemController>(); CreatureController carrier; if (ic == null) return null; else if (!ic.TryGetCarrier(out carrier)) return SourceDisposition.Exposed; else if (ic.isHeldItem) return SourceDisposition.Held; else return SourceDisposition.Carried; } #region Interning private static readonly List<WeakReference> internedSourceInfos = new List<WeakReference>(); /// <summary> /// Intern() returns this source info, or a pre-existing on that is iequal /// to it. Using this reduces trhe number of source infos we 'keep alive'. /// /// We use this only for SourceInfos that are in 'Slot' structs; only these /// persist long enough for interning to help. /// </summary> public SourceInfo Intern() { lock (internedSourceInfos) { // Using a list like this seems inefficent, but I observe that the // number of 'live' source infos is around 25; this iz small enough to // linear scan, and that means we get to use weak-references in a simple // way, so we can avoid keep unused source infos alive! for (int i = internedSourceInfos.Count - 1; i >= 0; --i) { SourceInfo info = (SourceInfo)internedSourceInfos[i].Target; // The weak reference gives us null if the source info has been garbage collected; // after that the weak references itself is useless and we can discard it. if (info == null) internedSourceInfos.RemoveAt(i); else if (this.Equals(info)) return info; } internedSourceInfos.Add(new WeakReference(this)); return this; } } #endregion #region IEquatable implementation public bool Equals(SourceInfo other) { if (this == other) { return true; } return other != null && this.Name == other.Name && this.Tag == other.Tag; } public override bool Equals(object obj) { return Equals(obj as SourceInfo); } public override int GetHashCode() { return Name.GetHashCode(); } #endregion } /// <summary> /// SourceDisposition indicates whether the source item is /// being carried or held; does not apply to anything but items. /// </summary> public enum SourceDisposition { Exposed, Carried, Held } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Globalization; using System.IO; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Loader; using System.Security; using System.Text; using System.Text.RegularExpressions; namespace System.Management.Automation { /// <summary> /// ClrFacade contains all diverging code (different implementation for FullCLR and CoreCLR using if/def). /// It exposes common APIs that can be used by the rest of the code base. /// </summary> internal static class ClrFacade { /// <summary> /// Initialize powershell AssemblyLoadContext and register the 'Resolving' event, if it's not done already. /// If powershell is hosted by a native host such as DSC, then PS ALC might be initialized via 'SetPowerShellAssemblyLoadContext' before loading S.M.A. /// </summary> static ClrFacade() { if (PowerShellAssemblyLoadContext.Instance == null) { PowerShellAssemblyLoadContext.InitializeSingleton(string.Empty); } } #region Assembly internal static IEnumerable<Assembly> GetAssemblies(TypeResolutionState typeResolutionState, TypeName typeName) { string typeNameToSearch = typeResolutionState.GetAlternateTypeName(typeName.Name) ?? typeName.Name; return GetAssemblies(typeNameToSearch); } /// <summary> /// Facade for AppDomain.GetAssemblies. /// </summary> /// <param name="namespaceQualifiedTypeName"> /// In CoreCLR context, if it's for string-to-type conversion and the namespace qualified type name is known, pass it in so that /// powershell can load the necessary TPA if the target type is from an unloaded TPA. /// </param> internal static IEnumerable<Assembly> GetAssemblies(string namespaceQualifiedTypeName = null) { return PSAssemblyLoadContext.GetAssembly(namespaceQualifiedTypeName) ?? GetPSVisibleAssemblies(); } /// <summary> /// Return assemblies from the default load context and the 'individual' load contexts. /// The 'individual' load contexts are the ones holding assemblies loaded via 'Assembly.Load(byte[])' and 'Assembly.LoadFile'. /// Assemblies loaded in any custom load contexts are not consider visible to PowerShell to avoid type identity issues. /// </summary> private static IEnumerable<Assembly> GetPSVisibleAssemblies() { const string IndividualAssemblyLoadContext = "System.Runtime.Loader.IndividualAssemblyLoadContext"; foreach (Assembly assembly in AssemblyLoadContext.Default.Assemblies) { if (!assembly.FullName.StartsWith(TypeDefiner.DynamicClassAssemblyFullNamePrefix, StringComparison.Ordinal)) { yield return assembly; } } foreach (AssemblyLoadContext context in AssemblyLoadContext.All) { if (IndividualAssemblyLoadContext.Equals(context.GetType().FullName, StringComparison.Ordinal)) { foreach (Assembly assembly in context.Assemblies) { yield return assembly; } } } } /// <summary> /// Get the namespace-qualified type names of all available .NET Core types shipped with PowerShell. /// This is used for type name auto-completion in PS engine. /// </summary> internal static IEnumerable<string> AvailableDotNetTypeNames => PSAssemblyLoadContext.AvailableDotNetTypeNames; /// <summary> /// Get the assembly names of all available .NET Core assemblies shipped with PowerShell. /// This is used for type name auto-completion in PS engine. /// </summary> internal static HashSet<string> AvailableDotNetAssemblyNames => PSAssemblyLoadContext.AvailableDotNetAssemblyNames; private static PowerShellAssemblyLoadContext PSAssemblyLoadContext => PowerShellAssemblyLoadContext.Instance; #endregion Assembly #region Encoding /// <summary> /// Facade for getting default encoding. /// </summary> internal static Encoding GetDefaultEncoding() { if (s_defaultEncoding == null) { // load all available encodings EncodingRegisterProvider(); s_defaultEncoding = new UTF8Encoding(false); } return s_defaultEncoding; } private static volatile Encoding s_defaultEncoding; /// <summary> /// Facade for getting OEM encoding /// OEM encodings work on all platforms, or rather codepage 437 is available on both Windows and Non-Windows. /// </summary> internal static Encoding GetOEMEncoding() { if (s_oemEncoding == null) { // load all available encodings EncodingRegisterProvider(); #if UNIX s_oemEncoding = new UTF8Encoding(false); #else uint oemCp = NativeMethods.GetOEMCP(); s_oemEncoding = Encoding.GetEncoding((int)oemCp); #endif } return s_oemEncoding; } private static volatile Encoding s_oemEncoding; private static void EncodingRegisterProvider() { if (s_defaultEncoding == null && s_oemEncoding == null) { Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); } } #endregion Encoding #if !UNIX #region Security /// <summary> /// Facade to get the SecurityZone information of a file. /// </summary> internal static SecurityZone GetFileSecurityZone(string filePath) { Diagnostics.Assert(Path.IsPathRooted(filePath), "Caller makes sure the path is rooted."); Diagnostics.Assert(File.Exists(filePath), "Caller makes sure the file exists."); return MapSecurityZone(filePath); } /// <summary> /// Map the file to SecurityZone. /// </summary> /// <remarks> /// The algorithm is as follows: /// /// 1. Alternate data stream "Zone.Identifier" is checked first. If this alternate data stream has content, then the content is parsed to determine the SecurityZone. /// 2. If the alternate data stream "Zone.Identifier" doesn't exist, or its content is not expected, then the file path will be analyzed to determine the SecurityZone. /// /// For #1, the parsing rules are observed as follows: /// A. Read content of the data stream line by line. Each line is trimmed. /// B. Try to match the current line with '^\[ZoneTransfer\]'. /// - if matching, then do step (#C) starting from the next line /// - if not matching, then continue to do step (#B) with the next line. /// C. Try to match the current line with '^ZoneId\s*=\s*(.*)' /// - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if the 'ZoneId' is valid, or 'NoZone' if invalid. /// - if not matching, then continue to do step (#C) with the next line. /// D. Reach EOF, then return 'NoZone'. /// After #1, if the returned SecurityZone is 'NoZone', then proceed with #2. Otherwise, return it as the mapping result. /// /// For #2, the analysis rules are observed as follows: /// A. If the path is a UNC path, then /// - if the host name of the UNC path is IP address, then mapping it to "Internet" zone. /// - if the host name of the UNC path has dot (.) in it, then mapping it to "internet" zone. /// - otherwise, mapping it to "intranet" zone. /// B. If the path is not UNC path, then get the root drive, /// - if the drive is CDRom, mapping it to "Untrusted" zone /// - if the drive is Network, mapping it to "Intranet" zone /// - otherwise, mapping it to "MyComputer" zone. /// /// The above algorithm has two changes comparing to the behavior of "Zone.CreateFromUrl" I observed: /// (1) If a file downloaded from internet (ZoneId=3) is not on the local machine, "Zone.CreateFromUrl" won't respect the MOTW. /// I think it makes more sense for powershell to always check the MOTW first, even for files not on local box. /// (2) When it's a UNC path and is actually a loopback (\\127.0.0.1\c$\test.txt), "Zone.CreateFromUrl" returns "Internet", but /// the above algorithm changes it to be "MyComputer" because it's actually the same computer. /// </remarks> private static SecurityZone MapSecurityZone(string filePath) { // WSL introduces a new filesystem path to access the Linux filesystem from Windows, like '\\wsl$\ubuntu'. // If the given file path is such a special case, we consider it's in 'MyComputer' zone. if (filePath.StartsWith(Utils.WslRootPath, StringComparison.OrdinalIgnoreCase)) { return SecurityZone.MyComputer; } SecurityZone reval = ReadFromZoneIdentifierDataStream(filePath); if (reval != SecurityZone.NoZone) { return reval; } // If it reaches here, then we either couldn't get the ZoneId information, or the ZoneId is invalid. // In this case, we try to determine the SecurityZone by analyzing the file path. Uri uri = new Uri(filePath); if (uri.IsUnc) { if (uri.IsLoopback) { return SecurityZone.MyComputer; } if (uri.HostNameType == UriHostNameType.IPv4 || uri.HostNameType == UriHostNameType.IPv6) { return SecurityZone.Internet; } // This is also an observation of Zone.CreateFromUrl/Zone.SecurityZone. If the host name // has 'dot' in it, the file will be treated as in Internet security zone. Otherwise, it's // in Intranet security zone. string hostName = uri.Host; return hostName.Contains('.') ? SecurityZone.Internet : SecurityZone.Intranet; } string root = Path.GetPathRoot(filePath); DriveInfo drive = new DriveInfo(root); switch (drive.DriveType) { case DriveType.NoRootDirectory: case DriveType.Unknown: case DriveType.CDRom: return SecurityZone.Untrusted; case DriveType.Network: return SecurityZone.Intranet; default: return SecurityZone.MyComputer; } } /// <summary> /// Read the 'Zone.Identifier' alternate data stream to determin SecurityZone of the file. /// </summary> private static SecurityZone ReadFromZoneIdentifierDataStream(string filePath) { if (!AlternateDataStreamUtilities.TryCreateFileStream(filePath, "Zone.Identifier", FileMode.Open, FileAccess.Read, FileShare.Read, out var zoneDataStream)) { return SecurityZone.NoZone; } // If we successfully get the zone data stream, try to read the ZoneId information using (StreamReader zoneDataReader = new StreamReader(zoneDataStream, GetDefaultEncoding())) { string line = null; bool zoneTransferMatched = false; // After a lot experiments with Zone.CreateFromUrl/Zone.SecurityZone, the way it handles the alternate // data stream 'Zone.Identifier' is observed as follows: // 1. Read content of the data stream line by line. Each line is trimmed. // 2. Try to match the current line with '^\[ZoneTransfer\]'. // - if matching, then do step #3 starting from the next line // - if not matching, then continue to do step #2 with the next line. // 3. Try to match the current line with '^ZoneId\s*=\s*(.*)' // - if matching, check if the ZoneId is valid. Then return the corresponding SecurityZone if valid, or 'NoZone' if invalid. // - if not matching, then continue to do step #3 with the next line. // 4. Reach EOF, then return 'NoZone'. while ((line = zoneDataReader.ReadLine()) != null) { line = line.Trim(); if (!zoneTransferMatched) { zoneTransferMatched = Regex.IsMatch(line, @"^\[ZoneTransfer\]", RegexOptions.IgnoreCase); } else { Match match = Regex.Match(line, @"^ZoneId\s*=\s*(.*)", RegexOptions.IgnoreCase); if (!match.Success) { continue; } // Match found. Validate ZoneId value. string zoneIdRawValue = match.Groups[1].Value; match = Regex.Match(zoneIdRawValue, @"^[+-]?\d+", RegexOptions.IgnoreCase); if (!match.Success) { return SecurityZone.NoZone; } string zoneId = match.Groups[0].Value; SecurityZone result; return LanguagePrimitives.TryConvertTo(zoneId, out result) ? result : SecurityZone.NoZone; } } } return SecurityZone.NoZone; } #endregion Security #endif #region Misc /// <summary> /// Facade for ManagementDateTimeConverter.ToDmtfDateTime(DateTime) /// </summary> internal static string ToDmtfDateTime(DateTime date) { #if CORECLR // This implementation is copied from ManagementDateTimeConverter.ToDmtfDateTime(DateTime date) with a minor adjustment: // Use TimeZoneInfo.Local instead of TimeZone.CurrentTimeZone. System.TimeZone is not in CoreCLR. // According to MSDN, CurrentTimeZone property corresponds to the TimeZoneInfo.Local property, and // it's recommended to use TimeZoneInfo.Local whenever possible. const int maxsizeUtcDmtf = 999; string UtcString = string.Empty; // Fill up the UTC field in the DMTF date with the current zones UTC value TimeZoneInfo curZone = TimeZoneInfo.Local; TimeSpan tickOffset = curZone.GetUtcOffset(date); long OffsetMins = (tickOffset.Ticks / TimeSpan.TicksPerMinute); IFormatProvider frmInt32 = (IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(int)); // If the offset is more than that what can be specified in DMTF format, then // convert the date to UniversalTime if (Math.Abs(OffsetMins) > maxsizeUtcDmtf) { date = date.ToUniversalTime(); UtcString = "+000"; } else if ((tickOffset.Ticks >= 0)) { UtcString = "+" + ((tickOffset.Ticks / TimeSpan.TicksPerMinute)).ToString(frmInt32).PadLeft(3, '0'); } else { string strTemp = OffsetMins.ToString(frmInt32); UtcString = "-" + strTemp.Substring(1, strTemp.Length - 1).PadLeft(3, '0'); } string dmtfDateTime = date.Year.ToString(frmInt32).PadLeft(4, '0'); dmtfDateTime += date.Month.ToString(frmInt32).PadLeft(2, '0'); dmtfDateTime += date.Day.ToString(frmInt32).PadLeft(2, '0'); dmtfDateTime += date.Hour.ToString(frmInt32).PadLeft(2, '0'); dmtfDateTime += date.Minute.ToString(frmInt32).PadLeft(2, '0'); dmtfDateTime += date.Second.ToString(frmInt32).PadLeft(2, '0'); dmtfDateTime += "."; // Construct a DateTime with with the precision to Second as same as the passed DateTime and so get // the ticks difference so that the microseconds can be calculated DateTime dtTemp = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); Int64 microsec = ((date.Ticks - dtTemp.Ticks) * 1000) / TimeSpan.TicksPerMillisecond; // fill the microseconds field string strMicrosec = microsec.ToString((IFormatProvider)CultureInfo.InvariantCulture.GetFormat(typeof(Int64))); if (strMicrosec.Length > 6) { strMicrosec = strMicrosec.Substring(0, 6); } dmtfDateTime += strMicrosec.PadLeft(6, '0'); // adding the UTC offset dmtfDateTime += UtcString; return dmtfDateTime; #else return ManagementDateTimeConverter.ToDmtfDateTime(date); #endif } #endregion Misc /// <summary> /// Native methods that are used by facade methods. /// </summary> private static class NativeMethods { /// <summary> /// Pinvoke for GetOEMCP to get the OEM code page. /// </summary> [DllImport(PinvokeDllNames.GetOEMCPDllName, SetLastError = false, CharSet = CharSet.Unicode)] internal static extern uint GetOEMCP(); } } }
/* Copyright 2015-2018 Daniel Adrian Redondo Suarez Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Text; #pragma warning disable 1591 namespace TWCore.Serialization.RawSerializer { public delegate void SerializeActionDelegate(object obj, SerializersTable table); public class SerializerTypeDescriptor { private static readonly MethodInfo RawSerializableSerializeMInfo = typeof(IRawSerializable).GetMethod("Serialize", BindingFlags.Public | BindingFlags.Instance); public readonly bool IsRawSerializable; public readonly byte[] Definition; public readonly Type Type; public readonly LambdaExpression InnerWriterLambda; public readonly SerializeActionDelegate SerializeAction; [MethodImpl(MethodImplOptions.AggressiveInlining)] public SerializerTypeDescriptor(Type type, HashSet<Type> previousTypes = null) { Type = type; if (previousTypes == null) previousTypes = new HashSet<Type>(); var ifaces = type.GetInterfaces(); var iListType = ifaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>)); var iDictionaryType = ifaces.FirstOrDefault(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IDictionary<,>)); var isIList = iListType != null; var isIDictionary = iDictionaryType != null; var runtimeProperties = type.GetRuntimeProperties().OrderBy(p => p.Name).Where(prop => { if (prop.IsSpecialName || !prop.CanRead || !prop.CanWrite) return false; if (prop.GetAttribute<NonSerializeAttribute>() != null) return false; if (prop.GetIndexParameters().Length > 0) return false; if (isIList && prop.Name == "Capacity") return false; return true; }).ToArray(); // var properties = runtimeProperties.Select(p => p.Name).ToArray(); IsRawSerializable = ifaces.Any(i => i == typeof(IRawSerializable)); var isArray = type.IsArray; var isList = false; if (!isArray) isList = !isIDictionary && isIList; // var typeName = type.GetTypeName(); var defText = typeName + ";" + (isArray ? "1" : "0") + ";" + (isList ? "1" : "0") + ";" + (isIDictionary ? "1" : "0") + ";" + properties.Join(";"); var defBytesLength = Encoding.UTF8.GetByteCount(defText); var defBytes = new byte[defBytesLength + 5]; defBytes[0] = DataBytesDefinition.TypeStart; defBytes[1] = (byte)defBytesLength; defBytes[2] = (byte)(defBytesLength >> 8); defBytes[3] = (byte)(defBytesLength >> 16); defBytes[4] = (byte)(defBytesLength >> 24); Encoding.UTF8.GetBytes(defText, 0, defText.Length, defBytes, 5); Definition = defBytes; SerializeAction = null; // var serExpressions = new List<Expression>(); var varExpressions = new List<ParameterExpression>(); // var obj = Expression.Parameter(typeof(object), "obj"); var serTable = Expression.Parameter(typeof(SerializersTable), "table"); var instance = Expression.Parameter(type, "instance"); varExpressions.Add(instance); serExpressions.Add(Expression.Assign(instance, Expression.Convert(obj, type))); // if (isArray) { var elementType = type.GetElementType(); var arrLength = Expression.Parameter(typeof(int), "length"); varExpressions.Add(arrLength); serExpressions.Add(Expression.Assign(arrLength, Expression.Call(instance, SerializersTable.ArrayLengthGetMethod))); serExpressions.Add(Expression.Call(serTable, SerializersTable.WriteIntMethodInfo, arrLength)); var forIdx = Expression.Parameter(typeof(int), "i"); varExpressions.Add(forIdx); var breakLabel = Expression.Label(typeof(void), "exitLoop"); serExpressions.Add(Expression.Assign(forIdx, Expression.Constant(0))); var getValueExpression = Expression.ArrayIndex(instance, Expression.PostIncrementAssign(forIdx)); var loop = Expression.Loop( Expression.IfThenElse( Expression.LessThan(forIdx, arrLength), WriteExpression(elementType, getValueExpression, serTable), Expression.Break(breakLabel)), breakLabel); serExpressions.Add(loop); } else if (isList) { var argTypes = iListType.GenericTypeArguments; var iLength = Expression.Parameter(typeof(int), "length"); varExpressions.Add(iLength); serExpressions.Add(Expression.Assign(iLength, Expression.Call(instance, SerializersTable.ListCountGetMethod))); serExpressions.Add(Expression.Call(serTable, SerializersTable.WriteIntMethodInfo, iLength)); var forIdx = Expression.Parameter(typeof(int), "i"); varExpressions.Add(forIdx); var breakLabel = Expression.Label(typeof(void), "exitLoop"); serExpressions.Add(Expression.Assign(forIdx, Expression.Constant(0))); var getValueExpression = Expression.MakeIndex(instance, SerializersTable.ListIndexProperty, new[] { Expression.PostIncrementAssign(forIdx) }); var loop = Expression.Loop( Expression.IfThenElse( Expression.LessThan(forIdx, iLength), WriteExpression(argTypes[0], getValueExpression, serTable), Expression.Break(breakLabel)), breakLabel); serExpressions.Add(loop); } else if (isIDictionary) { var argTypes = iDictionaryType.GenericTypeArguments; var iLength = Expression.Parameter(typeof(int), "length"); varExpressions.Add(iLength); serExpressions.Add(Expression.Assign(iLength, Expression.Call(instance, SerializersTable.ListCountGetMethod))); serExpressions.Add(Expression.Call(serTable, SerializersTable.WriteIntMethodInfo, iLength)); var enumerator = Expression.Parameter(typeof(IDictionaryEnumerator), "enumerator"); varExpressions.Add(enumerator); serExpressions.Add(Expression.Assign(enumerator, Expression.Call(instance, SerializersTable.DictionaryGetEnumeratorMethod))); var breakLabel = Expression.Label(typeof(void), "exitLoop"); var getKeyExpression = Expression.Convert(Expression.Call(enumerator, SerializersTable.DictionaryEnumeratorKeyMethod), argTypes[0]); var getValueExpression = Expression.Convert(Expression.Call(enumerator, SerializersTable.DictionaryEnumeratorValueMethod), argTypes[1]); var loop = Expression.Loop( Expression.IfThenElse( Expression.Call(enumerator, SerializersTable.EnumeratorMoveNextMethod), Expression.Block( WriteExpression(argTypes[0], getKeyExpression, serTable), WriteExpression(argTypes[1], getValueExpression, serTable) ), Expression.Break(breakLabel)), breakLabel); serExpressions.Add(loop); } // if (runtimeProperties.Length > 0) { foreach (var prop in runtimeProperties) { var getExpression = Expression.Property(instance, prop); serExpressions.Add(WriteExpression(prop.PropertyType, getExpression, serTable)); } } // var serExpression = Expression.Block(varExpressions, serExpressions).Reduce(); var innerValue = Expression.Parameter(type, "innerValue"); var innerSerExpression = Expression.Block(varExpressions, new[] { Expression.Assign(instance, innerValue) }.Concat(serExpressions.Skip(1))).Reduce(); InnerWriterLambda = Expression.Lambda(innerSerExpression, type.Name + "Writer", new[] { innerValue, serTable }); var serializationLambda = Expression.Lambda<SerializeActionDelegate>(serExpression, type.Name + "_Serializer", new[] { obj, serTable }); SerializeAction = serializationLambda.Compile(); Expression WriteExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression) { if (itemType == typeof(int)) return SerializersTable.WriteIntExpression(itemGetExpression, serTableExpression); if (itemType == typeof(int?)) return SerializersTable.WriteNulleableIntExpression(itemGetExpression, serTableExpression); if (itemType == typeof(bool)) return SerializersTable.WriteBooleanExpression(itemGetExpression, serTableExpression); if (itemType == typeof(bool?)) return SerializersTable.WriteNulleableBooleanExpression(itemGetExpression, serTableExpression); if (SerializersTable.WriteValues.TryGetValue(itemType, out var wMethodTuple)) return Expression.Call(serTableExpression, wMethodTuple.Method, itemGetExpression); if (itemType.IsEnum) return Expression.Call(serTableExpression, SerializersTable.WriteValues[typeof(Enum)].Method, Expression.Convert(itemGetExpression, typeof(Enum))); if (itemType.IsGenericType && itemType.GetGenericTypeDefinition() == typeof(Nullable<>)) { var nullParam = Expression.Parameter(itemType); var nullBlock = Expression.Block(new[] { nullParam }, Expression.Assign(nullParam, itemGetExpression), Expression.IfThenElse( Expression.Equal(nullParam, Expression.Constant(null, itemType)), Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), WriteExpression(itemType.GenericTypeArguments[0], nullParam, serTableExpression) ) ); return nullBlock; } if (itemType == typeof(IEnumerable) || itemType == typeof(IEnumerable<>) || itemType.ReflectedType == typeof(IEnumerable) || itemType.ReflectedType == typeof(IEnumerable<>) || itemType.ReflectedType == typeof(Enumerable) || itemType.FullName.IndexOf("System.Linq", StringComparison.Ordinal) > -1 || itemType.IsAssignableFrom(typeof(IEnumerable))) return Expression.Call(serTableExpression, SerializersTable.InternalWriteObjectValueMInfo, itemGetExpression); if (itemType.IsAbstract || itemType.IsInterface || itemType == typeof(object)) return Expression.Call(serTableExpression, SerializersTable.InternalWriteObjectValueMInfo, itemGetExpression); if (itemType.IsSealed) return WriteSealedExpression(itemType, itemGetExpression, serTableExpression); return WriteMixedExpression(itemType, itemGetExpression, serTableExpression); //return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); } Expression WriteSealedExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression) { if (itemType == type) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); if (!previousTypes.Add(itemType)) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); var innerDescriptor = SerializersTable.Descriptors.GetOrAdd(itemType, (tp, ptypes) => new SerializerTypeDescriptor(tp, ptypes), previousTypes); var innerVarExpressions = new List<ParameterExpression>(); var innerSerExpressions = new List<Expression>(); var returnLabel = Expression.Label(typeof(void), "return"); var value = Expression.Parameter(itemType, "value"); innerVarExpressions.Add(value); innerSerExpressions.Add(Expression.Assign(value, Expression.Convert(itemGetExpression, itemType))); #region Null Check innerSerExpressions.Add( Expression.IfThen(Expression.ReferenceEqual(value, Expression.Constant(null)), Expression.Block( Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), Expression.Return(returnLabel) ) ) ); #endregion #region Object Cache Check var objCacheExp = Expression.Field(serTableExpression, "_objectCache"); var objIdxExp = Expression.Variable(typeof(int), "objIdx"); innerVarExpressions.Add(objIdxExp); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(objCacheExp, SerializersTable.TryGetValueObjectSerializerCacheMethod, value, objIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteRefObjectMInfo, objIdxExp), Expression.Return(returnLabel) ), Expression.Call(objCacheExp, SerializersTable.SetObjectSerializerCacheMethod, value) ) ); #endregion #region Type Cache Check var typeCacheExp = Expression.Field(serTableExpression, "_typeCache"); var typeIdxExp = Expression.Variable(typeof(int), "tIdx"); innerVarExpressions.Add(typeIdxExp); var descDefinition = typeof(SerializerTypeDescriptor<>).MakeGenericType(itemType).GetField("Definition", BindingFlags.Public | BindingFlags.Static); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(typeCacheExp, SerializersTable.TryGetValueTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type)), typeIdxExp), Expression.Call(serTable, SerializersTable.WriteRefTypeMInfo, typeIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteBytesMethodInfo, Expression.Field(null, descDefinition)), Expression.Call(typeCacheExp, SerializersTable.SetTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type))) ) ) ); #endregion #region Serializer Call if (innerDescriptor.IsRawSerializable) { innerSerExpressions.Add(Expression.Call(Expression.Convert(value, typeof(IRawSerializable)), RawSerializableSerializeMInfo, serTableExpression)); } else { innerSerExpressions.Add(Expression.Invoke(innerDescriptor.InnerWriterLambda, value, serTable)); } #endregion innerSerExpressions.Add(Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.TypeEnd))); innerSerExpressions.Add(Expression.Label(returnLabel)); var innerExpression = Expression.Block(innerVarExpressions, innerSerExpressions).Reduce(); previousTypes.Remove(itemType); return innerExpression; } Expression WriteMixedExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression) { if (itemType == type) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); if (!previousTypes.Add(itemType)) return Expression.Call(serTableExpression, SerializersTable.InternalSimpleWriteObjectValueMInfo, itemGetExpression); var innerDescriptor = SerializersTable.Descriptors.GetOrAdd(itemType, (tp, ptypes) => new SerializerTypeDescriptor(tp, ptypes), previousTypes); var innerVarExpressions = new List<ParameterExpression>(); var innerSerExpressions = new List<Expression>(); var returnLabel = Expression.Label(typeof(void), "return"); var objValue = Expression.Parameter(typeof(object), "objValue"); innerVarExpressions.Add(objValue); innerSerExpressions.Add(Expression.Assign(objValue, itemGetExpression)); #region Null Check innerSerExpressions.Add( Expression.IfThen(Expression.ReferenceEqual(objValue, Expression.Constant(null)), Expression.Block( Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.ValueNull)), Expression.Return(returnLabel) ) ) ); #endregion #region Object Cache Check var objCacheExp = Expression.Field(serTableExpression, "_objectCache"); var objIdxExp = Expression.Variable(typeof(int), "objIdx"); innerVarExpressions.Add(objIdxExp); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(objCacheExp, SerializersTable.TryGetValueObjectSerializerCacheMethod, objValue, objIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteRefObjectMInfo, objIdxExp), Expression.Return(returnLabel) ), Expression.Call(objCacheExp, SerializersTable.SetObjectSerializerCacheMethod, objValue) ) ); #endregion var valueType = Expression.Parameter(typeof(Type), "valueType"); innerVarExpressions.Add(valueType); innerSerExpressions.Add(Expression.Assign(valueType, Expression.Call(objValue, SerializersTable.GetTypeMethodInfo))); innerSerExpressions.Add( Expression.IfThenElse(Expression.TypeIs(objValue, itemType), WriteShortSealedExpression(itemType, objValue, serTableExpression, returnLabel, innerDescriptor), Expression.Call(serTableExpression, SerializersTable.InternalMixedWriteObjectValueMInfo, objValue, valueType) ) ); innerSerExpressions.Add(Expression.Call(serTable, SerializersTable.WriteByteMethodInfo, Expression.Constant(DataBytesDefinition.TypeEnd))); innerSerExpressions.Add(Expression.Label(returnLabel)); var innerExpression = Expression.Block(innerVarExpressions, innerSerExpressions).Reduce(); previousTypes.Remove(itemType); return innerExpression; } Expression WriteShortSealedExpression(Type itemType, Expression itemGetExpression, ParameterExpression serTableExpression, LabelTarget returnLabel, SerializerTypeDescriptor innerDescriptor) { var innerVarExpressions = new List<ParameterExpression>(); var innerSerExpressions = new List<Expression>(); var value = Expression.Parameter(itemType, "value"); innerVarExpressions.Add(value); innerSerExpressions.Add(Expression.Assign(value, Expression.Convert(itemGetExpression, itemType))); #region Type Cache Check var typeCacheExp = Expression.Field(serTableExpression, "_typeCache"); var typeIdxExp = Expression.Variable(typeof(int), "tIdx"); innerVarExpressions.Add(typeIdxExp); var descDefinition = typeof(SerializerTypeDescriptor<>).MakeGenericType(itemType).GetField("Definition", BindingFlags.Public | BindingFlags.Static); innerSerExpressions.Add( Expression.IfThenElse(Expression.Call(typeCacheExp, SerializersTable.TryGetValueTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type)), typeIdxExp), Expression.Call(serTable, SerializersTable.WriteRefTypeMInfo, typeIdxExp), Expression.Block( Expression.Call(serTable, SerializersTable.WriteBytesMethodInfo, Expression.Field(null, descDefinition)), Expression.Call(typeCacheExp, SerializersTable.SetTypeSerializerCacheMethod, Expression.Constant(itemType, typeof(Type))) ) ) ); #endregion #region Serializer Call if (innerDescriptor.IsRawSerializable) { innerSerExpressions.Add(Expression.Call(Expression.Convert(value, typeof(IRawSerializable)), RawSerializableSerializeMInfo, serTableExpression)); } else { innerSerExpressions.Add(Expression.Invoke(innerDescriptor.InnerWriterLambda, value, serTable)); } #endregion var innerExpression = Expression.Block(innerVarExpressions, innerSerExpressions).Reduce(); return innerExpression; } } } public static class SerializerTypeDescriptor<T> { public static byte[] Definition; public static SerializerTypeDescriptor Descriptor; static SerializerTypeDescriptor() { Descriptor = SerializersTable.Descriptors.GetOrAdd(typeof(T), t => new SerializerTypeDescriptor(t)); Definition = Descriptor.Definition; } } }
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 Website.Areas.HelpPage { /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); ActionSamples = new Dictionary<HelpPageSampleKey, object>(); SampleObjects = new Dictionary<Type, object>(); } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try get sample provided for a specific mediaType, controllerName, actionName and parameterNames. // If not found, try get the sample provided for a specific mediaType, controllerName and actionName regardless of the parameterNames // If still not found, try get the sample provided for a specific type and mediaType if (ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create one using <see cref="ObjectGenerator"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> public virtual object GetSampleObject(Type type) { object sampleObject; if (!SampleObjects.TryGetValue(type, out sampleObject)) { // Try create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); sampleObject = objectGenerator.GenerateObject(type); } return sampleObject; } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.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, e.Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (String.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } } }
/******************************************************************************* * Copyright 2019 Viridian Software Limited * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ******************************************************************************/ using Microsoft.Xna.Framework.Graphics; using Org.Mini2Dx.Core; using Org.Mini2Dx.Core.Assets; using Org.Mini2Dx.Core.Font; using Org.Mini2Dx.Core.Util; using Color = Org.Mini2Dx.Core.Graphics.Color; using System; using Org.Mini2Dx.Gdx.Math; using Org.Mini2Dx.Core.Graphics; using Microsoft.Xna.Framework.Content; using System.Collections.Generic; namespace monogame.Graphics { public class MonoGameShader : global::Java.Lang.Object, Org.Mini2Dx.Core.Graphics.Shader { private Microsoft.Xna.Framework.Vector2 tmpVector2 = new Microsoft.Xna.Framework.Vector2(); private Microsoft.Xna.Framework.Vector3 tmpVector3 = new Microsoft.Xna.Framework.Vector3(); private Microsoft.Xna.Framework.Vector4 tmpVector4 = new Microsoft.Xna.Framework.Vector4(); private Microsoft.Xna.Framework.Matrix tmpMatrix = new Microsoft.Xna.Framework.Matrix(); private Dictionary<Java.Lang.String, string> StringCache = new Dictionary<Java.Lang.String, string>(); public Effect shader; public MonoGameShader(string name) { if(!name.EndsWith(".fx")) { name += ".fx"; } ContentManager contentManager = ((MonoGameFiles)Mdx.files_)._contentManager; shader = contentManager.Load<Effect>(name); shader.CurrentTechnique = shader.Techniques[0]; } public MonoGameShader(Effect effect) { shader = effect; if(shader != null) { shader.CurrentTechnique = shader.Techniques[0]; } } public void dispose_EFE09FC0() { shader.Dispose(); } public void begin_EFE09FC0() { } public void end_EFE09FC0() { } public bool hasParameter_62DB41BA(Java.Lang.String str) { try { return shader.Parameters[GetString(str)] != null; } catch { } return false; } public void setParameter_0CF4EE29(Java.Lang.String str, Org.Mini2Dx.Core.Graphics.Texture t) { setParameter_42C1476E(str, 0, t); } public void setParameter_42C1476E(Java.Lang.String str, int i, Org.Mini2Dx.Core.Graphics.Texture t) { MonoGameTexture texture = t as MonoGameTexture; shader.Parameters[GetString(str)].SetValue(texture.texture2D); } public void setParameterf_8993FAC4(Java.Lang.String str, float f) { shader.Parameters[GetString(str)].SetValue(f); } public void setParameterf_BFC06056(Java.Lang.String str, float f1, float f2) { tmpVector2.X = f1; tmpVector2.Y = f2; shader.Parameters[GetString(str)].SetValue(tmpVector2); } public void setParameterf_2C2C4844(Java.Lang.String str, float f1, float f2, float f3) { tmpVector3.X = f1; tmpVector3.Y = f2; tmpVector3.Z = f3; shader.Parameters[GetString(str)].SetValue(tmpVector3); } public void setParameterf_A02729D6(Java.Lang.String str, float f1, float f2, float f3, float f4) { tmpVector4.X = f1; tmpVector4.Y = f2; tmpVector4.Z = f3; tmpVector4.W = f4; shader.Parameters[GetString(str)].SetValue(tmpVector4); } public void setParameterf_DC7C90B6(Java.Lang.String str, Vector2 v) { tmpVector2.X = v.x_; tmpVector2.Y = v.y_; shader.Parameters[GetString(str)].SetValue(tmpVector2); } public void setParameterf_DA5AD9B1(Java.Lang.String str, Vector3 v) { tmpVector3.X = v.x_; tmpVector3.Y = v.y_; tmpVector3.Z = v.z_; shader.Parameters[GetString(str)].SetValue(tmpVector3); } public void setParameteri_DB225B79(Java.Lang.String str, int i) { shader.Parameters[GetString(str)].SetValue(i); } public void setParameterMatrix_BD88B5D2(Java.Lang.String str, Matrix4 m) { setParameterMatrix_53DFED5C(str, m, false); } public void setParameterMatrix_53DFED5C(Java.Lang.String str, Matrix4 m, bool b) { setTempMatrix(m); if (b) { shader.Parameters[GetString(str)].SetValueTranspose(tmpMatrix); } else { shader.Parameters[GetString(str)].SetValue(tmpMatrix); } } private void setTempMatrix(Matrix4 m) { tmpMatrix.M11 = m.val_[Matrix4.M00_]; tmpMatrix.M12 = m.val_[Matrix4.M01_]; tmpMatrix.M13 = m.val_[Matrix4.M02_]; tmpMatrix.M14 = m.val_[Matrix4.M03_]; tmpMatrix.M21 = m.val_[Matrix4.M10_]; tmpMatrix.M22 = m.val_[Matrix4.M11_]; tmpMatrix.M23 = m.val_[Matrix4.M12_]; tmpMatrix.M24 = m.val_[Matrix4.M13_]; tmpMatrix.M31 = m.val_[Matrix4.M20_]; tmpMatrix.M32 = m.val_[Matrix4.M21_]; tmpMatrix.M33 = m.val_[Matrix4.M22_]; tmpMatrix.M34 = m.val_[Matrix4.M23_]; tmpMatrix.M41 = m.val_[Matrix4.M30_]; tmpMatrix.M42 = m.val_[Matrix4.M31_]; tmpMatrix.M43 = m.val_[Matrix4.M32_]; tmpMatrix.M44 = m.val_[Matrix4.M33_]; } private string GetString(Java.Lang.String str) { if(!StringCache.ContainsKey(str)) { StringCache[str] = (string)str; } return StringCache[str]; } public Java.Lang.String getLog_E605312C() { return string.Empty; } public bool isCompiled_FBE0B2A4() { return true; } public ShaderType getShaderType_7478A89B() { return ShaderType.HLSL_; } } }
// 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 ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer; using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclassregindexer.genclassregindexer { using System; public class MyClass { public int Field = 0; } public struct MyStruct { public int Number; } public enum MyEnum { First = 1, Second = 2, Third = 3 } public class MemberClass<T> { [ThreadStatic] public static int Status; public bool? this[string p1, float p2, short[] p3] { get { MemberClass<T>.Status = 1; return null; } set { MemberClass<T>.Status = 2; } } public byte this[dynamic[] p1, ulong[] p2, dynamic p3] { get { MemberClass<T>.Status = 1; return (byte)3; } set { MemberClass<T>.Status = 2; } } public dynamic this[MyClass p1, char? p2, MyEnum[] p3] { get { MemberClass<T>.Status = 1; return p1; } set { MemberClass<T>.Status = 2; } } public dynamic[] this[MyClass p1, MyStruct? p2, MyEnum[] p3] { get { MemberClass<T>.Status = 1; return new dynamic[] { p1, p2 } ; } set { MemberClass<T>.Status = 2; } } public double[] this[float p1] { get { MemberClass<T>.Status = 1; return new double[] { 1.4, double.Epsilon, double.NaN } ; } set { MemberClass<T>.Status = 2; } } public dynamic this[int?[] p1] { get { MemberClass<T>.Status = 1; return p1; } set { MemberClass<T>.Status = 2; } } public MyClass[] this[MyEnum p1] { get { MemberClass<T>.Status = 1; return new MyClass[] { null, new MyClass() { Field = 3 } } ; } set { MemberClass<T>.Status = 2; } } public T this[string p1] { get { MemberClass<T>.Status = 1; return default(T); } set { MemberClass<T>.Status = 2; } } public MyClass this[string p1, T p2] { get { MemberClass<T>.Status = 1; return new MyClass(); } set { MemberClass<T>.Status = 2; } } public dynamic this[T p1] { get { MemberClass<T>.Status = 1; return default(T); } set { MemberClass<T>.Status = 2; } } public T this[dynamic p1, T p2] { get { MemberClass<T>.Status = 1; return default(T); } set { MemberClass<T>.Status = 2; } } public T this[T p1, short p2, dynamic p3, string p4] { get { MemberClass<T>.Status = 1; return default(T); } set { MemberClass<T>.Status = 2; } } } public class MemberClassMultipleParams<T, U, V> { public static int Status; public T this[V v, U u] { get { MemberClassMultipleParams<T, U, V>.Status = 1; return default(T); } set { MemberClassMultipleParams<T, U, V>.Status = 2; } } } public class MemberClassWithClassConstraint<T> where T : class { [ThreadStatic] public static int Status; public int this[int x] { get { MemberClassWithClassConstraint<T>.Status = 3; return 1; } set { MemberClassWithClassConstraint<T>.Status = 4; } } public T this[decimal dec, dynamic d] { get { MemberClassWithClassConstraint<T>.Status = 1; return null; } set { MemberClassWithClassConstraint<T>.Status = 2; } } } public class MemberClassWithNewConstraint<T> where T : new() { [ThreadStatic] public static int Status; public dynamic this[T t] { get { MemberClassWithNewConstraint<T>.Status = 1; return new T(); } set { MemberClassWithNewConstraint<T>.Status = 2; } } } public class MemberClassWithAnotherTypeConstraint<T, U> where T : U { public static int Status; public U this[dynamic d] { get { MemberClassWithAnotherTypeConstraint<T, U>.Status = 3; return default(U); } set { MemberClassWithAnotherTypeConstraint<T, U>.Status = 4; } } public dynamic this[int x, U u, dynamic d] { get { MemberClassWithAnotherTypeConstraint<T, U>.Status = 1; return default(T); } set { MemberClassWithAnotherTypeConstraint<T, U>.Status = 2; } } } #region Negative tests - you should not be able to construct this with a dynamic object public class C { } public interface I { } public class MemberClassWithUDClassConstraint<T> where T : C, new() { public static int Status; public C this[T t] { get { MemberClassWithUDClassConstraint<T>.Status = 1; return new T(); } set { MemberClassWithUDClassConstraint<T>.Status = 2; } } } public class MemberClassWithStructConstraint<T> where T : struct { public static int Status; public dynamic this[int x] { get { MemberClassWithStructConstraint<T>.Status = 1; return x; } set { MemberClassWithStructConstraint<T>.Status = 2; } } } public class MemberClassWithInterfaceConstraint<T> where T : I { public static int Status; public dynamic this[int x, T v] { get { MemberClassWithInterfaceConstraint<T>.Status = 1; return default(T); } set { MemberClassWithInterfaceConstraint<T>.Status = 2; } } } #endregion } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001 { // <Title> Tests generic class indexer used in + operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void PlusOperator() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass001.genclass001 dynamic dy = new MemberClass<int>(); string p1 = null; int result = dy[string.Empty] + dy[p1] + 1; Assert.Equal(1, result); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002 { // <Title> Tests generic class indexer used in implicit operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(15,20\).*CS0649</Expects> //<Expects Status=warning>\(29,20\).*CS0649</Expects> public class Test { public class ClassWithImplicitOperator { public static implicit operator EmptyClass(ClassWithImplicitOperator t1) { dynamic dy = new MemberClass<ClassWithImplicitOperator>(); ClassWithImplicitOperator p2 = t1; return dy[dy, p2]; } } public class EmptyClass { } [Fact] public static void ImplicitOperator() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass002.genclass002 ClassWithImplicitOperator target = new ClassWithImplicitOperator(); EmptyClass result = target; //implicit Assert.Null(result); Assert.Equal(1, MemberClass<ClassWithImplicitOperator>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003 { // <Title> Tests generic class indexer used in implicit operator.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { public class ClassWithExplicitOperator { public byte field; public static explicit operator ClassWithExplicitOperator(byte t1) { dynamic dy = new MemberClass<int>(); dynamic[] p1 = null; ulong[] p2 = null; dynamic p3 = null; dy[p1, p2, p3] = (byte)10; return new ClassWithExplicitOperator { field = dy[p1, p2, p3] }; } } [Fact] public static void ExplicitOperator() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass003.genclass003 byte b = 1; ClassWithExplicitOperator result = (ClassWithExplicitOperator)b; Assert.Equal(3, result.field); Assert.Equal(1, MemberClass<int>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005 { // <Title> Tests generic class indexer used in using block and using expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.IO; public class Test { [Fact] public static void DynamicCSharpRunTest() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass005.genclass005 dynamic dy = new MemberClass<string>(); dynamic dy2 = new MemberClass<bool>(); string result = null; using (MemoryStream sm = new MemoryStream()) { using (StreamWriter sw = new StreamWriter(sm)) { sw.Write((string)(dy[string.Empty] ?? "Test")); sw.Flush(); sm.Position = 0; using (StreamReader sr = new StreamReader(sm, (bool)dy2[false])) { result = sr.ReadToEnd(); } } } Assert.Equal("Test", result); Assert.Equal(1, MemberClass<string>.Status); Assert.Equal(1, MemberClass<bool>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006 { // <Title> Tests generic class indexer used in the for-condition.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void ForStatement_MultipleParameters() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006 MemberClassMultipleParams<int, string, Test> mc = new MemberClassMultipleParams<int, string, Test>(); dynamic dy = mc; string u = null; Test v = null; int index1 = 10; for (int i = 10; i > dy[v, u]; i--) { index1--; } Assert.Equal(0, index1); Assert.Equal(1, MemberClassMultipleParams<int, string, Test>.Status); } [Fact] public void ForStatement_ClassConstraints() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass006.genclass006 dynamic dy = new MemberClassWithClassConstraint<Test>(); int index = 0; for (int i = 0; i < 10; i = i + dy[i]) { dy[i] = i; index++; } Assert.Equal(10, index); Assert.Equal(3, MemberClassWithClassConstraint<Test>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008 { // <Title> Tests generic class indexer used in the while/do expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void DoWhileExpression() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass008.genclass008 dynamic dy = new MemberClass<int>(); string p1 = null; float p2 = 1.23f; short[] p3 = null; int index = 0; do { index++; if (index == 10) break; } while (dy[p1, p2, p3] ?? true); Assert.Equal(10, index); Assert.Equal(1, MemberClass<int>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009 { // <Title> Tests generic class indexer used in switch expression.</Title> // <Description> Won't fix: no dynamic in switch expression </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void SwitchExpression() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass009.genclass009 dynamic dy = new MemberClass<int>(); bool isChecked = false; switch ((int)dy["Test"]) { case 0: isChecked = true; break; default: break; } Assert.True(isChecked); Assert.Equal(1, MemberClass<int>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010 { // <Title> Tests generic class indexer used in switch section statement list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void SwitchSectionStatementList() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass010.genclass010 dynamic dy = new MemberClass<int>(); string a = "Test"; MyClass p1 = new MyClass() { Field = 10 }; char? p2 = null; MyEnum[] p3 = new MyEnum[] { MyEnum.Second }; dynamic result = null; switch (a) { case "Test": dy[p1, p2, p3] = 10; result = dy[p1, p2, p3]; break; default: break; } Assert.Equal(10, ((MyClass)result).Field); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011 { // <Title> Tests generic class indexer used in switch default section statement list.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void SwitchDefaultSectionStatementList() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass011.genclass011 MemberClass<int> mc = new MemberClass<int>(); dynamic dy = mc; string a = "Test1"; MyClass p1 = new MyClass() { Field = 10 }; MyStruct? p2 = new MyStruct() { Number = 11 }; MyEnum[] p3 = new MyEnum[10]; dynamic[] result = null; switch (a) { case "Test": break; default: result = dy[p1, p2, p3]; dy[p1, p2, p3] = new dynamic[10]; break; } Assert.Equal(2, result.Length); Assert.Equal(10, ((MyClass)result[0]).Field); Assert.Equal(11, ((MyStruct)result[1]).Number); Assert.Equal(2, MemberClass<int>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass014.genclass014 { // <Title> Tests generic class indexer used in try/catch/finally.</Title> // <Description> // try/catch/finally that uses an anonymous method and refer two dynamic parameters. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; public class Test { [Fact] public static void TryCatchFinally() { dynamic dy = new MemberClass<int>(); dynamic result = -1; bool threwException = true; try { Func<string, dynamic> func = delegate (string x) { throw new TimeoutException(dy[x].ToString()); }; result = func("Test"); threwException = false; } catch (TimeoutException e) { Assert.Equal("0", e.Message); } finally { result = dy[new int?[3]]; } Assert.True(threwException); Assert.Equal(new int?[] { null, null, null }, result); Assert.Equal(1, MemberClass<int>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass015.genclass015 { // <Title> Tests generic class indexer used in iterator that calls to a lambda expression.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System; using System.Collections; public class Test { private static dynamic s_dy = new MemberClass<string>(); private static int s_num = 0; [Fact] [ActiveIssue(16747)] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod()); } public static int MainMethod() { dynamic t = new Test(); foreach (MyClass[] me in t.Increment()) { if (MemberClass<string>.Status != 1 || me.Length != 2) return 1; } return 0; } public IEnumerable Increment() { while (s_num++ < 4) { Func<MyEnum, MyClass[]> func = (MyEnum p1) => s_dy[p1]; yield return func((MyEnum)s_num); } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016 { // <Title> Tests generic class indexer used in object initializer inside a collection initializer.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Collections.Generic; public class Test { private string _field = string.Empty; [Fact] public static void ObjectInitializerInsideCollectionInitializer() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass016.genclass016 dynamic dy = new MemberClassWithClassConstraint<string>(); decimal dec = 123M; List<Test> list = new List<Test>() { new Test() { _field = dy[dec, dy] } }; Assert.Equal(1, list.Count); Assert.Null(list[0]._field); Assert.Equal(1, MemberClassWithClassConstraint<string>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017 { // <Title> Tests generic class indexer used in anonymous type.</Title> // <Description> // anonymous type inside a query expression that introduces dynamic variables. // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Linq; using System.Collections.Generic; public class Test { private int _field; public Test() { _field = 10; } [Fact] public static void AnonymousTypeInsideQueryExpression() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass017.genclass017 List<string> list = new List<string>() { "0", "4", null, "6", "4", "4", null }; dynamic dy = new MemberClassWithAnotherTypeConstraint<string, string>(); dynamic dy2 = new MemberClassWithNewConstraint<Test>(); Test t = new Test() { _field = 1 }; var result = list.Where(p => p == dy[dy2]).Select(p => new { A = dy2[t], B = dy[dy2] }).ToList(); Assert.Equal(2, result.Count); Assert.Equal(3, MemberClassWithAnotherTypeConstraint<string, string>.Status); Assert.Equal(1, MemberClassWithNewConstraint<Test>.Status); foreach (var m in result) { Assert.Equal(10, ((Test)m.A)._field); Assert.Null(m.B); } } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018 { // <Title> Tests generic class indexer used in static generic method body.</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void StaticGenericMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass018.genclass018 StaticGenericMethod<Test>(); } private static void StaticGenericMethod<T>() { dynamic dy = new MemberClassWithNewConstraint<MyClass>(); MyClass p1 = null; dy[p1] = dy; Assert.Equal(2, MemberClassWithNewConstraint<MyClass>.Status); dynamic p2 = dy[p1]; Assert.IsType<MyClass>(p2); Assert.Equal(1, MemberClassWithNewConstraint<MyClass>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020 { // <Title> Tests generic class indexer used in static method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test : C { private int _field; public Test() { _field = 11; } [Fact] public static void StaticMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass020.genclass020 dynamic dy = new MemberClassWithUDClassConstraint<Test>(); Test t = null; dy[t] = new C(); Assert.Equal(2, MemberClassWithUDClassConstraint<Test>.Status); t = new Test() { _field = 10 }; Test result = (Test)dy[t]; Assert.Equal(11, result._field); Assert.Equal(1, MemberClassWithUDClassConstraint<Test>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021 { // <Title> Tests generic class indexer used in static method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test { [Fact] public static void StaticMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass021.genclass021 dynamic dy = new MemberClassWithStructConstraint<char>(); dy[int.MinValue] = new Test(); Assert.Equal(2, MemberClassWithStructConstraint<char>.Status); dynamic result = dy[int.MaxValue]; Assert.Equal(int.MaxValue, result); Assert.Equal(1, MemberClassWithStructConstraint<char>.Status); } } //</Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022 { // <Title> Tests generic class indexer used in static method body.</Title> // <Description> // Negative // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public class Test : I { public class InnerTest : Test { } [Fact] public static void StaticMethodBody() { // ManagedTests.DynamicCSharp.Conformance.dynamic.context.indexer.genclass.genclass022.genclass022 dynamic dy = new MemberClassWithInterfaceConstraint<InnerTest>(); dy[int.MinValue, new InnerTest()] = new Test(); Assert.Equal(2, MemberClassWithInterfaceConstraint<InnerTest>.Status); dynamic result = dy[int.MaxValue, null]; Assert.Null(result); Assert.Equal(1, MemberClassWithInterfaceConstraint<InnerTest>.Status); } } //</Code> }
using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace xDockPanel { public abstract class DockPaneStripBase : Control { [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] protected internal class Tab : IDisposable { private IDockContent m_content; public Tab(IDockContent content) { m_content = content; } ~Tab() { Dispose(false); } public IDockContent Content { get { return m_content; } } public Form ContentForm { get { return m_content as Form; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] protected sealed class TabCollection : IEnumerable<Tab> { #region IEnumerable Members IEnumerator<Tab> IEnumerable<Tab>.GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } #endregion internal TabCollection(DockPane pane) { m_dockPane = pane; } private DockPane m_dockPane; public DockPane DockPane { get { return m_dockPane; } } public int Count { get { return DockPane.DisplayingContents.Count; } } public Tab this[int index] { get { IDockContent content = DockPane.DisplayingContents[index]; if (content == null) throw (new ArgumentOutOfRangeException("index")); return content.DockHandler.GetTab(DockPane.TabStripControl); } } public bool Contains(Tab tab) { return (IndexOf(tab) != -1); } public bool Contains(IDockContent content) { return (IndexOf(content) != -1); } public int IndexOf(Tab tab) { if (tab == null) return -1; return DockPane.DisplayingContents.IndexOf(tab.Content); } public int IndexOf(IDockContent content) { return DockPane.DisplayingContents.IndexOf(content); } } protected DockPaneStripBase(DockPane pane) { m_dockPane = pane; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.Selectable, false); AllowDrop = true; } private DockPane m_dockPane; protected DockPane DockPane { get { return m_dockPane; } } protected DockPane.AppearanceStyle Appearance { get { return DockPane.Appearance; } } private TabCollection m_tabs = null; protected TabCollection Tabs { get { if (m_tabs == null) m_tabs = new TabCollection(DockPane); return m_tabs; } } internal void RefreshChanges() { if (IsDisposed) return; OnRefreshChanges(); } protected virtual void OnRefreshChanges() { } protected internal abstract int MeasureHeight(); protected internal abstract void EnsureTabVisible(IDockContent content); protected int HitTest() { return HitTest(PointToClient(Control.MousePosition)); } protected internal abstract int HitTest(Point point); protected internal abstract GraphicsPath GetOutline(int index); protected internal virtual Tab CreateTab(IDockContent content) { return new Tab(content); } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); int index = HitTest(e.Location); if (index != -1) { if (e.Button == MouseButtons.Middle) { // Close the specified content. IDockContent content = Tabs[index].Content; DockPane.CloseContent(content); } else { IDockContent content = Tabs[index].Content; if (DockPane.ActiveContent != content) DockPane.ActiveContent = content; } } if (e.Button == MouseButtons.Left) { if (DockPane.AllowDockDragAndDrop) DockPane.DockPanel.BeginDrag(DockPane.ActiveContent.DockHandler); } } protected bool HasTabPageContextMenu { get { return DockPane.HasTabPageContextMenu; } } protected void ShowTabPageContextMenu(Point position) { DockPane.ShowTabPageContextMenu(this, position); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (e.Button == MouseButtons.Right) ShowTabPageContextMenu(new Point(e.X, e.Y)); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == (int)Win32.Msgs.WM_LBUTTONDBLCLK) { base.WndProc(ref m); int index = HitTest(); if (index != -1) { IDockContent content = Tabs[index].Content; if (content.DockHandler.CheckDockState(!content.DockHandler.IsFloat) != DockState.Unknown) content.DockHandler.IsFloat = !content.DockHandler.IsFloat; } return; } base.WndProc(ref m); return; } protected override void OnDragOver(DragEventArgs drgevent) { base.OnDragOver(drgevent); int index = HitTest(); if (index != -1) { IDockContent content = Tabs[index].Content; if (DockPane.ActiveContent != content) DockPane.ActiveContent = content; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Logging; namespace QuantConnect.Securities { /// <summary> /// Represents a holding of a currency in cash. /// </summary> public class Cash { private bool _isBaseCurrency; private bool _invertRealTimePrice; private readonly object _locker = new object(); /// <summary> /// Gets the symbol of the security required to provide conversion rates. /// </summary> public Symbol SecuritySymbol { get; private set; } /// <summary> /// Gets the symbol used to represent this cash /// </summary> public string Symbol { get; private set; } /// <summary> /// Gets or sets the amount of cash held /// </summary> public decimal Amount { get; private set; } /// <summary> /// Gets the conversion rate into account currency /// </summary> public decimal ConversionRate { get; internal set; } /// <summary> /// Gets the value of this cash in the accout currency /// </summary> public decimal ValueInAccountCurrency { get { return Amount*ConversionRate; } } /// <summary> /// Initializes a new instance of the <see cref="Cash"/> class /// </summary> /// <param name="symbol">The symbol used to represent this cash</param> /// <param name="amount">The amount of this currency held</param> /// <param name="conversionRate">The initial conversion rate of this currency into the <see cref="CashBook.AccountCurrency"/></param> public Cash(string symbol, decimal amount, decimal conversionRate) { if (symbol == null || symbol.Length != 3) { throw new ArgumentException("Cash symbols must be exactly 3 characters."); } Amount = amount; ConversionRate = conversionRate; Symbol = symbol.ToUpper(); } /// <summary> /// Updates this cash object with the specified data /// </summary> /// <param name="data">The new data for this cash object</param> public void Update(BaseData data) { if (_isBaseCurrency) return; var rate = data.Value; if (_invertRealTimePrice) { rate = 1/rate; } ConversionRate = rate; } /// <summary> /// Adds the specified amount of currency to this Cash instance and returns the new total. /// This operation is thread-safe /// </summary> /// <param name="amount">The amount of currency to be added</param> /// <returns>The amount of currency directly after the addition</returns> public decimal AddAmount(decimal amount) { lock (_locker) { Amount += amount; return Amount; } } /// <summary> /// Sets the Quantity to the specified amount /// </summary> /// <param name="amount">The amount to set the quantity to</param> public void SetAmount(decimal amount) { lock (_locker) { Amount = amount; } } /// <summary> /// Ensures that we have a data feed to convert this currency into the base currency. /// This will add a subscription at the lowest resolution if one is not found. /// </summary> /// <param name="securities">The security manager</param> /// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param> /// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param> /// <param name="symbolPropertiesDatabase">A symbol properties database instance</param> /// <param name="marketMap">The market map that decides which market the new security should be in</param> /// <param name="cashBook">The cash book - used for resolving quote currencies for created conversion securities</param> /// <returns>Returns the added currency security if needed, otherwise null</returns> public Security EnsureCurrencyDataFeed(SecurityManager securities, SubscriptionManager subscriptions, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase, IReadOnlyDictionary<SecurityType, string> marketMap, CashBook cashBook) { if (Symbol == CashBook.AccountCurrency) { SecuritySymbol = QuantConnect.Symbol.Empty; _isBaseCurrency = true; ConversionRate = 1.0m; return null; } // we require a subscription that converts this into the base currency string normal = Symbol + CashBook.AccountCurrency; string invert = CashBook.AccountCurrency + Symbol; foreach (var config in subscriptions.Subscriptions.Where(config => config.SecurityType == SecurityType.Forex || config.SecurityType == SecurityType.Cfd || config.SecurityType == SecurityType.Crypto)) { if (config.Symbol.Value == normal) { SecuritySymbol = config.Symbol; return null; } if (config.Symbol.Value == invert) { SecuritySymbol = config.Symbol; _invertRealTimePrice = true; return null; } } // if we've made it here we didn't find a subscription, so we'll need to add one // Create a SecurityType to Market mapping with the markets from SecurityManager members var markets = securities.Keys.GroupBy(x => x.SecurityType).ToDictionary(x => x.Key, y => y.First().ID.Market); if (markets.ContainsKey(SecurityType.Cfd) && !markets.ContainsKey(SecurityType.Forex)) { markets.Add(SecurityType.Forex, markets[SecurityType.Cfd]); } if (markets.ContainsKey(SecurityType.Forex) && !markets.ContainsKey(SecurityType.Cfd)) { markets.Add(SecurityType.Cfd, markets[SecurityType.Forex]); } var potentials = Currencies.CurrencyPairs.Select(fx => CreateSymbol(marketMap, fx, markets, SecurityType.Forex)) .Concat(Currencies.CfdCurrencyPairs.Select(cfd => CreateSymbol(marketMap, cfd, markets, SecurityType.Cfd))) .Concat(Currencies.CryptoCurrencyPairs.Select(crypto => CreateSymbol(marketMap, crypto, markets, SecurityType.Crypto))); var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(Resolution.Minute).Min(); var objectType = minimumResolution == Resolution.Tick ? typeof (Tick) : typeof (QuoteBar); foreach (var symbol in potentials) { if (symbol.Value == normal || symbol.Value == invert) { _invertRealTimePrice = symbol.Value == invert; var securityType = symbol.ID.SecurityType; var symbolProperties = symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol.Value, securityType, Symbol); Cash quoteCash; if (!cashBook.TryGetValue(symbolProperties.QuoteCurrency, out quoteCash)) { throw new Exception("Unable to resolve quote cash: " + symbolProperties.QuoteCurrency + ". This is required to add conversion feed: " + symbol.ToString()); } var marketHoursDbEntry = marketHoursDatabase.GetEntry(symbol.ID.Market, symbol.Value, symbol.ID.SecurityType); var exchangeHours = marketHoursDbEntry.ExchangeHours; // set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events var config = subscriptions.Add(objectType, TickType.Quote, symbol, minimumResolution, marketHoursDbEntry.DataTimeZone, exchangeHours.TimeZone, false, true, false, true); SecuritySymbol = config.Symbol; Security security; if (securityType == SecurityType.Cfd) { security = new Cfd.Cfd(exchangeHours, quoteCash, config, symbolProperties); } else if (securityType == SecurityType.Crypto) { security = new Crypto.Crypto(exchangeHours, quoteCash, config, symbolProperties); } else { security = new Forex.Forex(exchangeHours, quoteCash, config, symbolProperties); } securities.Add(config.Symbol, security); Log.Trace("Cash.EnsureCurrencyDataFeed(): Adding " + symbol.Value + " for cash " + Symbol + " currency feed"); return security; } } // if this still hasn't been set then it's an error condition throw new ArgumentException(string.Format("In order to maintain cash in {0} you are required to add a subscription for Forex pair {0}{1} or {1}{0}", Symbol, CashBook.AccountCurrency)); } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="QuantConnect.Securities.Cash"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="QuantConnect.Securities.Cash"/>.</returns> public override string ToString() { // round the conversion rate for output decimal rate = ConversionRate; rate = rate < 1000 ? rate.RoundToSignificantDigits(5) : Math.Round(rate, 2); return string.Format("{0}: {1,15} @ ${2,10} = {3}{4}", Symbol, Amount.ToString("0.00"), rate.ToString("0.00####"), Currencies.GetCurrencySymbol(Symbol), Math.Round(ValueInAccountCurrency, 2) ); } private static Symbol CreateSymbol(IReadOnlyDictionary<SecurityType, string> marketMap, string crypto, Dictionary<SecurityType, string> markets, SecurityType securityType) { string market; if (!markets.TryGetValue(securityType, out market)) { market = marketMap[securityType]; } return QuantConnect.Symbol.Create(crypto, securityType, market); } } }
using System; using System.Collections.Generic; using System.Text; using System.Text; using System.Runtime.InteropServices; using gView.Framework.Data; using gView.Framework.Geometry; using gView.SDEWrapper; namespace gView.Interoperability.Sde { internal class SdeQueryInfo : IDisposable { private SE_QUERYINFO _queryInfo = new SE_QUERYINFO(); private SE_SHAPE _shape = new SE_SHAPE(); private System.Int32 _err_no = 0; private string _errMsg = ""; private SE_FILTER _seFilter = new SE_FILTER(); private bool _isSpatial = false; private List<IField> _queryFields = new List<IField>(); public SdeQueryInfo(ArcSdeConnection connection, ITableClass tc, IQueryFilter filter) { if (tc == null) return; try { if (filter is ISpatialFilter && ((ISpatialFilter)filter).Geometry != null && tc is IFeatureClass && tc.Dataset is SdeDataset) { SE_ENVELOPE maxExtent = new SE_ENVELOPE(); SE_COORDREF coordRef = ((SdeDataset)tc.Dataset).GetSeCoordRef(connection, tc.Name, ((IFeatureClass)tc).ShapeFieldName, ref maxExtent); if (((SdeDataset)tc.Dataset).lastErrorMsg != "") return; _isSpatial = true; _err_no = Wrapper92.SE_shape_create(coordRef, ref _shape); ((SdeDataset)tc.Dataset).FreeSeCoordRef(coordRef); if (_err_no != 0) return; //IEnvelope env = ((ISpatialFilter)filter).Geometry.Envelope; //SE_ENVELOPE seEnvelope = new SE_ENVELOPE(); //seEnvelope.minx = Math.Max(env.minx, maxExtent.minx); //seEnvelope.miny = Math.Max(env.miny, maxExtent.miny); //seEnvelope.maxx = Math.Min(env.maxx, maxExtent.maxx); //seEnvelope.maxy = Math.Min(env.maxy, maxExtent.maxy); //if (seEnvelope.minx == seEnvelope.maxx && seEnvelope.miny == seEnvelope.maxy) //{ // /* fudge a rectangle so we have a valid one for generate_rectangle */ // /* FIXME: use the real shape for the query and set the filter_type // to be an appropriate type */ // seEnvelope.minx = seEnvelope.minx - 0.001; // seEnvelope.maxx = seEnvelope.maxx + 0.001; // seEnvelope.miny = seEnvelope.miny - 0.001; // seEnvelope.maxy = seEnvelope.maxy + 0.001; //} //_err_no = Wrapper92.SE_shape_generate_rectangle(ref seEnvelope, _shape); _err_no = gView.SDEWrapper.Functions.SE_GenerateGeometry(_shape, ((ISpatialFilter)filter).Geometry, maxExtent); if (_err_no != 0) return; _seFilter.shape = _shape; /* set spatial constraint column and table */ _seFilter.table = tc.Name.PadRight(CONST.SE_QUALIFIED_TABLE_NAME, '\0'); ; _seFilter.column = ((IFeatureClass)tc).ShapeFieldName.PadRight(CONST.SE_MAX_COLUMN_LEN, '\0'); /* set a couple of other spatial constraint properties */ _seFilter.method = (((ISpatialFilter)filter).SpatialRelation == spatialRelation.SpatialRelationEnvelopeIntersects) ? CONST.SM_ENVP_BY_GRID /*CONST.SM_AI*/ : CONST.SM_AI; _seFilter.filter_type = CONST.SE_SHAPE_FILTER; _seFilter.truth = true; // True; } _err_no = Wrapper92.SE_queryinfo_create(ref _queryInfo); if (_err_no != 0) return; _err_no = Wrapper92.SE_queryinfo_set_tables(_queryInfo, 1, new string[] { tc.Name }, null); if (_err_no != 0) return; string [] fields; if (filter.SubFields == "" || filter.SubFields == "*" || filter.SubFields == null) { StringBuilder subFields = new StringBuilder(); foreach (IField field in tc.Fields.ToEnumerable()) { if (subFields.Length != 0) subFields.Append(" "); subFields.Append(tc.Name + "." + field.name); _queryFields.Add(field); } fields=subFields.ToString().Split(' '); } else { fields=filter.SubFields.Split(' '); foreach (string fieldname in fields) { string fname = fieldname; if (fieldname.ToLower().IndexOf("distinct(") == 0) { fname = fieldname.Substring(9, fieldname.IndexOf(")") - 9); } IField field = tc.FindField(fname); if (field == null) { _errMsg = "Can't get Field " + fname; Cleanup(); return; } _queryFields.Add(field); } } _err_no = Wrapper92.SE_queryinfo_set_columns(_queryInfo, fields.Length, fields); if (_err_no != 0) return; string where = ""; if (filter != null) { if (filter is IRowIDFilter) { where = ((IRowIDFilter)filter).RowIDWhereClause; } else { where = filter.WhereClause; } } if (where != "") { _err_no = Wrapper92.SE_queryinfo_set_where_clause(_queryInfo, where); if (_err_no != 0) return; } _err_no = Wrapper92.SE_queryinfo_set_query_type(_queryInfo, CONST.SE_QUERYTYPE_JSFA); if (_err_no != 0) return; } catch (Exception ex) { _errMsg = "SeQueryInfo:" + ex.Message + "\n" + ex.StackTrace; _err_no = -1; } finally { if (_err_no != 0) { _errMsg = Wrapper92.GetErrorMsg(new SE_CONNECTION(), _err_no); Cleanup(); } } } private void Cleanup() { if (_shape.handle != 0) { Wrapper92.SE_shape_free(_shape); _shape.handle = 0; } if (_queryInfo.handle != 0) { Wrapper92.SE_queryinfo_free(_queryInfo); _queryInfo.handle = 0; } } public string ErrorMessage { get { return _errMsg; } } public SE_QUERYINFO SeQueryInfo { get { return _queryInfo; } } public bool IsSpatial { get { return _isSpatial; } } public SE_FILTER Filter_Shape { get { return _seFilter; } } public SE_FILTER Filter_Id { get { return _seFilter; } } public List<IField> QueryFields { get { return _queryFields; } } #region IDisposable Member public void Dispose() { Cleanup(); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for PacketCapturesOperations. /// </summary> public static partial class PacketCapturesOperationsExtensions { /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> public static PacketCaptureResult Create(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters) { return operations.CreateAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PacketCaptureResult> CreateAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.CreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a packet capture session by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> public static PacketCaptureResult Get(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { return operations.GetAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Gets a packet capture session by name. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PacketCaptureResult> GetAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> public static void Delete(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { operations.DeleteAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task DeleteAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.DeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> public static void Stop(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { operations.StopAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task StopAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.StopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> public static PacketCaptureQueryStatusResult GetStatus(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { return operations.GetStatusAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PacketCaptureQueryStatusResult> GetStatusAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Lists all packet capture sessions within the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> public static IEnumerable<PacketCaptureResult> List(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName) { return operations.ListAsync(resourceGroupName, networkWatcherName).GetAwaiter().GetResult(); } /// <summary> /// Lists all packet capture sessions within the specified resource group. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IEnumerable<PacketCaptureResult>> ListAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, networkWatcherName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> public static PacketCaptureResult BeginCreate(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters) { return operations.BeginCreateAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters).GetAwaiter().GetResult(); } /// <summary> /// Create and start a packet capture on the specified VM. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='parameters'> /// Parameters that define the create packet capture operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PacketCaptureResult> BeginCreateAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, PacketCapture parameters, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginCreateWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> public static void BeginDelete(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { operations.BeginDeleteAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginDeleteAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginDeleteWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> public static void BeginStop(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { operations.BeginStopAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Stops a specified packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the network watcher. /// </param> /// <param name='packetCaptureName'> /// The name of the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task BeginStopAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { (await operations.BeginStopWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)).Dispose(); } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> public static PacketCaptureQueryStatusResult BeginGetStatus(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName) { return operations.BeginGetStatusAsync(resourceGroupName, networkWatcherName, packetCaptureName).GetAwaiter().GetResult(); } /// <summary> /// Query the status of a running packet capture session. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='networkWatcherName'> /// The name of the Network Watcher resource. /// </param> /// <param name='packetCaptureName'> /// The name given to the packet capture session. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<PacketCaptureQueryStatusResult> BeginGetStatusAsync(this IPacketCapturesOperations operations, string resourceGroupName, string networkWatcherName, string packetCaptureName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.BeginGetStatusWithHttpMessagesAsync(resourceGroupName, networkWatcherName, packetCaptureName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System; using System.Runtime.InteropServices; #if IOS using MonoTouch.UIKit; using MonoTouch.Foundation; using MonoTouch.CoreFoundation; using MonoTouch.AudioToolbox; using MonoTouch.AudioUnit; using OpenTK.Audio.OpenAL; #elif MONOMAC using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreFoundation; using MonoMac.AudioToolbox; using MonoMac.AudioUnit; using MonoMac.OpenAL; #endif namespace Microsoft.Xna.Framework.Audio { internal static class OpenALSupport { public static ExtAudioFile GetExtAudioFile (NSUrl url, out AudioStreamBasicDescription audioDescription) { // Notice the following line that we can not pass a NSUrl to a CFUrl //ExtAudioFile ext = ExtAudioFile.OpenUrl(url); // Basic Descriptions AudioStreamBasicDescription fileFormat; AudioStreamBasicDescription outputFormat; // So now we create a CFUrl CFUrl curl = CFUrl.FromFile (url.Path); // Open the file ExtAudioFile ext = ExtAudioFile.OpenUrl (curl); // Get the audio format fileFormat = ext.FileDataFormat; // Don't know how to handle sounds with more than 2 channels (i.e. stereo) // Remember that OpenAL sound effects must be mono to be spatialized anyway. if (fileFormat.ChannelsPerFrame > 2) { #if DEBUG Console.WriteLine ("Unsupported Format: Channel count [0] is greater than stereo.", fileFormat.ChannelsPerFrame); #endif audioDescription = new AudioStreamBasicDescription(); return null; } // The output format must be linear PCM because that's the only type OpenAL knows how to deal with. // Set the client format to 16 bit signed integer (native-endian) data because that is the most // optimal format on iPhone/iPod Touch hardware. // Maintain the channel count and sample rate of the original source format. outputFormat = new AudioStreamBasicDescription (); // Create our output format description to be converted to outputFormat.SampleRate = fileFormat.SampleRate; // Preserve the original sample rate outputFormat.ChannelsPerFrame = fileFormat.ChannelsPerFrame; // Preserve the orignal number of channels outputFormat.Format = AudioFormatType.LinearPCM; // We want Linear PCM // IsBigEndian is causing some problems with distorted sounds on MacOSX // outputFormat.FormatFlags = AudioFormatFlags.IsBigEndian // | AudioFormatFlags.IsPacked // | AudioFormatFlags.IsSignedInteger; outputFormat.FormatFlags = AudioFormatFlags.IsPacked | AudioFormatFlags.IsSignedInteger; outputFormat.FramesPerPacket = 1; // We know for linear PCM, the definition is 1 frame per packet outputFormat.BitsPerChannel = 16; // We know we want 16-bit outputFormat.BytesPerPacket = 2 * outputFormat.ChannelsPerFrame; // We know we are using 16-bit, so 2-bytes per channel per frame outputFormat.BytesPerFrame = 2 * outputFormat.ChannelsPerFrame; // For PCM, since 1 frame is 1 packet, it is the same as mBytesPerPacket // Set the desired client (output) data format ext.ClientDataFormat = outputFormat; // Copy the output format to the audio description that was passed in so the // info will be returned to the user. audioDescription = outputFormat; return ext; } public static bool GetDataFromExtAudioFile (ExtAudioFile ext, AudioStreamBasicDescription outputFormat, int maxBufferSize, byte[] dataBuffer, out int dataBufferSize, out ALFormat format, out double sampleRate) { int errorStatus = 0; int bufferSizeInFrames = 0; dataBufferSize = 0; format = ALFormat.Mono16; sampleRate = 0; /* Compute how many frames will fit into our max buffer size */ bufferSizeInFrames = maxBufferSize / outputFormat.BytesPerFrame; if (dataBuffer != null) { MutableAudioBufferList audioBufferList = new MutableAudioBufferList (1, maxBufferSize); audioBufferList.Buffers [0].DataByteSize = maxBufferSize; audioBufferList.Buffers [0].NumberChannels = outputFormat.ChannelsPerFrame; // This a hack so if there is a problem speak to kjpou1 -Kenneth // the cleanest way is to copy the buffer to the pointer already allocated // but what we are going to do is replace the pointer with our own and restore it later // GCHandle meBePinned = GCHandle.Alloc (dataBuffer, GCHandleType.Pinned); IntPtr meBePointer = meBePinned.AddrOfPinnedObject (); // Let's not use copy for right now while we test this. For very large files this // might show some stutter in the sound loading //Marshal.Copy(dataBuffer, 0, audioBufferList.Buffers[0].Data, maxBufferSize); IntPtr savedDataPtr = audioBufferList.Buffers [0].Data; audioBufferList.Buffers [0].Data = meBePointer; try { // Read the data into an AudioBufferList // errorStatus here returns back the amount of information read errorStatus = ext.Read (bufferSizeInFrames, audioBufferList); if (errorStatus >= 0) { /* Success */ /* Note: 0 == bufferSizeInFrames is a legitimate value meaning we are EOF. */ /* ExtAudioFile.Read returns the number of frames actually read. * Need to convert back to bytes. */ dataBufferSize = bufferSizeInFrames * outputFormat.BytesPerFrame; // Now we set our format format = outputFormat.ChannelsPerFrame > 1 ? ALFormat.Stereo16 : ALFormat.Mono16; sampleRate = outputFormat.SampleRate; } else { #if DEBUG Console.WriteLine ("ExtAudioFile.Read failed, Error = " + errorStatus); #endif return false; } } catch (Exception exc) { #if DEBUG Console.WriteLine ("ExtAudioFile.Read failed: " + exc.Message); #endif return false; } finally { // Don't forget to free our dataBuffer memory pointer that was pinned above meBePinned.Free (); // and restore what was allocated to beginwith audioBufferList.Buffers[0].Data = savedDataPtr; } } return true; } /** * Returns a byte buffer containing all the pcm data. */ public static byte[] GetOpenALAudioDataAll (NSUrl file_url, out int dataBufferSize, out ALFormat alFormat, out double sampleRate, out double duration) { long fileLengthInFrames = 0; AudioStreamBasicDescription outputFormat; int maxBufferSize; byte[] pcmData; dataBufferSize = 0; alFormat = 0; sampleRate = 0; duration = 0; ExtAudioFile extFile; try { extFile = GetExtAudioFile (file_url, out outputFormat); } catch (Exception extExc) { #if DEBUG Console.WriteLine ("ExtAudioFile.OpenUrl failed, Error : " + extExc.Message); #endif return null; } /* Get the total frame count */ try { fileLengthInFrames = extFile.FileLengthFrames; } catch (Exception exc) { #if DEBUG Console.WriteLine ("ExtAudioFile.FileLengthFranes failed, Error : " + exc.Message); #endif return null; } /* Compute the number of bytes needed to hold all the data in the file. */ maxBufferSize = (int)(fileLengthInFrames * outputFormat.BytesPerFrame); /* Allocate memory to hold all the decoded PCM data. */ pcmData = new byte[maxBufferSize]; bool gotData = GetDataFromExtAudioFile (extFile, outputFormat, maxBufferSize, pcmData, out dataBufferSize, out alFormat, out sampleRate); if (!gotData) { pcmData = null; } duration = (dataBufferSize / ((outputFormat.BitsPerChannel / 8) * outputFormat.ChannelsPerFrame)) / outputFormat.SampleRate; // we probably should make sure the buffer sizes are in accordance. // assert(maxBufferSize == dataBufferSize); // We do not need the ExtAudioFile so we will set it to null extFile = null; return pcmData; } public static byte[] LoadFromFile (string filename, out int dataBufferSize, out ALFormat alFormat, out double sampleRate, out double duration) { return OpenALSupport.GetOpenALAudioDataAll (NSUrl.FromFilename (filename), out dataBufferSize, out alFormat, out sampleRate, out duration); } } }
// 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; using System.IO; using System.Text; using XmlCoreTest.Common; namespace System.Xml.Tests { [InheritRequired()] public abstract partial class TCReadContentAsBinHex : TCXMLReaderBaseGeneral { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public static string BinHexXml = "BinHex.xml"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.BINHEX_TEST); return ret; } public override int Terminate(object objParam) { if (DataReader.Internal != null) { while (DataReader.Read()) ; DataReader.Close(); } return base.Terminate(objParam); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return true; try { DataReader.ReadContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { CError.WriteLine("Actual exception:{0}", e.GetType().ToString()); CError.WriteLine("Expected exception:{0}", exceptionType.ToString()); bPassed = (e.GetType().ToString() == exceptionType.ToString()); } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } [Variation("ReadBinHex Element with all valid value")] public int TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; binhexlen = DataReader.ReadContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } CError.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Num value", Pri = 0)] public int TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME3); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Text value")] public int TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); return TEST_PASS; } public void Dump(byte[] bytes) { for (int i = 0; i < bytes.Length; i++) { CError.WriteLineIgnore("Byte" + i + ": " + bytes[i]); } } [Variation("ReadBinHex Element on CDATA", Pri = 0)] public int TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; string xmlStr = "<root><![CDATA[ABCDEF]]></root>"; ReloadSource(new StringReader(xmlStr)); DataReader.PositionOnElement("root"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 3, "BinHex"); BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 0, "BinHex"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.None, "Not on none"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0")] public int TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME5); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all long valid value (from concatenation)")] public int TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME6); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); CError.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex with count > buffer size")] public int TestReadBinHex_7() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with count < 0")] public int TestReadBinHex_8() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index > buffer size")] public int vReadBinHex_9() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index < 0")] public int TestReadBinHex_10() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index + count exceeds buffer")] public int TestReadBinHex_11() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex index & count =0")] public int TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { iCount = DataReader.ReadContentAsBinHex(buffer, 0, 0); } catch (Exception e) { CError.WriteLine(e.ToString()); return TEST_FAIL; } CError.Compare(iCount, 0, "has to be zero"); return TEST_PASS; } [Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0")] public int TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); CError.WriteLine("Actual: " + strActbinhex + " Exp: " + strTextBinHex); CError.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } return TEST_PASS; } [Variation("ReadBinHex with buffer == null")] public int TestReadBinHex_14() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return TEST_PASS; } return TEST_FAIL; } [Variation("Read after partial ReadBinHex")] public int TestReadBinHex_16() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[10]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 8); CError.Compare(nRead, 8, "0"); DataReader.Read(); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, "ElemText", String.Empty), "1vn"); return TEST_PASS; } [Variation("Current node on multiple calls")] public int TestReadBinHex_17() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[30]; int nRead = DataReader.ReadContentAsBinHex(buffer, 0, 2); CError.Compare(nRead, 2, "0"); nRead = DataReader.ReadContentAsBinHex(buffer, 0, 19); CError.Compare(nRead, 18, "1"); CError.Compare(DataReader.VerifyNode(XmlNodeType.EndElement, "ElemNum", String.Empty), "1vn"); return TEST_PASS; } [Variation("ReadBinHex with whitespaces")] public int TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex with odd number of chars")] public int TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex when end tag doesn't exist")] public int TestTextReadBinHex_23() { if (IsRoundTrippedReader()) return TEST_SKIPPED; byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("B"); DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadContentAsBinHex(buffer, 0, 5000); CError.WriteLine("Accepted incomplete element"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } return TEST_PASS; } [Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")] public int TestTextReadBinHex_24() { string filename = TestData + "Common/Bug99148.xml"; ReloadSource(filename); DataReader.MoveToContent(); int bytes = -1; DataReader.Read(); if (CheckCanReadBinaryContent()) return TEST_PASS; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { CError.Write(bbb[i].ToString()); output.AppendFormat(bbb[i].ToString()); } } CError.WriteLine(); CError.WriteLine("Length of the output : " + output.ToString().Length); return (CError.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) ? TEST_PASS : TEST_FAIL; } } [InheritRequired()] public abstract partial class TCReadElementContentAsBinHex : TCXMLReaderBaseGeneral { public const string ST_ELEM_NAME1 = "ElemAll"; public const string ST_ELEM_NAME2 = "ElemEmpty"; public const string ST_ELEM_NAME3 = "ElemNum"; public const string ST_ELEM_NAME4 = "ElemText"; public const string ST_ELEM_NAME5 = "ElemNumText"; public const string ST_ELEM_NAME6 = "ElemLong"; public static string BinHexXml = "BinHex.xml"; public const string strTextBinHex = "ABCDEF"; public const string strNumBinHex = "0123456789"; public override int Init(object objParam) { int ret = base.Init(objParam); CreateTestFile(EREADER_TYPE.BINHEX_TEST); return ret; } public override int Terminate(object objParam) { DataReader.Close(); return base.Terminate(objParam); } private bool VerifyInvalidReadBinHex(int iBufferSize, int iIndex, int iCount, Type exceptionType) { bool bPassed = false; byte[] buffer = new byte[iBufferSize]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return true; try { DataReader.ReadElementContentAsBinHex(buffer, iIndex, iCount); } catch (Exception e) { CError.WriteLine("Actual exception:{0}", e.GetType().ToString()); CError.WriteLine("Expected exception:{0}", exceptionType.ToString()); bPassed = (e.GetType().ToString() == exceptionType.ToString()); } return bPassed; } protected void TestInvalidNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); string name = DataReader.Name; string value = DataReader.Value; byte[] buffer = new byte[1]; if (CheckCanReadBinaryContent()) return; try { int nBytes = DataReader.ReadElementContentAsBinHex(buffer, 0, 1); } catch (InvalidOperationException) { return; } CError.Compare(false, "Invalid OP exception not thrown on wrong nodetype"); } [Variation("ReadBinHex Element with all valid value")] public int TestReadBinHex_1() { int binhexlen = 0; byte[] binhex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return TEST_PASS; binhexlen = DataReader.ReadElementContentAsBinHex(binhex, 0, binhex.Length); string strActbinhex = ""; for (int i = 0; i < binhexlen; i = i + 2) { strActbinhex += System.BitConverter.ToChar(binhex, i); } CError.Compare(strActbinhex, (strNumBinHex + strTextBinHex), "1. Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Num value", Pri = 0)] public int TestReadBinHex_2() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME3); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strNumBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid Text value")] public int TestReadBinHex_3() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, strTextBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with Comments and PIs", Pri = 0)] public int TestReadBinHex_4() { int BinHexlen = 0; byte[] BinHex = new byte[3]; ReloadSource(new StringReader("<root>AB<!--Comment-->CD<?pi target?>EF</root>")); DataReader.PositionOnElement("root"); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); CError.Compare(BinHexlen, 3, "BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all valid value (from concatenation), Pri=0")] public int TestReadBinHex_5() { int BinHexlen = 0; byte[] BinHex = new byte[1000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME5); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } CError.Compare(strActBinHex, (strNumBinHex + strTextBinHex), "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex Element with all long valid value (from concatenation)")] public int TestReadBinHex_6() { int BinHexlen = 0; byte[] BinHex = new byte[2000]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME6); if (CheckCanReadBinaryContent()) return TEST_PASS; BinHexlen = DataReader.ReadElementContentAsBinHex(BinHex, 0, BinHex.Length); string strActBinHex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { strActBinHex += System.BitConverter.ToChar(BinHex, i); } string strExpBinHex = ""; for (int i = 0; i < 10; i++) strExpBinHex += (strNumBinHex + strTextBinHex); CError.Compare(strActBinHex, strExpBinHex, "Compare All Valid BinHex"); return TEST_PASS; } [Variation("ReadBinHex with count > buffer size")] public int TestReadBinHex_7() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 6, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with count < 0")] public int TestReadBinHex_8() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 2, -1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index > buffer size")] public int vReadBinHex_9() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 5, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index < 0")] public int TestReadBinHex_10() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, -1, 1, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex with index + count exceeds buffer")] public int TestReadBinHex_11() { return BoolToLTMResult(VerifyInvalidReadBinHex(5, 0, 10, typeof(ArgumentOutOfRangeException))); } [Variation("ReadBinHex index & count =0")] public int TestReadBinHex_12() { byte[] buffer = new byte[5]; int iCount = 0; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME1); if (CheckCanReadBinaryContent()) return TEST_PASS; try { iCount = DataReader.ReadElementContentAsBinHex(buffer, 0, 0); } catch (Exception e) { CError.WriteLine(e.ToString()); return TEST_FAIL; } CError.Compare(iCount, 0, "has to be zero"); return TEST_PASS; } [Variation("ReadBinHex Element multiple into same buffer (using offset), Pri=0")] public int TestReadBinHex_13() { int BinHexlen = 10; byte[] BinHex = new byte[BinHexlen]; ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; string strActbinhex = ""; for (int i = 0; i < BinHexlen; i = i + 2) { DataReader.ReadElementContentAsBinHex(BinHex, i, 2); strActbinhex = (System.BitConverter.ToChar(BinHex, i)).ToString(); CError.WriteLine("Actual: " + strActbinhex + " Exp: " + strTextBinHex); CError.Compare(String.Compare(strActbinhex, 0, strTextBinHex, i / 2, 1), 0, "Compare All Valid Base64"); } return TEST_PASS; } [Variation("ReadBinHex with buffer == null")] public int TestReadBinHex_14() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement(ST_ELEM_NAME4); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(null, 0, 0); } catch (ArgumentNullException) { return TEST_PASS; } return TEST_FAIL; } [Variation("Read after partial ReadBinHex")] public int TestReadBinHex_16() { ReloadSource(EREADER_TYPE.BINHEX_TEST); DataReader.PositionOnElement("ElemNum"); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[10]; int nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 8); CError.Compare(nRead, 8, "0"); DataReader.Read(); CError.Compare(DataReader.NodeType, XmlNodeType.Text, "Not on text node"); return TEST_PASS; } [Variation("No op node types")] public int TestReadBinHex_18() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; TestInvalidNodeType(XmlNodeType.Text); TestInvalidNodeType(XmlNodeType.Attribute); TestInvalidNodeType(XmlNodeType.Whitespace); TestInvalidNodeType(XmlNodeType.ProcessingInstruction); TestInvalidNodeType(XmlNodeType.CDATA); if (!(IsCoreReader() || IsRoundTrippedReader())) { TestInvalidNodeType(XmlNodeType.EndEntity); TestInvalidNodeType(XmlNodeType.EntityReference); } return TEST_PASS; } [Variation("ReadBinHex with whitespaces")] public int TestTextReadBinHex_21() { byte[] buffer = new byte[1]; string strxml = "<abc> 1 1 B </abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex with odd number of chars")] public int TestTextReadBinHex_22() { byte[] buffer = new byte[1]; string strxml = "<abc>11B</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; int result = 0; int nRead; while ((nRead = DataReader.ReadElementContentAsBinHex(buffer, 0, 1)) > 0) result += nRead; CError.Compare(result, 1, "res"); CError.Compare(buffer[0], (byte)17, "buffer[0]"); return TEST_PASS; } [Variation("ReadBinHex when end tag doesn't exist")] public int TestTextReadBinHex_23() { if (IsRoundTrippedReader()) return TEST_SKIPPED; byte[] buffer = new byte[5000]; string strxml = "<B>" + new string('A', 5000); ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("B"); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(buffer, 0, 5000); CError.WriteLine("Accepted incomplete element"); return TEST_FAIL; } catch (XmlException e) { CheckXmlException("Xml_UnexpectedEOFInElementContent", e, 1, 5004); } return TEST_PASS; } [Variation("WS:WireCompat:hex binary fails to send/return data after 1787 bytes")] public int TestTextReadBinHex_24() { string filename = TestData + "Common/Bug99148.xml"; ReloadSource(filename); DataReader.MoveToContent(); if (CheckCanReadBinaryContent()) return TEST_PASS; int bytes = -1; StringBuilder output = new StringBuilder(); while (bytes != 0) { byte[] bbb = new byte[1024]; bytes = DataReader.ReadElementContentAsBinHex(bbb, 0, bbb.Length); for (int i = 0; i < bytes; i++) { CError.Write(bbb[i].ToString()); output.AppendFormat(bbb[i].ToString()); } } CError.WriteLine(); CError.WriteLine("Length of the output : " + output.ToString().Length); return (CError.Compare(output.ToString().Length, 1735, "Expected Length : 1735")) ? TEST_PASS : TEST_FAIL; } [Variation("430329: SubtreeReader inserted attributes don't work with ReadContentAsBinHex")] public int TestReadBinHex_430329() { if (IsCustomReader() || IsXsltReader() || IsBinaryReader()) return TEST_SKIPPED; string strxml = "<root xmlns='0102030405060708090a0B0c'><bar/></root>"; ReloadSource(new StringReader(strxml)); DataReader.Read(); DataReader.Read(); using (XmlReader sr = DataReader.ReadSubtree()) { sr.Read(); sr.MoveToFirstAttribute(); sr.MoveToFirstAttribute(); byte[] bytes = new byte[4]; while ((sr.ReadContentAsBinHex(bytes, 0, bytes.Length)) > 0) { if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } } DataReader.Close(); return TEST_PASS; } [Variation("ReadBinHex with = in the middle")] public int TestReadBinHex_27() { byte[] buffer = new byte[1]; string strxml = "<abc>1=2</abc>"; ReloadSource(new StringReader(strxml)); DataReader.PositionOnElement("abc"); if (CheckCanReadBinaryContent()) return TEST_PASS; try { DataReader.ReadElementContentAsBinHex(buffer, 0, 1); CError.Compare(false, "ReadBinHex with = in the middle succeeded"); } catch (XmlException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("ReadBinHex runs into an Overflow", Params = new object[] { "1000000" })] //[Variation("ReadBinHex runs into an Overflow", Params = new object[] { "10000000" })] public int TestReadBinHex_105376() { int totalfilesize = Convert.ToInt32(CurVariation.Params[0].ToString()); CError.WriteLine(" totalfilesize = " + totalfilesize); string ascii = new string('c', totalfilesize); byte[] bits = Encoding.Unicode.GetBytes(ascii); CError.WriteLineIgnore("Count = " + bits.Length); string base64str = Convert.ToBase64String(bits); string fileName = "bug105376c_" + CurVariation.Params[0].ToString() + ".xml"; MemoryStream mems = new MemoryStream(); StreamWriter sw = new StreamWriter(mems); sw.Write("<root><base64>"); sw.Write(base64str); sw.Write("</base64></root>"); sw.Flush();//sw.Close(); FilePathUtil.addStream(fileName, mems); ReloadSource(fileName); int SIZE = (totalfilesize - 30); int SIZE64 = SIZE * 3 / 4; DataReader.PositionOnElement("base64"); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] base64 = new byte[SIZE64]; try { DataReader.ReadElementContentAsBinHex(base64, 0, 4096); return TEST_FAIL; } catch (XmlException) { DataReader.Close(); return TEST_PASS; } finally { DataReader.Close(); } } [Variation("call ReadContentAsBinHex on two or more nodes")] public int TestReadBinHex_28() { string xml = "<elem0> 11B <elem1> 11B <elem2> 11B </elem2> 11B </elem1> 11B </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)17, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } [Variation("read BinHex over invalid text node")] public int TestReadBinHex_29() { string xml = "<elem0>12%45<elem1>12%45<elem2>12%45</elem2>12%45</elem1>12%45</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[5]; int currentSize = 0; while (DataReader.Read()) { DataReader.Read(); try { currentSize = DataReader.ReadContentAsBinHex(buffer, 0, 5); if (!(IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader())) return TEST_FAIL; } catch (XmlException) { CError.Compare(currentSize, 0, "size"); } } DataReader.Close(); return TEST_PASS; } [Variation("goto to text node, ask got.Value, readcontentasBinHex")] public int TestReadBinHex_30() { string xml = "<elem0>123</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; DataReader.Read(); DataReader.Read(); CError.Compare(DataReader.Value, "123", "value"); CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 1), 1, "size"); DataReader.Close(); return TEST_PASS; } [Variation("goto to text node, readcontentasBinHex, ask got.Value")] public int TestReadBinHex_31() { string xml = "<elem0>123</elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; DataReader.Read(); DataReader.Read(); CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 1), 1, "size"); CError.Compare(DataReader.Value, (IsCharCheckingReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsXPathNavigatorReader()) ? "123" : "3", "value"); DataReader.Close(); return TEST_PASS; } [Variation("goto to huge text node, read several chars with ReadContentAsBinHex and Move forward with .Read()")] public int TestReadBinHex_32() { string xml = "<elem0>1234567 89 1234 123345 5676788 5567712 34567 89 1234 123345 5676788 55677</elem0>"; ReloadSource(new StringReader(xml)); byte[] buffer = new byte[5]; DataReader.Read(); DataReader.Read(); try { CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 5), 5, "size"); } catch (NotSupportedException) { return TEST_PASS; } DataReader.Read(); DataReader.Close(); return TEST_PASS; } [Variation("goto to huge text node with invalid chars, read several chars with ReadContentAsBinHex and Move forward with .Read()")] public int TestReadBinHex_33() { string xml = "<elem0>123 $^ 56789 abcdefg hij klmn opqrst 12345 uvw xy ^ z</elem0>"; ReloadSource(new StringReader(xml)); byte[] buffer = new byte[5]; DataReader.Read(); DataReader.Read(); try { CError.Compare(DataReader.ReadContentAsBinHex(buffer, 0, 5), 5, "size"); DataReader.Read(); } catch (XmlException) { return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } //[Variation("ReadContentAsBinHex on an xmlns attribute", Param = "<foo xmlns='default'> <bar > id='1'/> </foo>")] //[Variation("ReadContentAsBinHex on an xmlns:k attribute", Param = "<k:foo xmlns:k='default'> <k:bar id='1'/> </k:foo>")] //[Variation("ReadContentAsBinHex on an xml:space attribute", Param = "<foo xml:space='default'> <bar > id='1'/> </foo>")] //[Variation("ReadContentAsBinHex on an xml:lang attribute", Param = "<foo xml:lang='default'> <bar > id='1'/> </foo>")] public int TestBinHex_34() { string xml = (string)CurVariation.Param; byte[] buffer = new byte[8]; try { ReloadSource(new StringReader(xml)); DataReader.Read(); if (IsBinaryReader()) DataReader.Read(); DataReader.MoveToAttribute(0); CError.Compare(DataReader.Value, "default", "value"); CError.Equals(DataReader.ReadContentAsBinHex(buffer, 0, 8), 5, "size"); CError.Equals(false, "No exception"); } catch (XmlException) { return TEST_PASS; } catch (NotSupportedException) { return TEST_PASS; } finally { DataReader.Close(); } return TEST_FAIL; } [Variation("call ReadContentAsBinHex on two or more nodes and whitespace")] public int TestReadBinHex_35() { string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123 <elem2> 123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)18, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } [Variation("call ReadContentAsBinHex on two or more nodes and whitespace after call Value")] public int TestReadBinHex_36() { string xml = @"<elem0> 123" + "\n" + @" <elem1>" + "\r" + @"123 <elem2> 123 </elem2>" + "\r\n" + @" 123</elem1> 123 </elem0>"; ReloadSource(new StringReader(xml)); if (CheckCanReadBinaryContent()) return TEST_PASS; byte[] buffer = new byte[3]; int startPos = 0; int readSize = 3; int currentSize = 0; DataReader.Read(); while (DataReader.Read()) { CError.Equals(DataReader.Value.Contains("123"), "Value"); currentSize = DataReader.ReadContentAsBinHex(buffer, startPos, readSize); CError.Equals(currentSize, 1, "size"); CError.Equals(buffer[0], (byte)18, "buffer"); if (!(IsXPathNavigatorReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc())) { CError.WriteLine("LineNumber" + DataReader.LineNumber); CError.WriteLine("LinePosition" + DataReader.LinePosition); } } DataReader.Close(); return TEST_PASS; } } }
/* * HtmlControlConverter.cs * * Copyright ?2007 Michael Schwarz (http://www.ajaxpro.info). * 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. */ /* * MS 06-05-23 using local variables instead of "new Type()" for get De-/SerializableTypes * MS 06-09-26 improved performance using StringBuilder * * */ using System; using System.Web; using System.Web.UI; using System.Web.UI.HtmlControls; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace AjaxPro { /// <summary> /// Provides methods to serialize and deserialize an object that is inherited from HtmlControl. /// </summary> public class HtmlControlConverter : IJavaScriptConverter { /// <summary> /// Initializes a new instance of the <see cref="HtmlControlConverter"/> class. /// </summary> public HtmlControlConverter() : base() { m_serializableTypes = new Type[] { typeof(HtmlControl), typeof(HtmlAnchor), typeof(HtmlButton), typeof(HtmlImage), typeof(HtmlInputButton), typeof(HtmlInputCheckBox), typeof(HtmlInputRadioButton), typeof(HtmlInputText), typeof(HtmlSelect), typeof(HtmlTableCell), typeof(HtmlTable), typeof(HtmlTableRow), typeof(HtmlTextArea) }; m_deserializableTypes = new Type[] { typeof(HtmlControl), typeof(HtmlAnchor), typeof(HtmlButton), typeof(HtmlImage), typeof(HtmlInputButton), typeof(HtmlInputCheckBox), typeof(HtmlInputRadioButton), typeof(HtmlInputText), typeof(HtmlSelect), typeof(HtmlTableCell), typeof(HtmlTable), typeof(HtmlTableRow), typeof(HtmlTextArea) }; } /// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { if(!typeof(HtmlControl).IsAssignableFrom(t) || !(o is JavaScriptString)) throw new NotSupportedException(); return HtmlControlFromString(o.ToString(), t); } /// <summary> /// Converts a .NET object into a JSON string. /// </summary> /// <param name="o">The object to convert.</param> /// <returns>Returns a JSON string.</returns> public override string Serialize(object o) { StringBuilder sb = new StringBuilder(); Serialize(o, sb); return sb.ToString(); } /// <summary> /// Serializes the specified o. /// </summary> /// <param name="o">The o.</param> /// <param name="sb">The sb.</param> public override void Serialize(object o, StringBuilder sb) { if(!(o is Control)) throw new NotSupportedException(); sb.Append(HtmlControlToString((HtmlControl)o)); } #region Internal Methods /// <summary> /// Corrects the attributes. /// </summary> /// <param name="input">The input.</param> /// <returns></returns> internal static string CorrectAttributes(string input) { string s = @"selected=""selected"""; Regex r = new Regex(s, RegexOptions.Singleline | RegexOptions.IgnoreCase); input = r.Replace(input, @"selected=""true"""); s = @"multiple=""multiple"""; r = new Regex(s, RegexOptions.Singleline | RegexOptions.IgnoreCase); input = r.Replace(input, @"multiple=""true"""); s = @"disabled=""disabled"""; r = new Regex(s, RegexOptions.Singleline | RegexOptions.IgnoreCase); input = r.Replace(input, @"disabled=""true"""); return input; } /// <summary> /// HTMLs the control to string. /// </summary> /// <param name="control">The control.</param> /// <returns></returns> internal static string HtmlControlToString(HtmlControl control) { StringWriter writer = new StringWriter(new StringBuilder()); control.RenderControl(new HtmlTextWriter(writer)); return JavaScriptSerializer.Serialize(writer.ToString()); } /// <summary> /// HTMLs the control from string. /// </summary> /// <param name="html">The HTML.</param> /// <param name="type">The type.</param> /// <returns></returns> internal static HtmlControl HtmlControlFromString(string html, Type type) { if(!typeof(HtmlControl).IsAssignableFrom(type)) throw new InvalidCastException("The target type is not a HtmlControlType"); html = AddRunAtServer(html, (Activator.CreateInstance(type) as HtmlControl).TagName); if(type.IsAssignableFrom(typeof(HtmlSelect))) html = CorrectAttributes(html); Control o = HtmlControlConverterHelper.Parse(html);; if(o.GetType() == type) return (o as HtmlControl); else { foreach(Control con in o.Controls) { if(con.GetType() == type) { return (con as HtmlControl); } } } return null; } /// <summary> /// Adds the run at server. /// </summary> /// <param name="input">The input.</param> /// <param name="tagName">Name of the tag.</param> /// <returns></returns> internal static string AddRunAtServer(string input, string tagName) { // <select[^>]*?(?<InsertPos>\s*)> string pattern = "<" + Regex.Escape(tagName) + @"[^>]*?(?<InsertPos>\s*)/?>"; Regex regEx = new Regex(pattern, RegexOptions.Singleline | RegexOptions.IgnoreCase); Match match = regEx.Match(input); if (match.Success) { Group group = match.Groups["InsertPos"]; return input.Insert(group.Index + group.Length, " runat=\"server\""); } else return input; } #endregion } internal class HtmlControlConverterHelper : TemplateControl { /// <summary> /// Parses the specified control string. /// </summary> /// <param name="controlString">The control string.</param> /// <returns></returns> internal static Control Parse(string controlString) { HtmlControlConverterHelper control = new HtmlControlConverterHelper(); #if(NET20) control.AppRelativeVirtualPath = "~"; #endif return control.ParseControl(controlString); } } }
using System.Globalization; using System.Reflection; using System; using System.Collections.Generic; using System.Linq; namespace ToolBox { public static class Extensions { private static Dictionary<Type, MethodInfo> _validParseAsNullableMethod2 = new Dictionary<Type, MethodInfo>(); private static Dictionary<Type, MethodInfo> _validParseAsNullableMethod4 = new Dictionary<Type, MethodInfo>(); /// <summary> /// Parse a string into a nullable type. /// </summary> /// <param name="s">String to parse.</param> /// <returns>Parsed value on success, null otherwise.</returns> public static Nullable<T> ParseAsNullable<T>(this string s) where T : struct, IConvertible { var type = typeof(T); var ret = new Nullable<T>(); // Using a hashset here is approximately // the same speed as this if statement. if (type == typeof(bool) || type == typeof(sbyte) || type == typeof(byte) || type == typeof(Int16) || type == typeof(UInt16) || type == typeof(Int32) || type == typeof(UInt32) || type == typeof(Int64) || type == typeof(UInt64) || type == typeof(int) || type == typeof(Single) || type == typeof(double) || type == typeof(decimal) || type == typeof(DateTime) || type == typeof(char)) { // Caching the method goes from ~350 ticks to ~30 ticks // on subsequent invocations. MethodInfo method = null; if (!_validParseAsNullableMethod2.TryGetValue(type, out method)) { method = type.GetMethods().Single(x => x.Name == "TryParse" && x.GetParameters().Length == 2); _validParseAsNullableMethod2[type] = method; } // The last parameter is a reference to the out parameter in TryParse. // If the parse succeeds, the reference will point to a valid object. var parameters = new object[] { s, null }; var result = (bool)method.Invoke(null, parameters); if (result) { // The result is already the correct type but the compiler // doesn't know that. ret = (T)parameters[1]; } } else { throw new NotSupportedException(); } return ret; } /// <summary> /// Parse a string into a nullable type. /// </summary> /// <param name="s">String to parse.</param> /// <param name="style">Style information.</param> /// <param name="provider">Format provider.</param> /// <returns>Parsed value on success, null otherwise.</returns> public static Nullable<T> ParseAsNullable<T>(this string s, NumberStyles style, IFormatProvider provider) where T : struct, IConvertible { var type = typeof(T); var ret = new Nullable<T>(); // no bool // no DateTime // no char if (type == typeof(sbyte) || type == typeof(byte) || type == typeof(Int16) || type == typeof(UInt16) || type == typeof(Int32) || type == typeof(UInt32) || type == typeof(Int64) || type == typeof(UInt64) || type == typeof(int) || type == typeof(Single) || type == typeof(double) || type == typeof(decimal)) { MethodInfo method = null; if (!_validParseAsNullableMethod4.TryGetValue(type, out method)) { method = type.GetMethods().Single(x => x.Name == "TryParse" && x.GetParameters().Length == 4); _validParseAsNullableMethod4[type] = method; } // The last parameter is a reference to the out paramter in TryParse. // If the parse succeeds, the reference will point to a valid object. var parameters = new object[] { s, style, provider, null }; var result = (bool)method.Invoke(null, parameters); if (result) { // The result is already the correct type but the compiler // doesn't know that. ret = (T)parameters[3]; } } else { throw new NotSupportedException(); } return ret; } /// <summary> /// Parse a string into a nullable type. /// </summary> /// <param name="s">String to parse.</param> /// <param name="styles">Style information.</param> /// <param name="provider">Format provider.</param> /// <returns>Parsed value on success, null otherwise.</returns> public static Nullable<T> ParseAsNullable<T>(this string s, DateTimeStyles styles, IFormatProvider provider) where T : struct, IConvertible { var type = typeof(T); var ret = new Nullable<T>(); if (type == typeof(DateTime)) { DateTime x; // DateTime TryParse swaps the provider and styles arguments // compared to the order for the other types above. if (DateTime.TryParse(s, provider, styles, out x)) { // The result is already the correct type but the compiler // doesn't know that. This cast could also be written as // ret = (T)((object)x); ret = (T)Convert.ChangeType(x, type); } } else { throw new NotSupportedException(); } return ret; } /* ********************************************************************** // An alternative implementation to convert to a nullable type. // // Advantages: // - A bit simpler. // - No global static variables. // // Disadvantages: // - This takes about 5x longer than the TryParse method. // - There is an overload to accept a CultureInfo, but it also // requires a type converter context, so this is a bit harder // to setup if you wanted to do something like change the // decimal seperator in a double. // // I posted this on SO: https://stackoverflow.com/a/47189518/1462295 using System.ComponentModel; public static Nullable<T> ToNullable<T>(this string s) where T : struct { var ret = new Nullable<T>(); var conv = TypeDescriptor.GetConverter(typeof(T)); if (!conv.CanConvertFrom(typeof(string))) { throw new NotSupportedException(); } if (conv.IsValid(s)) { ret = (T)conv.ConvertFrom(s); } return ret; } ********************************************************************** */ /// <summary> /// Attempts to get the value associated with the specified key from the <see /// cref="Dictionary{TKey,TValue}"/>. If not found, action will be executed, /// and the dictionary will be updated with the returned value. /// </summary> /// <param name="key">The key of the value to get.</param> /// <param name="value">When this method returns, <paramref name="value"/> contains the object from /// the /// <see cref="Dictionary{TKey,TValue}"/> with the specified key or the result from /// the action if the key was not found.</param> /// <param name="action">Action to perform if the specified key is not found.</param> /// <returns>true if the key was found in the <see cref="ConcurrentDictionary{TKey,TValue}"/>; /// otherwise, false.</returns> /// <exception cref="T:System.ArgumentNullException"><paramref name="key"/> is a null /// reference.</exception> public static void TryGetValueAction<TKey, TValue>(this IDictionary<TKey, TValue> dict, TKey key, out TValue value, Func<TKey, TValue> action) { if (!dict.TryGetValue(key, out value)) { value = action(key); dict[key] = value; } } /// <summary> /// Splits a string and then parses each substring to int. Items that do not /// parse correctly are silently dropped. /// </summary> /// <param name="input">Input string to split and parse.</param> /// <param name="splitChar">Character used to split the string.</param> /// <returns>A list of ints that were successfully parsed.</returns> public IEnumerable<int> SplitParse(this string input, char splitChar) { var results = new List<int>(); if (string.IsNullOrEmpty(input)) { return results; } var items = input.Split(splitChar); foreach (var x in items) { int i; if (int.TryParse(x, out i)) { results.Add(i); } } return results.AsEnumerable(); } } }
using System; using System.Collections.Generic; using System.Text; using NUnit.Framework; using Appleseed.Framework.Providers.AppleseedMembershipProvider; using System.Collections.Specialized; using System.Web.Security; using System.Data.SqlClient; namespace Appleseed.Tests { [TestFixture] public class MembershipProviderTest { [TestFixtureSetUp] public void FixtureSetUp() { // Set up initial database environment for testing purposes TestHelper.TearDownDB(); TestHelper.RecreateDBSchema(); } [Test] public void Foo() { Console.WriteLine("This should pass. It only writes to the Console."); } #region Config properties [Test] public void ApplicationNameTest() { try { string appName = Membership.ApplicationName; Assert.AreEqual(appName, "Appleseed"); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving ApplicationName property", ex); } } [Test] public void EnablePasswordResetTest() { try { bool enablePwdReset = Membership.EnablePasswordReset; Assert.AreEqual(enablePwdReset, true); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving EnablePasswordReset property", ex); } } [Test] public void EnablePasswordRetrievalTest() { try { bool enablePwdRetrieval = Membership.EnablePasswordRetrieval; Assert.AreEqual(enablePwdRetrieval, false); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving EnablePasswordRetrieval property", ex); } } [Test] public void HashAlgorithmTypeTest() { try { string hashAlgType = Membership.HashAlgorithmType; Assert.AreEqual(hashAlgType, "SHA1"); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving HashAlgorithmType property", ex); } } [Test] public void MaxInvalidPasswordAttemptsTest() { try { int maxInvalidPwdAttempts = Membership.MaxInvalidPasswordAttempts; Assert.AreEqual(maxInvalidPwdAttempts, 5); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving MaxInvalidPasswordAttempts property", ex); } } [Test] public void MinRequiredNonAlphanumericCharactersTest() { try { int minReqNonAlpha = Membership.MinRequiredNonAlphanumericCharacters; Assert.AreEqual(minReqNonAlpha, 1); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving MinRequiredNonAlphanumericCharacters property", ex); } } [Test] public void MinRequiredPasswordLengthTest() { try { int minReqPwdLength = Membership.MinRequiredPasswordLength; Assert.AreEqual(minReqPwdLength, 5); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving MinRequiredPasswordLength property", ex); } } [Test] public void PasswordAttemptWindowTest() { try { int pwdAttemptWindow = Membership.PasswordAttemptWindow; Assert.AreEqual(pwdAttemptWindow, 15); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving PasswordAttemptWindows property", ex); } } [Test] public void PasswordStrengthRegularExpressionTest() { try { string pwdStrengthRegex = Membership.PasswordStrengthRegularExpression; Assert.AreEqual(pwdStrengthRegex, string.Empty); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving PasswordStrengthRegularExpression property", ex); } } [Test] public void ProviderTest() { try { MembershipProvider provider = Membership.Provider; Assert.AreEqual(provider.GetType(), typeof(Appleseed.Framework.Providers.AppleseedMembershipProvider.AppleseedSqlMembershipProvider)); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving Provider property", ex); } } [Test] public void ProvidersTest() { try { MembershipProviderCollection providers = Membership.Providers; Assert.AreEqual(providers.Count, 1); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving Providers property", ex); } } [Test] public void RequiresQuestionAndAnswerTest() { try { bool reqQuestionAndAnswer = Membership.RequiresQuestionAndAnswer; Assert.AreEqual(reqQuestionAndAnswer, false); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error retrieving RequiresQuestionAndAnswer property", ex); } } #endregion #region Membership provider methods [Test] public void GetAllUsersTest() { try { int totalRecords; Membership.GetAllUsers(); Membership.GetAllUsers(0, 1, out totalRecords); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in GetAllUsersTest", ex); } } [Test] public void GetNumberOfUsersOnlineTest() { try { Membership.GetNumberOfUsersOnline(); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in GetNumberOfUsersOnlineTest", ex); } } [Test] public void GetPasswordTest() { try { if (Membership.EnablePasswordRetrieval) { string pwd = Membership.Provider.GetPassword("admin@Appleseedportal.net", "answer"); } } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in GetPasswordTest", ex); } } [Test] public void GetUserTest() { try { MembershipUser user = Membership.GetUser("admin@Appleseedportal.net"); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in GetUserTest", ex); } } [Test] public void GetUserNameByEmailValidUserTest() { try { string userName = Membership.GetUserNameByEmail("admin@Appleseedportal.net"); Assert.AreEqual(userName, "admin@Appleseedportal.net"); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in GetUserNameByEmailValidUserTest", ex); } } [Test] public void GetUserNameByEmailInvalidUserTest() { try { string userName = Membership.GetUserNameByEmail("invaliduser@doesnotexist.com"); Assert.AreEqual(userName, string.Empty); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in GetUserNameByEmailInvalidUserTest", ex); } } [Test] public void FindUsersByNameTest1() { try { MembershipUserCollection users = Membership.FindUsersByName("admin@Appleseedportal.net"); Assert.AreEqual(users.Count, 1); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByNameTest1", ex); } } [Test] public void FindUsersByNameTest2() { try { MembershipUserCollection users = Membership.FindUsersByName("invaliduser@doesnotexist.com"); Assert.IsEmpty(users); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByNameTest2", ex); } } [Test] public void FindUsersByNameTest3() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByName("admin@Appleseedportal.net", 0, 10, out totalRecords); Assert.AreEqual(users.Count, 1); Assert.Greater(totalRecords, 0); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByNameTest3", ex); } } [Test] public void FindUsersByNameTest4() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByName("invaliduser@doesnotexist.com", 0, 10, out totalRecords); Assert.IsEmpty(users); Assert.AreEqual(totalRecords, 0); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByNameTest4", ex); } } [Test] public void FindUsersByEmailTest1() { try { MembershipUserCollection users = Membership.FindUsersByEmail("admin@Appleseedportal.net"); Assert.AreEqual(users.Count, 1); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByEmailTest1", ex); } } [Test] public void FindUsersByEmailTest2() { try { MembershipUserCollection users = Membership.FindUsersByName("invaliduser@doesnotexist.com"); Assert.IsEmpty(users); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByEmailTest2", ex); } } [Test] public void FindUsersByEmailTest3() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByEmail("admin@Appleseedportal.net", 0, 10, out totalRecords); Assert.AreEqual(users.Count, 1); Assert.Greater(totalRecords, 0); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByEmailTest3", ex); } } [Test] public void FindUsersByEmailTest4() { try { int totalRecords = -1; MembershipUserCollection users = Membership.FindUsersByEmail("invaliduser@doesnotexist.com", 0, 10, out totalRecords); Assert.IsEmpty(users); Assert.AreEqual(totalRecords, 0); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in FindUsersByEmailTes4", ex); } } [Test] public void ValidateUserTest1() { try { bool isValid = Membership.ValidateUser("admin@Appleseedportal.net", "notavalidpwd"); Assert.IsFalse(isValid); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ValidateUserTest1", ex); } } [Test] public void ValidateUserTest2() { try { bool isValid = Membership.ValidateUser("admin@Appleseedportal.net", "admin"); Assert.IsTrue(isValid); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ValidateUserTest2", ex); } } [Test] public void ValidateUserTest3() { try { bool isValid = Membership.ValidateUser("invaliduser@doesnotexist.com", "notavalidpwd"); Assert.IsFalse(isValid); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ValidateUserTest3", ex); } } [Test] public void ValidateUserTest4() { try { bool isValid = Membership.ValidateUser("invaliduser@doesnotexist.com", "admin"); Assert.IsFalse(isValid); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ValidateUserTest4", ex); } } [Test] public void ChangePasswordQuestionAndAnswerTest1() { try { bool pwdChanged = Membership.Provider.ChangePasswordQuestionAndAnswer("admin@Appleseedportal.net", "admin", "newPasswordQuestion", "newPasswordAnswer"); Assert.IsTrue(pwdChanged); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ChangePasswordQuestionAndAnswer1", ex); } } [Test] public void ChangePasswordQuestionAndAnswerTest2() { try { bool pwdChanged = Membership.Provider.ChangePasswordQuestionAndAnswer("admin@Appleseedportal.net", "invalidPwd", "newPasswordQuestion", "newPasswordAnswer"); Assert.IsFalse(pwdChanged); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ChangePasswordQuestionAndAnswer2", ex); } } [Test] public void ChangePasswordQuestionAndAnswerTest3() { try { bool pwdChanged = Membership.Provider.ChangePasswordQuestionAndAnswer("invaliduser@doesnotexist.com", "InvalidPwd", "newPasswordQuestion", "newPasswordAnswer"); Assert.IsFalse(pwdChanged); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ChangePasswordQuestionAndAnswer3", ex); } } [Test] public void UnlockUserTest1() { try { bool unlocked = Membership.Provider.UnlockUser("admin@Appleseedportal.net"); Assert.IsTrue(unlocked); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in UnlockUserTest1", ex); } } [Test] public void UnlockUserTest2() { try { bool unlocked = Membership.Provider.UnlockUser("invaliduser@doesnotexist.com"); Assert.IsFalse(unlocked); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in UnlockUserTest2", ex); } } [Test] public void CreateUserTest1() { try { MembershipCreateStatus status; MembershipUser user = Membership.CreateUser("Admin@Appleseedportal.net", "admin", "Admin@Appleseedportal.net", "question", "answer", true, out status); Assert.IsNull(user); Assert.AreEqual(status, MembershipCreateStatus.DuplicateUserName); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in CreateUserTest1", ex); } } [Test] public void CreateUserTest2() { try { MembershipCreateStatus status; MembershipUser user = Membership.CreateUser("Tito", "tito", "tito@tito.com", "question", "answer", true, out status); Assert.IsNotNull(user); Assert.AreEqual(status, MembershipCreateStatus.Success); Assert.AreEqual(user.UserName, "Tito"); Assert.AreEqual(user.Email, "tito@tito.com"); Assert.AreEqual(user.PasswordQuestion, "question"); Assert.IsTrue(user.IsApproved); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in CreateUserTest2", ex); } } [Test] public void ChangePasswordToExistingUserTest() { try { bool sucess = Membership.Provider.ChangePassword("Tito", "tito", "newPassword"); Assert.IsTrue(sucess); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ChangePasswordTest1", ex); } } [Test] public void ChangePasswordToInexistentUserTest() { try { bool sucess = Membership.Provider.ChangePassword("invaliduser@doesnotexist.com", "pwd", "newPassword"); Assert.IsFalse(sucess); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ChangePasswordTest2", ex); } } [Test] public void ChangePasswordInvalidCurrentPassorwdTest() { try { bool sucess = Membership.Provider.ChangePassword("Admin@Appleseedportal.net", "invalidPwd", "newPassword"); Assert.IsFalse(sucess); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ChangePasswordTest3", ex); } } [Test] public void UpdateExistingUserTest() { try { AppleseedUser user = (AppleseedUser)Membership.GetUser("Tito"); Assert.AreEqual(user.Email, "tito@tito.com"); Assert.IsTrue(user.IsApproved); user.Email = "newEmail@tito.com"; user.IsApproved = false; user.LastLoginDate = new DateTime(1982, 2, 6); Membership.UpdateUser(user); user = (AppleseedUser)Membership.GetUser("Tito"); Assert.AreEqual(user.Email, "newEmail@tito.com"); Assert.IsFalse(user.IsApproved); Assert.AreEqual(new DateTime(1982, 2, 6), user.LastLoginDate); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in UpdateUserTest1", ex); } } [Test] public void UpdateUserTest2() { try { AppleseedUser user = new AppleseedUser(Membership.Provider.Name, "invalidUserName", Guid.NewGuid(), "tito@tito.com", "question", "answer", true, false, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.Now, DateTime.MinValue); Membership.UpdateUser(user); Assert.Fail("UpdateUser didn't throw an exception even though userName was invalid"); } catch (AppleseedMembershipProviderException) { } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in UpdateUserTest1", ex); } } [Test] public void ResetPasswordTest1() { try { string newPwd = Membership.Provider.ResetPassword("invalidUser", "answer"); Assert.Fail("ResetPassword went ok with invalid user name"); } catch (AppleseedMembershipProviderException) { } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ResetPasswordTest1", ex); } } [Test] public void ResetPasswordTest2() { try { string newPwd = Membership.Provider.ResetPassword("Tito", "invalidAnswer"); Assert.Fail("ResetPassword went ok with invalid password answer"); } catch (MembershipPasswordException) { } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ResetPasswordTest2", ex); } } [Test] public void ResetPasswordTest3() { try { string newPwd = Membership.Provider.ResetPassword("Tito", "answer"); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in ResetPasswordTest3", ex); } } [Test] public void DeleteUserTest1() { try { bool success = Membership.DeleteUser("invalidUser"); Assert.IsFalse(success); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in DeleteUserTest1", ex); } } [Test] public void DeleteUserTest2() { try { bool success = Membership.DeleteUser("Tito"); Assert.IsTrue(success); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); Assert.Fail("Error in DeleteUserTest2", ex); } } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace Microsoft.Management.UI.Internal { /// <content> /// Partial class implementation for ListOrganizerItem control. /// </content> [SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public partial class ListOrganizerItem : Control { private string startingText; private FrameworkElement templatedParent; /// <summary> /// Creates a new instance of the ListOrganizerItem class. /// </summary> public ListOrganizerItem() { // empty } /// <summary> /// Gets a value indicating whether the item is in edit mode. /// </summary> public bool IsInEditMode { get { return (this.renameButton != null) ? this.renameButton.IsChecked.Value : false; } } /// <summary> /// Selects the current item. /// </summary> public void Select() { if (!this.IsLoaded) { this.Loaded += this.ListOrganizerItem_Loaded_SelectItem; this.ApplyTemplate(); return; } CommandHelper.ExecuteCommand(this.linkButton.Command, this.linkButton.CommandParameter, this.linkButton.CommandTarget); } /// <summary> /// Allows modification of the item. /// </summary> public void Rename() { this.renameButton.IsChecked = true; } /// <summary> /// Deletes the item. /// </summary> public void Delete() { CommandHelper.ExecuteCommand(this.deleteButton.Command, this.deleteButton.CommandParameter, this.deleteButton.CommandTarget); } /// <summary> /// Provides class handling for the KeyDown routed event that /// occurs when the user presses a key while this control has focus. /// </summary> /// <param name="e">The event data.</param> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (this.IsInEditMode) { return; } switch (e.Key) { case Key.Insert: this.Rename(); e.Handled = true; break; case Key.Delete: this.Delete(); e.Handled = true; break; case Key.Enter: case Key.Space: this.Select(); e.Handled = true; break; default: break; } } private void TemplatedParent_OnKeyDown(object sender, KeyEventArgs e) { this.OnKeyDown(e); } private void ListOrganizerItem_Loaded_SelectItem(object sender, RoutedEventArgs e) { this.Loaded -= this.ListOrganizerItem_Loaded_SelectItem; this.Select(); } #region EditBox Event Handlers private void EditBox_LostFocus(object sender, RoutedEventArgs e) { this.ChangeFromEditToDisplayMode(); } private void EditBox_KeyDown(object sender, KeyEventArgs e) { switch (e.Key) { case Key.Enter: this.ChangeFromEditToDisplayMode(); e.Handled = true; break; case Key.Escape: this.RevertTextAndChangeFromEditToDisplayMode(); e.Handled = true; break; default: break; } } private void RevertTextAndChangeFromEditToDisplayMode() { this.editBox.Text = this.startingText; this.ChangeFromEditToDisplayMode(); } private void ChangeFromEditToDisplayMode() { // NOTE : This is to resolve a race condition where clicking // on the rename button causes the the edit box to change and // then have re-toggle. DependencyObject d = Mouse.DirectlyOver as DependencyObject; if (d == null || !(this.renameButton.IsAncestorOf(d) && Mouse.LeftButton == MouseButtonState.Pressed)) { this.renameButton.IsChecked = false; } if (!this.IsKeyboardFocusWithin) { this.Focus(); } } private void EditBox_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e) { if (this.editBox.IsVisible) { this.startingText = this.editBox.Text; this.editBox.Focus(); this.editBox.SelectAll(); } } #endregion EditBox Event Handlers partial void OnTextContentPropertyNameChangedImplementation(PropertyChangedEventArgs<string> e) { this.UpdateTextContentBindings(); } private void UpdateTextContentBindings() { if (!this.IsLoaded) { this.Loaded += this.ListOrganizerItem_Loaded_UpdateTextContentBindings; this.ApplyTemplate(); return; } if (!string.IsNullOrEmpty(this.TextContentPropertyName)) { Binding b = new Binding(this.TextContentPropertyName); b.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged; this.linkButton.SetBinding(Button.ContentProperty, b); this.editBox.SetBinding(TextBox.TextProperty, b); } else { BindingOperations.ClearBinding(this.linkButton, Button.ContentProperty); BindingOperations.ClearBinding(this.editBox, TextBox.TextProperty); } } private void ListOrganizerItem_Loaded_UpdateTextContentBindings(object sender, RoutedEventArgs e) { this.Loaded -= this.ListOrganizerItem_Loaded_UpdateTextContentBindings; this.UpdateTextContentBindings(); } #region OnApplyTemplate Helpers partial void PreOnApplyTemplate() { this.DetachFromVisualTree(); } partial void PostOnApplyTemplate() { this.AttachToVisualTree(); } private void AttachToVisualTree() { this.editBox.IsVisibleChanged += new DependencyPropertyChangedEventHandler(this.EditBox_IsVisibleChanged); this.editBox.KeyDown += this.EditBox_KeyDown; this.editBox.LostFocus += this.EditBox_LostFocus; this.templatedParent = this.TemplatedParent as FrameworkElement; if (this.templatedParent != null) { this.templatedParent.KeyDown += this.TemplatedParent_OnKeyDown; } } private void DetachFromVisualTree() { if (this.editBox != null) { this.editBox.IsVisibleChanged -= this.EditBox_IsVisibleChanged; this.editBox.KeyDown -= this.EditBox_KeyDown; this.editBox.LostFocus -= this.EditBox_LostFocus; } if (this.templatedParent != null) { this.templatedParent.KeyDown -= this.TemplatedParent_OnKeyDown; } } #endregion OnApplyTemplate Helpers } }
using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.Compilation.Parser; using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; namespace DotVVM.Framework.Tests.Parser.Dothtml { [TestClass] public class DothtmlTokenizerHtmlSpecialElementsTests : DothtmlTokenizerTestsBase { [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid() { var input = @"test <!DOCTYPE html> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_Begin() { var input = @"<!DOCTYPE html> test"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_End() { var input = @"test <!DOCTYPE html>"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_Empty() { var input = @"<!DOCTYPE>"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual("", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Invalid_Incomplete_WithValue() { var input = @"<!DOCTYPE html"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Invalid_Incomplete_NoValue() { var input = @"<!DOCTYPE"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_XmlProcessingInstructionParsing_Valid() { var input = @"test <?xml version=""1.0"" encoding=""utf-8"" ?> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<?", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenXmlProcessingInstruction, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"xml version=""1.0"" encoding=""utf-8"" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.XmlProcessingInstructionBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("?>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseXmlProcessingInstruction, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CDataParsing_Valid() { var input = @"test <![CDATA[ this is a text < > "" ' ]]> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<![CDATA[", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenCData, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CDataBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("]]>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseCData, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentParsing_Valid() { var input = @"test <!-- this is a text < > "" ' --> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("-->", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentParsing_Valid_2() { var input = @"test <!--<a href=""test1"">test2</a>--> test3 <img />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"<a href=""test1"">test2</a>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("-->", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test3 ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual("img", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual("/", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Slash, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_ServerCommentParsing_Valid() { var input = @"test <%-- this is a text < > "" ' --%> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<%--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("--%>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_ServerCommentParsing_Valid_2() { var input = @"test <%--<a href=""test1"">test2</a>--%> test3 <img />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<%--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"<a href=""test1"">test2</a>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("--%>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test3 ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual("img", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual("/", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Slash, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentInsideElement() { var input = "<a <!-- comment --> href='so'>"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenTag, tokens[0].Type); Assert.AreEqual(@"<", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[1].Type); Assert.AreEqual(@"a", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[2].Type); Assert.AreEqual(@" ", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[3].Type); Assert.AreEqual(@"<!--", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[4].Type); Assert.AreEqual(@" comment ", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[5].Type); Assert.AreEqual(@"-->", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[7].Type); Assert.AreEqual(@"href", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.Equals, tokens[8].Type); Assert.AreEqual(@"=", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[9].Type); Assert.AreEqual(@"'", tokens[9].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[10].Type); Assert.AreEqual(@"so", tokens[10].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[11].Type); Assert.AreEqual(@"'", tokens[11].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokens[12].Type); Assert.AreEqual(@">", tokens[12].Text); } [TestMethod] public void DothtmlTokenizer_ServerCommentInsideElement() { var input = "<a <%-- comment --%> href=''>"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenTag, tokens[0].Type); Assert.AreEqual(@"<", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[1].Type); Assert.AreEqual(@"a", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[2].Type); Assert.AreEqual(@" ", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[3].Type); Assert.AreEqual(@"<%--", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[4].Type); Assert.AreEqual(@" comment ", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[5].Type); Assert.AreEqual(@"--%>", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[7].Type); Assert.AreEqual(@"href", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.Equals, tokens[8].Type); Assert.AreEqual(@"=", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[9].Type); Assert.AreEqual(@"'", tokens[9].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[10].Type); Assert.AreEqual(@"", tokens[10].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[11].Type); Assert.AreEqual(@"'", tokens[11].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokens[12].Type); Assert.AreEqual(@">", tokens[12].Text); } [TestMethod] public void DothtmlTokenizer_Valid_CommentBeforeDirective() { var input = "<!-- my comment --> @viewModel TestDirective\r\nTest"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[0].Type); Assert.AreEqual(@"<!--", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(@" my comment ", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(@"-->", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[3].Type); Assert.AreEqual(@" ", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokens[4].Type); Assert.AreEqual(@"@", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.DirectiveName, tokens[5].Type); Assert.AreEqual(@"viewModel", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokens[7].Type); Assert.AreEqual(@"TestDirective", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[8].Type); Assert.AreEqual("\r\n", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[9].Type); Assert.AreEqual(@"Test", tokens[9].Text); } [TestMethod] public void DothtmlTokenizer_NestedServerComment() { var input = "<%-- my <div> <%-- <p> </p> --%> comment --%>"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[0].Type); Assert.AreEqual(@"<%--", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(@" my <div> <%-- <p> </p> --%> comment ", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(@"--%>", tokens[2].Text); } [TestMethod] public void DothtmlTokenizer_CommentWithMoreMinuses() { var input = "<!-- my comment ---> @viewModel TestDirective\r\nTest"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[0].Type); Assert.AreEqual(@"<!--", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(@" my comment -", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(@"-->", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[3].Type); Assert.AreEqual(@" ", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokens[4].Type); Assert.AreEqual(@"@", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.DirectiveName, tokens[5].Type); Assert.AreEqual(@"viewModel", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokens[7].Type); Assert.AreEqual(@"TestDirective", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[8].Type); Assert.AreEqual("\r\n", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[9].Type); Assert.AreEqual(@"Test", tokens[9].Text); } [TestMethod] public void DothtmlTokenizer_Valid_ServerCommentBeforeDirective() { var input = " <%-- my comment --%>@viewModel TestDirective\r\nTest"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.Text, tokens[0].Type); Assert.AreEqual(@" ", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[1].Type); Assert.AreEqual(@"<%--", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[2].Type); Assert.AreEqual(@" my comment ", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[3].Type); Assert.AreEqual(@"--%>", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokens[4].Type); Assert.AreEqual(@"@", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.DirectiveName, tokens[5].Type); Assert.AreEqual(@"viewModel", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokens[7].Type); Assert.AreEqual(@"TestDirective", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[8].Type); Assert.AreEqual("\r\n", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[9].Type); Assert.AreEqual(@"Test", tokens[9].Text); } [TestMethod] public void BindingTokenizer_UnclosedHtmlComment_Error() { var tokens = Tokenize(@"<!--REEEEEEEEE"); Assert.AreEqual(3, tokens.Count); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[0].Type); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(null, tokens[0].Error, "This token is just opening token nothing wrong here."); Assert.AreEqual(null, tokens[1].Error, "This token is just body nothing wrong with that."); Assert.IsTrue(tokens[2].Error.ErrorMessage.Contains("not closed"),"This token had to be created artificialy."); } [TestMethod] public void BindingTokenizer_UnclosedServerComment_Error() { var tokens = Tokenize(@"<%--REEEEEEEEE"); Assert.AreEqual(3, tokens.Count); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[0].Type); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(null, tokens[0].Error, "This token is just opening token nothing wrong here."); Assert.AreEqual(null, tokens[1].Error, "This token is just body nothing wrong with that."); Assert.IsTrue(tokens[2].Error.ErrorMessage.Contains("not closed"), "This token had to be created artificialy."); } } }
// // Slider.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright 2009 Aaron Bockover // // 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 Cairo; using Hyena.Gui; using Hyena.Gui.Theming; namespace Hyena.Gui.Canvas { public class Slider : CanvasItem { private uint value_changed_inhibit_ref = 0; public event EventHandler<EventArgs> ValueChanged; public event EventHandler<EventArgs> PendingValueChanged; public Slider () { Margin = new Thickness (3); MarginStyle = new ShadowMarginStyle { ShadowSize = 3, ShadowOpacity = 0.25 }; } protected virtual void OnValueChanged () { if (value_changed_inhibit_ref != 0) { return; } var handler = ValueChanged; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnPendingValueChanged () { var handler = PendingValueChanged; if (handler != null) { handler (this, EventArgs.Empty); } } public void InhibitValueChangeEvent () { value_changed_inhibit_ref++; } public void UninhibitValueChangeEvent () { value_changed_inhibit_ref--; } private void SetPendingValueFromX (double x) { IsValueUpdatePending = true; PendingValue = Math.Max (0, Math.Min ((x - ThrobberSize / 2) / RenderSize.Width, 1)); } public override bool ButtonEvent (Point cursor, bool pressed, uint button) { if (pressed && button == 1) { GrabPointer (); SetPendingValueFromX (cursor.X); return true; } else if (!pressed && IsPointerGrabbed) { ReleasePointer (); Value = PendingValue; IsValueUpdatePending = false; return true; } return false; } public override bool CursorMotionEvent (Point cursor) { if (IsPointerGrabbed) { SetPendingValueFromX (cursor.X); return true; } return false; } //private double last_invalidate_value = -1; /*private void Invalidate () { double current_value = (IsValueUpdatePending ? PendingValue : Value); // FIXME: Something is wrong with the updating below causing an // invalid region when IsValueUpdatePending is true, so when // that is the case for now, we trigger a full invalidation if (last_invalidate_value < 0 || IsValueUpdatePending) { last_invalidate_value = current_value; InvalidateRender (); return; } double max = Math.Max (last_invalidate_value, current_value) * RenderSize.Width; double min = Math.Min (last_invalidate_value, current_value) * RenderSize.Width; Rect region = new Rect ( InvalidationRect.X + min, InvalidationRect.Y, (max - min) + 2 * ThrobberSize, InvalidationRect.Height ); last_invalidate_value = current_value; InvalidateRender (region); }*/ /*protected override Rect InvalidationRect { get { return new Rect ( -Margin.Left - ThrobberSize / 2, -Margin.Top, Allocation.Width + ThrobberSize, Allocation.Height); } }*/ protected override void ClippedRender (Cairo.Context cr) { double throbber_r = ThrobberSize / 2.0; double throbber_x = Math.Round (RenderSize.Width * (IsValueUpdatePending ? PendingValue : Value)); double throbber_y = (Allocation.Height - ThrobberSize) / 2.0 - Margin.Top + throbber_r; double bar_w = RenderSize.Width * Value; cr.SetSourceColor (Theme.Colors.GetWidgetColor (GtkColorClass.Base, Gtk.StateType.Normal)); cr.Rectangle (0, 0, RenderSize.Width, RenderSize.Height); cr.Fill (); Color color = Theme.Colors.GetWidgetColor (GtkColorClass.Dark, Gtk.StateType.Active); Color fill_color = CairoExtensions.ColorShade (color, 0.4); Color light_fill_color = CairoExtensions.ColorShade (color, 0.3); fill_color.A = 1.0; light_fill_color.A = 1.0; LinearGradient fill = new LinearGradient (0, 0, 0, RenderSize.Height); fill.AddColorStop (0, light_fill_color); fill.AddColorStop (0.5, fill_color); fill.AddColorStop (1, light_fill_color); cr.Rectangle (0, 0, bar_w, RenderSize.Height); cr.SetSource (fill); cr.Fill (); cr.SetSourceColor (fill_color); cr.Arc (throbber_x, throbber_y, throbber_r, 0, Math.PI * 2); cr.Fill (); } public override Size Measure (Size available) { Height = BarSize; return DesiredSize = new Size (base.Measure (available).Width, Height + Margin.Top + Margin.Bottom); } private double bar_size = 3; public virtual double BarSize { get { return bar_size; } set { bar_size = value; } } private double throbber_size = 7; public virtual double ThrobberSize { get { return throbber_size; } set { throbber_size = value; } } private double value; public virtual double Value { get { return this.value; } set { if (value < 0.0 || value > 1.0) { throw new ArgumentOutOfRangeException ("Value", "Must be between 0.0 and 1.0 inclusive"); } else if (this.value == value) { return; } this.value = value; Invalidate (); OnValueChanged (); } } private bool is_value_update_pending; public virtual bool IsValueUpdatePending { get { return is_value_update_pending; } set { is_value_update_pending = value; } } private double pending_value; public virtual double PendingValue { get { return pending_value; } set { if (value < 0.0 || value > 1.0) { throw new ArgumentOutOfRangeException ("Value", "Must be between 0.0 and 1.0 inclusive"); } else if (pending_value == value) { return; } pending_value = value; Invalidate (); OnPendingValueChanged (); } } } }
/* * 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 log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.Framework.Scenes { public delegate void RemoveKnownRegionsFromAvatarList(UUID avatarID, List<ulong> regionlst); /// <summary> /// Class that Region communications runs through /// </summary> public class SceneCommunicationService //one instance per region { protected RegionInfo m_regionInfo; protected Scene m_scene; private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public delegate void InformNeighbourThatRegionUpDelegate(INeighbourService nService, RegionInfo region, ulong regionhandle); public delegate void SendChildAgentDataUpdateDelegate(AgentPosition cAgentData, UUID scopeID, GridRegion dest); public void InformNeighborsThatRegionisUp(INeighbourService neighbourService, RegionInfo region) { //m_log.Info("[INTER]: " + debugRegionName + ": SceneCommunicationService: Sending InterRegion Notification that region is up " + region.RegionName); List<GridRegion> neighbours = m_scene.GridService.GetNeighbours(m_scene.RegionInfo.ScopeID, m_scene.RegionInfo.RegionID); m_log.DebugFormat( "[SCENE COMMUNICATION SERVICE]: Informing {0} neighbours that region {1} is up", neighbours.Count, m_scene.Name); foreach (GridRegion n in neighbours) { InformNeighbourThatRegionUpDelegate d = InformNeighboursThatRegionIsUpAsync; d.BeginInvoke(neighbourService, region, n.RegionHandle, InformNeighborsThatRegionisUpCompleted, d); } } public List<GridRegion> RequestNamedRegions(string name, int maxNumber) { return m_scene.GridService.GetRegionsByName(UUID.Zero, name, maxNumber); } public void SendChildAgentDataUpdate(AgentPosition cAgentData, ScenePresence presence) { // This assumes that we know what our neighbors are. try { uint x = 0, y = 0; List<string> simulatorList = new List<string>(); foreach (ulong regionHandle in presence.KnownRegionHandles) { if (regionHandle != m_regionInfo.RegionHandle) { // we only want to send one update to each simulator; the simulator will // hand it off to the regions where a child agent exists, this does assume // that the region position is cached or performance will degrade Util.RegionHandleToWorldLoc(regionHandle, out x, out y); GridRegion dest = m_scene.GridService.GetRegionByPosition(UUID.Zero, (int)x, (int)y); if (dest == null) continue; if (!simulatorList.Contains(dest.ServerURI)) { // we havent seen this simulator before, add it to the list // and send it an update simulatorList.Add(dest.ServerURI); // Let move this to sync. Mono definitely does not like async networking. m_scene.SimulationService.UpdateAgent(dest, cAgentData); // Leaving this here as a reminder that we tried, and it sucks. //SendChildAgentDataUpdateDelegate d = SendChildAgentDataUpdateAsync; //d.BeginInvoke(cAgentData, m_regionInfo.ScopeID, dest, // SendChildAgentDataUpdateCompleted, // d); } } } } catch (InvalidOperationException) { // We're ignoring a collection was modified error because this data gets old and outdated fast. } } /// <summary> /// Closes a child agents in a collection of regions. Does so asynchronously /// so that the caller doesn't wait. /// </summary> /// <param name="agentID"></param> /// <param name="regionslst"></param> public void SendCloseChildAgentConnections(UUID agentID, string auth_code, List<ulong> regionslst) { foreach (ulong handle in regionslst) { // We must take a copy here since handle is acts like a reference when used in an iterator. // This leads to race conditions if directly passed to SendCloseChildAgent with more than one neighbour region. ulong handleCopy = handle; Util.FireAndForget((o) => { SendCloseChildAgent(agentID, handleCopy, auth_code); }); } } public void SetScene(Scene s) { m_scene = s; m_regionInfo = s.RegionInfo; } /// <summary> /// Closes a child agent on a given region /// </summary> protected void SendCloseChildAgent(UUID agentID, ulong regionHandle, string auth_token) { // let's do our best, but there's not much we can do if the neighbour doesn't accept. //m_commsProvider.InterRegion.TellRegionToCloseChildConnection(regionHandle, agentID); uint x = 0, y = 0; Util.RegionHandleToWorldLoc(regionHandle, out x, out y); GridRegion destination = m_scene.GridService.GetRegionByPosition(m_regionInfo.ScopeID, (int)x, (int)y); m_log.DebugFormat( "[SCENE COMMUNICATION SERVICE]: Sending close agent ID {0} to {1}", agentID, destination.RegionName); m_scene.SimulationService.CloseAgent(destination, agentID, auth_token); } private void InformNeighborsThatRegionisUpCompleted(IAsyncResult iar) { InformNeighbourThatRegionUpDelegate icon = (InformNeighbourThatRegionUpDelegate)iar.AsyncState; icon.EndInvoke(iar); } /// <summary> /// Asynchronous call to information neighbouring regions that this region is up /// </summary> /// <param name="region"></param> /// <param name="regionhandle"></param> private void InformNeighboursThatRegionIsUpAsync(INeighbourService neighbourService, RegionInfo region, ulong regionhandle) { uint x = 0, y = 0; Utils.LongToUInts(regionhandle, out x, out y); GridRegion neighbour = null; if (neighbourService != null) neighbour = neighbourService.HelloNeighbour(regionhandle, region); else m_log.DebugFormat( "[SCENE COMMUNICATION SERVICE]: No neighbour service provided for region {0} to inform neigbhours of status", m_scene.Name); if (neighbour != null) { m_log.DebugFormat( "[SCENE COMMUNICATION SERVICE]: Region {0} successfully informed neighbour {1} at {2}-{3} that it is up", m_scene.Name, neighbour.RegionName, Util.WorldToRegionLoc(x), Util.WorldToRegionLoc(y)); m_scene.EventManager.TriggerOnRegionUp(neighbour); } else { m_log.WarnFormat( "[SCENE COMMUNICATION SERVICE]: Region {0} failed to inform neighbour at {1}-{2} that it is up.", m_scene.Name, Util.WorldToRegionLoc(x), Util.WorldToRegionLoc(y)); } } /// <summary> /// This informs all neighboring regions about the settings of it's child agent. /// Calls an asynchronous method to do so.. so it doesn't lag the sim. /// /// This contains information, such as, Draw Distance, Camera location, Current Position, Current throttle settings, etc. /// /// </summary> private void SendChildAgentDataUpdateAsync(AgentPosition cAgentData, UUID scopeID, GridRegion dest) { //m_log.Info("[INTERGRID]: Informing neighbors about my agent in " + m_regionInfo.RegionName); try { m_scene.SimulationService.UpdateAgent(dest, cAgentData); } catch { // Ignore; we did our best } } private void SendChildAgentDataUpdateCompleted(IAsyncResult iar) { SendChildAgentDataUpdateDelegate icon = (SendChildAgentDataUpdateDelegate)iar.AsyncState; icon.EndInvoke(iar); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Gallery; using Microsoft.Azure.Gallery.Models; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Gallery { /// <summary> /// Operations for working with gallery items. /// </summary> internal partial class ItemOperations : IServiceOperations<GalleryClient>, IItemOperations { /// <summary> /// Initializes a new instance of the ItemOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal ItemOperations(GalleryClient client) { this._client = client; } private GalleryClient _client; /// <summary> /// Gets a reference to the Microsoft.Azure.Gallery.GalleryClient. /// </summary> public GalleryClient Client { get { return this._client; } } /// <summary> /// Gets a gallery items. /// </summary> /// <param name='itemIdentity'> /// Optional. Gallery item identity. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Gallery item information. /// </returns> public async Task<ItemGetParameters> GetAsync(string itemIdentity, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("itemIdentity", itemIdentity); Tracing.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = "/Microsoft.Gallery/galleryitems/" + (itemIdentity != null ? itemIdentity.Trim() : ""); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ItemGetParameters result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ItemGetParameters(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { GalleryItem itemInstance = new GalleryItem(); result.Item = itemInstance; JToken identityValue = responseDoc["identity"]; if (identityValue != null && identityValue.Type != JTokenType.Null) { string identityInstance = ((string)identityValue); itemInstance.Identity = identityInstance; } JToken itemNameValue = responseDoc["itemName"]; if (itemNameValue != null && itemNameValue.Type != JTokenType.Null) { string itemNameInstance = ((string)itemNameValue); itemInstance.Name = itemNameInstance; } JToken itemDisplayNameValue = responseDoc["itemDisplayName"]; if (itemDisplayNameValue != null && itemDisplayNameValue.Type != JTokenType.Null) { string itemDisplayNameInstance = ((string)itemDisplayNameValue); itemInstance.DisplayName = itemDisplayNameInstance; } JToken publisherValue = responseDoc["publisher"]; if (publisherValue != null && publisherValue.Type != JTokenType.Null) { string publisherInstance = ((string)publisherValue); itemInstance.Publisher = publisherInstance; } JToken publisherDisplayNameValue = responseDoc["publisherDisplayName"]; if (publisherDisplayNameValue != null && publisherDisplayNameValue.Type != JTokenType.Null) { string publisherDisplayNameInstance = ((string)publisherDisplayNameValue); itemInstance.PublisherDisplayName = publisherDisplayNameInstance; } JToken versionValue = responseDoc["version"]; if (versionValue != null && versionValue.Type != JTokenType.Null) { string versionInstance = ((string)versionValue); itemInstance.Version = versionInstance; } JToken summaryValue = responseDoc["summary"]; if (summaryValue != null && summaryValue.Type != JTokenType.Null) { string summaryInstance = ((string)summaryValue); itemInstance.Summary = summaryInstance; } JToken descriptionValue = responseDoc["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); itemInstance.Description = descriptionInstance; } JToken resourceGroupNameValue = responseDoc["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); itemInstance.ResourceGroupName = resourceGroupNameInstance; } JToken definitionTemplatesValue = responseDoc["definitionTemplates"]; if (definitionTemplatesValue != null && definitionTemplatesValue.Type != JTokenType.Null) { DefinitionTemplates definitionTemplatesInstance = new DefinitionTemplates(); itemInstance.DefinitionTemplates = definitionTemplatesInstance; JToken uiDefinitionFileUrlValue = definitionTemplatesValue["uiDefinitionFileUrl"]; if (uiDefinitionFileUrlValue != null && uiDefinitionFileUrlValue.Type != JTokenType.Null) { string uiDefinitionFileUrlInstance = ((string)uiDefinitionFileUrlValue); definitionTemplatesInstance.UiDefinitionFileUrl = uiDefinitionFileUrlInstance; } JToken defaultDeploymentTemplateIdValue = definitionTemplatesValue["defaultDeploymentTemplateId"]; if (defaultDeploymentTemplateIdValue != null && defaultDeploymentTemplateIdValue.Type != JTokenType.Null) { string defaultDeploymentTemplateIdInstance = ((string)defaultDeploymentTemplateIdValue); definitionTemplatesInstance.DefaultDeploymentTemplateId = defaultDeploymentTemplateIdInstance; } JToken deploymentTemplateFileUrlsSequenceElement = ((JToken)definitionTemplatesValue["deploymentTemplateFileUrls"]); if (deploymentTemplateFileUrlsSequenceElement != null && deploymentTemplateFileUrlsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in deploymentTemplateFileUrlsSequenceElement) { string deploymentTemplateFileUrlsKey = ((string)property.Name); string deploymentTemplateFileUrlsValue = ((string)property.Value); definitionTemplatesInstance.DeploymentTemplateFileUrls.Add(deploymentTemplateFileUrlsKey, deploymentTemplateFileUrlsValue); } } } JToken categoryIdsArray = responseDoc["categoryIds"]; if (categoryIdsArray != null && categoryIdsArray.Type != JTokenType.Null) { foreach (JToken categoryIdsValue in ((JArray)categoryIdsArray)) { itemInstance.CategoryIds.Add(((string)categoryIdsValue)); } } JToken screenshotUrlsArray = responseDoc["screenshotUrls"]; if (screenshotUrlsArray != null && screenshotUrlsArray.Type != JTokenType.Null) { foreach (JToken screenshotUrlsValue in ((JArray)screenshotUrlsArray)) { itemInstance.ScreenshotUrls.Add(((string)screenshotUrlsValue)); } } JToken iconFileUrlsSequenceElement = ((JToken)responseDoc["iconFileUrls"]); if (iconFileUrlsSequenceElement != null && iconFileUrlsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property2 in iconFileUrlsSequenceElement) { string iconFileUrlsKey = ((string)property2.Name); string iconFileUrlsValue = ((string)property2.Value); itemInstance.IconFileUrls.Add(iconFileUrlsKey, iconFileUrlsValue); } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets collection of gallery items. /// </summary> /// <param name='parameters'> /// Optional. Query parameters. If null is passed returns all gallery /// items. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List of gallery items. /// </returns> public async Task<ItemListResult> ListAsync(ItemListParameters parameters, CancellationToken cancellationToken) { // Validate // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("parameters", parameters); Tracing.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = "/Microsoft.Gallery/galleryitems?"; bool appendFilter = true; if (parameters != null && parameters.Filter != null) { appendFilter = false; url = url + "$filter=" + Uri.EscapeDataString(parameters.Filter != null ? parameters.Filter.Trim() : ""); } if (parameters != null && parameters.Top != null) { url = url + "&$top=" + Uri.EscapeDataString(parameters.Top.Value.ToString()); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ItemListResult result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ItemListResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken itemsArray = responseDoc; if (itemsArray != null && itemsArray.Type != JTokenType.Null) { foreach (JToken itemsValue in ((JArray)itemsArray)) { GalleryItem galleryItemInstance = new GalleryItem(); result.Items.Add(galleryItemInstance); JToken identityValue = itemsValue["identity"]; if (identityValue != null && identityValue.Type != JTokenType.Null) { string identityInstance = ((string)identityValue); galleryItemInstance.Identity = identityInstance; } JToken itemNameValue = itemsValue["itemName"]; if (itemNameValue != null && itemNameValue.Type != JTokenType.Null) { string itemNameInstance = ((string)itemNameValue); galleryItemInstance.Name = itemNameInstance; } JToken itemDisplayNameValue = itemsValue["itemDisplayName"]; if (itemDisplayNameValue != null && itemDisplayNameValue.Type != JTokenType.Null) { string itemDisplayNameInstance = ((string)itemDisplayNameValue); galleryItemInstance.DisplayName = itemDisplayNameInstance; } JToken publisherValue = itemsValue["publisher"]; if (publisherValue != null && publisherValue.Type != JTokenType.Null) { string publisherInstance = ((string)publisherValue); galleryItemInstance.Publisher = publisherInstance; } JToken publisherDisplayNameValue = itemsValue["publisherDisplayName"]; if (publisherDisplayNameValue != null && publisherDisplayNameValue.Type != JTokenType.Null) { string publisherDisplayNameInstance = ((string)publisherDisplayNameValue); galleryItemInstance.PublisherDisplayName = publisherDisplayNameInstance; } JToken versionValue = itemsValue["version"]; if (versionValue != null && versionValue.Type != JTokenType.Null) { string versionInstance = ((string)versionValue); galleryItemInstance.Version = versionInstance; } JToken summaryValue = itemsValue["summary"]; if (summaryValue != null && summaryValue.Type != JTokenType.Null) { string summaryInstance = ((string)summaryValue); galleryItemInstance.Summary = summaryInstance; } JToken descriptionValue = itemsValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); galleryItemInstance.Description = descriptionInstance; } JToken resourceGroupNameValue = itemsValue["resourceGroupName"]; if (resourceGroupNameValue != null && resourceGroupNameValue.Type != JTokenType.Null) { string resourceGroupNameInstance = ((string)resourceGroupNameValue); galleryItemInstance.ResourceGroupName = resourceGroupNameInstance; } JToken definitionTemplatesValue = itemsValue["definitionTemplates"]; if (definitionTemplatesValue != null && definitionTemplatesValue.Type != JTokenType.Null) { DefinitionTemplates definitionTemplatesInstance = new DefinitionTemplates(); galleryItemInstance.DefinitionTemplates = definitionTemplatesInstance; JToken uiDefinitionFileUrlValue = definitionTemplatesValue["uiDefinitionFileUrl"]; if (uiDefinitionFileUrlValue != null && uiDefinitionFileUrlValue.Type != JTokenType.Null) { string uiDefinitionFileUrlInstance = ((string)uiDefinitionFileUrlValue); definitionTemplatesInstance.UiDefinitionFileUrl = uiDefinitionFileUrlInstance; } JToken defaultDeploymentTemplateIdValue = definitionTemplatesValue["defaultDeploymentTemplateId"]; if (defaultDeploymentTemplateIdValue != null && defaultDeploymentTemplateIdValue.Type != JTokenType.Null) { string defaultDeploymentTemplateIdInstance = ((string)defaultDeploymentTemplateIdValue); definitionTemplatesInstance.DefaultDeploymentTemplateId = defaultDeploymentTemplateIdInstance; } JToken deploymentTemplateFileUrlsSequenceElement = ((JToken)definitionTemplatesValue["deploymentTemplateFileUrls"]); if (deploymentTemplateFileUrlsSequenceElement != null && deploymentTemplateFileUrlsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in deploymentTemplateFileUrlsSequenceElement) { string deploymentTemplateFileUrlsKey = ((string)property.Name); string deploymentTemplateFileUrlsValue = ((string)property.Value); definitionTemplatesInstance.DeploymentTemplateFileUrls.Add(deploymentTemplateFileUrlsKey, deploymentTemplateFileUrlsValue); } } } JToken categoryIdsArray = itemsValue["categoryIds"]; if (categoryIdsArray != null && categoryIdsArray.Type != JTokenType.Null) { foreach (JToken categoryIdsValue in ((JArray)categoryIdsArray)) { galleryItemInstance.CategoryIds.Add(((string)categoryIdsValue)); } } JToken screenshotUrlsArray = itemsValue["screenshotUrls"]; if (screenshotUrlsArray != null && screenshotUrlsArray.Type != JTokenType.Null) { foreach (JToken screenshotUrlsValue in ((JArray)screenshotUrlsArray)) { galleryItemInstance.ScreenshotUrls.Add(((string)screenshotUrlsValue)); } } JToken iconFileUrlsSequenceElement = ((JToken)itemsValue["iconFileUrls"]); if (iconFileUrlsSequenceElement != null && iconFileUrlsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property2 in iconFileUrlsSequenceElement) { string iconFileUrlsKey = ((string)property2.Name); string iconFileUrlsValue = ((string)property2.Value); galleryItemInstance.IconFileUrls.Add(iconFileUrlsKey, iconFileUrlsValue); } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Runtime.Serialization; using System.Threading.Tasks; namespace System.Xml { internal abstract class XmlStreamNodeWriter : XmlNodeWriter { private Stream _stream; private byte[] _buffer; private int _offset; private bool _ownsStream; private const int bufferLength = 512; private const int maxBytesPerChar = 3; private Encoding _encoding; private static UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true); protected XmlStreamNodeWriter() { _buffer = new byte[bufferLength]; } protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding) { _stream = stream; _ownsStream = ownsStream; _offset = 0; _encoding = encoding; } // Getting/Setting the Stream exists for fragmenting public Stream Stream { get { return _stream; } set { _stream = value; } } // StreamBuffer/BufferOffset exists only for the BinaryWriter to fix up nodes public byte[] StreamBuffer { get { return _buffer; } } public int BufferOffset { get { return _offset; } } public int Position { get { return (int)_stream.Position + _offset; } } private int GetByteCount(char[] chars) { if (_encoding == null) { return s_UTF8Encoding.GetByteCount(chars); } else { return _encoding.GetByteCount(chars); } } protected byte[] GetBuffer(int count, out int offset) { DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, ""); int bufferOffset = _offset; if (bufferOffset + count <= bufferLength) { offset = bufferOffset; } else { FlushBuffer(); offset = 0; } #if DEBUG DiagnosticUtility.DebugAssert(offset + count <= bufferLength, ""); for (int i = 0; i < count; i++) { _buffer[offset + i] = (byte)'<'; } #endif return _buffer; } protected async Task<BytesWithOffset> GetBufferAsync(int count) { int offset; DiagnosticUtility.DebugAssert(count >= 0 && count <= bufferLength, ""); int bufferOffset = _offset; if (bufferOffset + count <= bufferLength) { offset = bufferOffset; } else { await FlushBufferAsync().ConfigureAwait(false); offset = 0; } #if DEBUG DiagnosticUtility.DebugAssert(offset + count <= bufferLength, ""); for (int i = 0; i < count; i++) { _buffer[offset + i] = (byte)'<'; } #endif return new BytesWithOffset(_buffer, offset); } protected void Advance(int count) { DiagnosticUtility.DebugAssert(_offset + count <= bufferLength, ""); _offset += count; } private void EnsureByte() { if (_offset >= bufferLength) { FlushBuffer(); } } protected void WriteByte(byte b) { EnsureByte(); _buffer[_offset++] = b; } protected Task WriteByteAsync(byte b) { if (_offset >= bufferLength) { return FlushBufferAndWriteByteAsync(b); } else { _buffer[_offset++] = b; return Task.CompletedTask; } } private async Task FlushBufferAndWriteByteAsync(byte b) { await FlushBufferAsync().ConfigureAwait(false); _buffer[_offset++] = b; } protected void WriteByte(char ch) { DiagnosticUtility.DebugAssert(ch < 0x80, ""); WriteByte((byte)ch); } protected Task WriteByteAsync(char ch) { DiagnosticUtility.DebugAssert(ch < 0x80, ""); return WriteByteAsync((byte)ch); } protected void WriteBytes(byte b1, byte b2) { byte[] buffer = _buffer; int offset = _offset; if (offset + 1 >= bufferLength) { FlushBuffer(); offset = 0; } buffer[offset + 0] = b1; buffer[offset + 1] = b2; _offset += 2; } protected Task WriteBytesAsync(byte b1, byte b2) { if (_offset + 1 >= bufferLength) { return FlushAndWriteBytesAsync(b1, b2); } else { _buffer[_offset++] = b1; _buffer[_offset++] = b2; return Task.CompletedTask; } } private async Task FlushAndWriteBytesAsync(byte b1, byte b2) { await FlushBufferAsync().ConfigureAwait(false); _buffer[_offset++] = b1; _buffer[_offset++] = b2; } protected void WriteBytes(char ch1, char ch2) { DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, ""); WriteBytes((byte)ch1, (byte)ch2); } protected Task WriteBytesAsync(char ch1, char ch2) { DiagnosticUtility.DebugAssert(ch1 < 0x80 && ch2 < 0x80, ""); return WriteBytesAsync((byte)ch1, (byte)ch2); } public void WriteBytes(byte[] byteBuffer, int byteOffset, int byteCount) { if (byteCount < bufferLength) { int offset; byte[] buffer = GetBuffer(byteCount, out offset); Buffer.BlockCopy(byteBuffer, byteOffset, buffer, offset, byteCount); Advance(byteCount); } else { FlushBuffer(); _stream.Write(byteBuffer, byteOffset, byteCount); } } protected unsafe void UnsafeWriteBytes(byte* bytes, int byteCount) { FlushBuffer(); byte[] buffer = _buffer; while (byteCount >= bufferLength) { for (int i = 0; i < bufferLength; i++) buffer[i] = bytes[i]; _stream.Write(buffer, 0, bufferLength); bytes += bufferLength; byteCount -= bufferLength; } { for (int i = 0; i < byteCount; i++) buffer[i] = bytes[i]; _stream.Write(buffer, 0, byteCount); } } protected unsafe void WriteUTF8Char(int ch) { if (ch < 0x80) { WriteByte((byte)ch); } else if (ch <= char.MaxValue) { char* chars = stackalloc char[1]; chars[0] = (char)ch; UnsafeWriteUTF8Chars(chars, 1); } else { SurrogateChar surrogateChar = new SurrogateChar(ch); char* chars = stackalloc char[2]; chars[0] = surrogateChar.HighChar; chars[1] = surrogateChar.LowChar; UnsafeWriteUTF8Chars(chars, 2); } } protected void WriteUTF8Chars(byte[] chars, int charOffset, int charCount) { if (charCount < bufferLength) { int offset; byte[] buffer = GetBuffer(charCount, out offset); Buffer.BlockCopy(chars, charOffset, buffer, offset, charCount); Advance(charCount); } else { FlushBuffer(); _stream.Write(chars, charOffset, charCount); } } protected unsafe void WriteUTF8Chars(string value) { int count = value.Length; if (count > 0) { fixed (char* chars = value) { UnsafeWriteUTF8Chars(chars, count); } } } protected unsafe void UnsafeWriteUTF8Chars(char* chars, int charCount) { const int charChunkSize = bufferLength / maxBytesPerChar; while (charCount > charChunkSize) { int offset; int chunkSize = charChunkSize; if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate chunkSize--; byte[] buffer = GetBuffer(chunkSize * maxBytesPerChar, out offset); Advance(UnsafeGetUTF8Chars(chars, chunkSize, buffer, offset)); charCount -= chunkSize; chars += chunkSize; } if (charCount > 0) { int offset; byte[] buffer = GetBuffer(charCount * maxBytesPerChar, out offset); Advance(UnsafeGetUTF8Chars(chars, charCount, buffer, offset)); } } protected unsafe void UnsafeWriteUnicodeChars(char* chars, int charCount) { const int charChunkSize = bufferLength / 2; while (charCount > charChunkSize) { int offset; int chunkSize = charChunkSize; if ((int)(chars[chunkSize - 1] & 0xFC00) == 0xD800) // This is a high surrogate chunkSize--; byte[] buffer = GetBuffer(chunkSize * 2, out offset); Advance(UnsafeGetUnicodeChars(chars, chunkSize, buffer, offset)); charCount -= chunkSize; chars += chunkSize; } if (charCount > 0) { int offset; byte[] buffer = GetBuffer(charCount * 2, out offset); Advance(UnsafeGetUnicodeChars(chars, charCount, buffer, offset)); } } protected unsafe int UnsafeGetUnicodeChars(char* chars, int charCount, byte[] buffer, int offset) { char* charsMax = chars + charCount; while (chars < charsMax) { char value = *chars++; buffer[offset++] = (byte)value; value >>= 8; buffer[offset++] = (byte)value; } return charCount * 2; } protected unsafe int UnsafeGetUTF8Length(char* chars, int charCount) { char* charsMax = chars + charCount; while (chars < charsMax) { if (*chars >= 0x80) break; chars++; } if (chars == charsMax) return charCount; char[] chArray = new char[charsMax - chars]; for (int i = 0; i < chArray.Length; i++) { chArray[i] = chars[i]; } return (int)(chars - (charsMax - charCount)) + GetByteCount(chArray); } protected unsafe int UnsafeGetUTF8Chars(char* chars, int charCount, byte[] buffer, int offset) { if (charCount > 0) { fixed (byte* _bytes = &buffer[offset]) { byte* bytes = _bytes; byte* bytesMax = &bytes[buffer.Length - offset]; char* charsMax = &chars[charCount]; while (true) { while (chars < charsMax) { char t = *chars; if (t >= 0x80) break; *bytes = (byte)t; bytes++; chars++; } if (chars >= charsMax) break; char* charsStart = chars; while (chars < charsMax && *chars >= 0x80) { chars++; } bytes += (_encoding ?? s_UTF8Encoding).GetBytes(charsStart, (int)(chars - charsStart), bytes, (int)(bytesMax - bytes)); if (chars >= charsMax) break; } return (int)(bytes - _bytes); } } return 0; } protected virtual void FlushBuffer() { if (_offset != 0) { _stream.Write(_buffer, 0, _offset); _offset = 0; } } protected virtual Task FlushBufferAsync() { if (_offset != 0) { var task = _stream.WriteAsync(_buffer, 0, _offset); _offset = 0; return task; } return Task.CompletedTask; } public override void Flush() { FlushBuffer(); _stream.Flush(); } public override async Task FlushAsync() { await FlushBufferAsync().ConfigureAwait(false); await _stream.FlushAsync().ConfigureAwait(false); } public override void Close() { if (_stream != null) { if (_ownsStream) { _stream.Dispose(); } _stream = null; } } } }
using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Design; using System.Windows.Forms; using System.ComponentModel; using System.Runtime.InteropServices; using System.Windows.Forms.VisualStyles; // Taken from http://www.codeproject.com/Articles/23746/TreeView-with-Columns with minor tweaks // and fixes for my purposes. namespace TreelistView { [Designer(typeof(TreeListViewDesigner))] public class TreeListView : Control, ISupportInitialize { public event TreeViewEventHandler AfterSelect; protected virtual void OnAfterSelect(Node node) { raiseAfterSelect(node); } protected virtual void raiseAfterSelect(Node node) { if (AfterSelect != null && node != null) AfterSelect(this, new TreeViewEventArgs(null)); } public delegate void NotifyBeforeExpandHandler(Node node, bool isExpanding); public event NotifyBeforeExpandHandler NotifyBeforeExpand; public virtual void OnNotifyBeforeExpand(Node node, bool isExpanding) { raiseNotifyBeforeExpand(node, isExpanding); } protected virtual void raiseNotifyBeforeExpand(Node node, bool isExpanding) { if (NotifyBeforeExpand != null) NotifyBeforeExpand(node, isExpanding); } public delegate void NotifyAfterHandler(Node node, bool isExpanding); public event NotifyAfterHandler NotifyAfterExpand; public virtual void OnNotifyAfterExpand(Node node, bool isExpanded) { raiseNotifyAfterExpand(node, isExpanded); } protected virtual void raiseNotifyAfterExpand(Node node, bool isExpanded) { if (NotifyAfterExpand != null) NotifyAfterExpand(node, isExpanded); } public delegate void NodeDoubleClickedHandler(Node node); public event NodeDoubleClickedHandler NodeDoubleClicked; public virtual void OnNodeDoubleClicked(Node node) { raiseNodeDoubleClicked(node); } protected virtual void raiseNodeDoubleClicked(Node node) { if (NodeDoubleClicked != null) NodeDoubleClicked(node); } public delegate void NodeClickedHandler(Node node); public event NodeClickedHandler NodeClicked; public virtual void OnNodeClicked(Node node) { raiseNodeClicked(node); } protected virtual void raiseNodeClicked(Node node) { if (NodeClicked != null) NodeClicked(node); } TreeListViewNodes m_nodes; TreeListColumnCollection m_columns; TreeList.RowSetting m_rowSetting; TreeList.ViewSetting m_viewSetting; Color m_GridLineColour = SystemColors.Control; Image m_SelectedImage = null; [Category("Columns")] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TreeListColumnCollection Columns { get { return m_columns; } } [Category("Options")] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TreeList.CollumnSetting ColumnsOptions { get { return m_columns.Options; } } [Category("Options")] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TreeList.RowSetting RowOptions { get { return m_rowSetting; } } [Category("Options")] [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] public TreeList.ViewSetting ViewOptions { get { return m_viewSetting; } } [Category("Behavior")] [DefaultValue(typeof(bool), "True")] public bool MultiSelect { get { return m_multiSelect; } set { m_multiSelect = value; } } [Category("Behavior")] [DefaultValue(typeof(int), "0")] public int TreeColumn { get { return m_treeColumn; } set { m_treeColumn = value; if(value >= m_columns.Count) throw new ArgumentOutOfRangeException("Tree column index invalid"); } } private int GetTreeColumn(Node n) { if (n != null && n.TreeColumn >= 0) return n.TreeColumn; return m_treeColumn; } [Category("Behavior")] [DefaultValue(typeof(bool), "False")] public bool AlwaysDisplayVScroll { get { return m_vScrollAlways; } set { m_vScrollAlways = value; } } [Category("Behavior")] [DefaultValue(typeof(bool), "False")] public bool AlwaysDisplayHScroll { get { return m_hScrollAlways; } set { m_hScrollAlways = value; } } [Category("Appearance")] [DefaultValue(typeof(Image), null)] public Image SelectedImage { get { return m_SelectedImage; } set { m_SelectedImage = value; } } [DefaultValue(typeof(Color), "Window")] public new Color BackColor { get { return base.BackColor; } set { base.BackColor = value; } } [Category("Appearance")] [DefaultValue(typeof(Color), "Control")] public Color GridLineColour { get { return m_GridLineColour; } set { m_GridLineColour = value; } } //[Browsable(false)] public TreeListViewNodes Nodes { get { return m_nodes; } } public TreeListView() { this.DoubleBuffered = true; this.BackColor = SystemColors.Window; this.TabStop = true; m_tooltip = new ToolTip(); m_tooltipVisible = false; m_tooltip.InitialDelay = 0; m_tooltip.UseAnimation = false; m_tooltip.UseFading = false; m_tooltipNode = null; m_tooltipTimer = new Timer(); m_tooltipTimer.Stop(); m_tooltipTimer.Interval = 500; m_tooltipTimer.Tick += new EventHandler(tooltipTick); m_rowPainter = new RowPainter(); m_cellPainter = new CellPainter(this); m_nodes = new TreeListViewNodes(this); m_rowSetting = new TreeList.RowSetting(this); m_viewSetting = new TreeList.ViewSetting(this); m_columns = new TreeListColumnCollection(this); AddScrollBars(); } protected override void Dispose(bool disposing) { m_tooltipTimer.Stop(); if(m_tooltipVisible) m_tooltip.Hide(this); m_tooltip.Dispose(); base.Dispose(disposing); } void tooltipTick(object sender, EventArgs e) { m_tooltipTimer.Stop(); if (m_tooltipNode == null) { m_tooltip.Hide(this); m_tooltipVisible = false; return; } Node node = m_tooltipNode; Point p = PointToClient(Cursor.Position); if (!ClientRectangle.Contains(p)) { m_tooltip.Hide(this); m_tooltipVisible = false; return; } int visibleRowIndex = CalcHitRow(PointToClient(Cursor.Position)); Rectangle rowRect = CalcRowRectangle(visibleRowIndex); rowRect.X = RowHeaderWidth() - HScrollValue(); rowRect.Width = Columns.ColumnsWidth; // draw the current node foreach (TreeListColumn col in Columns.VisibleColumns) { if (col.Index == GetTreeColumn(node)) { Rectangle cellRect = rowRect; cellRect.X = col.CalculatedRect.X - HScrollValue(); int lineindet = 10; // add left margin cellRect.X += Columns.Options.LeftMargin; // add indent size cellRect.X += GetIndentSize(node) + 5; cellRect.X += lineindet; Rectangle plusminusRect = GetPlusMinusRectangle(node, col, visibleRowIndex); if (!ViewOptions.ShowLine && (!ViewOptions.ShowPlusMinus || (!ViewOptions.PadForPlusMinus && plusminusRect == Rectangle.Empty))) cellRect.X -= (lineindet + 5); if (SelectedImage != null && (NodesSelection.Contains(node) || FocusedNode == node)) cellRect.X += (SelectedImage.Width + 2); Image icon = GetHoverNodeBitmap(node); if (icon != null) cellRect.X += (icon.Width + 2); string datastring = ""; object data = GetData(node, col); if(data == null) data = ""; if (CellPainter.CellDataConverter != null) datastring = CellPainter.CellDataConverter(col, data); else datastring = data.ToString(); if(datastring.Length > 0) { m_tooltip.Show(datastring, this, cellRect.X, cellRect.Y); m_tooltipVisible = true; } } } } public void RecalcLayout() { if (m_firstVisibleNode == null) m_firstVisibleNode = Nodes.FirstNode; if (Nodes.Count == 0) m_firstVisibleNode = null; UpdateScrollBars(); m_columns.RecalcVisibleColumsRect(); UpdateScrollBars(); m_columns.RecalcVisibleColumsRect(); int vscroll = VScrollValue(); if (vscroll == 0) m_firstVisibleNode = Nodes.FirstNode; else m_firstVisibleNode = NodeCollection.GetNextNode(Nodes.FirstNode, vscroll); Invalidate(); } void AddScrollBars() { // I was not able to get the wanted behavior by using ScrollableControl with AutoScroll enabled. // horizontal scrolling is ok to do it by pixels, but for vertical I want to maintain the headers // and only scroll the rows. // I was not able to manually overwrite the vscroll bar handling to get this behavior, instead I opted for // custom implementation of scrollbars // to get the 'filler' between hscroll and vscroll I dock scroll + filler in a panel m_hScroll = new HScrollBar(); m_hScroll.Scroll += new ScrollEventHandler(OnHScroll); m_hScroll.Dock = DockStyle.Fill; m_vScroll = new VScrollBar(); m_vScroll.Scroll += new ScrollEventHandler(OnVScroll); m_vScroll.Dock = DockStyle.Right; m_hScrollFiller = new Panel(); m_hScrollFiller.BackColor = Color.Transparent; m_hScrollFiller.Size = new Size(m_vScroll.Width-1, m_hScroll.Height); m_hScrollFiller.Dock = DockStyle.Right; Controls.Add(m_vScroll); m_hScrollPanel = new Panel(); m_hScrollPanel.Height = m_hScroll.Height; m_hScrollPanel.Dock = DockStyle.Bottom; m_hScrollPanel.Controls.Add(m_hScroll); m_hScrollPanel.Controls.Add(m_hScrollFiller); Controls.Add(m_hScrollPanel); // try and force handle creation here, as it can fail randomly // at runtime with weird side-effects (See github #202). bool handlesCreated = false; handlesCreated |= m_hScroll.Handle.ToInt64() > 0; handlesCreated |= m_vScroll.Handle.ToInt64() > 0; handlesCreated |= m_hScrollFiller.Handle.ToInt64() > 0; handlesCreated |= m_hScrollPanel.Handle.ToInt64() > 0; if (!handlesCreated) renderdoc.StaticExports.LogText("Couldn't create any handles!"); } ToolTip m_tooltip; Node m_tooltipNode; Timer m_tooltipTimer; bool m_tooltipVisible; VScrollBar m_vScroll; HScrollBar m_hScroll; Panel m_hScrollFiller; Panel m_hScrollPanel; bool m_multiSelect = true; int m_treeColumn = 0; bool m_vScrollAlways = false; bool m_hScrollAlways = false; Node m_firstVisibleNode = null; RowPainter m_rowPainter; CellPainter m_cellPainter; [Browsable(false)] public CellPainter CellPainter { get { return m_cellPainter; } set { m_cellPainter = value; } } TreeListColumn m_resizingColumn; int m_resizingColumnScrollOffset; int m_resizingColumnLeft; TreeListColumn m_movingColumn; NodesSelection m_nodesSelection = new NodesSelection(); Node m_focusedNode = null; [Browsable(false)] public NodesSelection NodesSelection { get { return m_nodesSelection; } } public void SortNodesSelection() { m_nodesSelection.Sort(); } [Browsable(false)] public Node SelectedNode { get { return m_nodesSelection.Count == 0 ? FocusedNode : m_nodesSelection[0]; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public Node FocusedNode { get { return m_focusedNode; } set { Node curNode = FocusedNode; if (object.ReferenceEquals(curNode, value)) return; if (MultiSelect == false) NodesSelection.Clear(); int oldrow = NodeCollection.GetVisibleNodeIndex(curNode); int newrow = NodeCollection.GetVisibleNodeIndex(value); m_focusedNode = value; OnAfterSelect(value); InvalidateRow(oldrow); InvalidateRow(newrow); EnsureVisible(m_focusedNode); } } public void EnsureVisible(Node node) { int screenvisible = MaxVisibleRows() - 1; int visibleIndex = NodeCollection.GetVisibleNodeIndex(node); if (visibleIndex < VScrollValue()) { SetVScrollValue(visibleIndex); } if (visibleIndex > VScrollValue() + screenvisible) { SetVScrollValue(visibleIndex - screenvisible); } } public Node CalcHitNode(Point mousepoint) { if (!ClientRectangle.Contains(mousepoint)) return null; int hitrow = CalcHitRow(mousepoint); if (hitrow < 0) return null; return NodeCollection.GetNextNode(m_firstVisibleNode, hitrow); } public Node GetHitNode() { return CalcHitNode(PointToClient(Control.MousePosition)); } public TreelistView.HitInfo CalcColumnHit(Point mousepoint) { return Columns.CalcHitInfo(mousepoint, HScrollValue()); } public bool HitTestScrollbar(Point mousepoint) { if (m_hScroll.Visible && mousepoint.Y >= ClientRectangle.Height - m_hScroll.Height) return true; return false; } protected override void OnSizeChanged(EventArgs e) { base.OnSizeChanged(e); if (ClientRectangle.Width > 0 && ClientRectangle.Height > 0) { Columns.RecalcVisibleColumsRect(); UpdateScrollBars(); Columns.RecalcVisibleColumsRect(); } } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); RecalcLayout(); } protected virtual void BeforeShowContextMenu() { } protected void InvalidateRow(int absoluteRowIndex) { int visibleRowIndex = absoluteRowIndex - VScrollValue(); Rectangle r = CalcRowRectangle(visibleRowIndex); if (r != Rectangle.Empty) { r.Inflate(1,1); Invalidate(r); } } void OnVScroll(object sender, ScrollEventArgs e) { int diff = e.NewValue - e.OldValue; //assumedScrollPos += diff; if (e.NewValue == 0) { m_firstVisibleNode = Nodes.FirstNode; diff = 0; } m_firstVisibleNode = NodeCollection.GetNextNode(m_firstVisibleNode, diff); Invalidate(); } void OnHScroll(object sender, ScrollEventArgs e) { Invalidate(); } public void SetVScrollValue(int value) { if (value < 0) value = 0; int max = m_vScroll.Maximum - m_vScroll.LargeChange + 1; if (value > max) value = max; if ((value >= 0 && value <= max) && (value != m_vScroll.Value)) { ScrollEventArgs e = new ScrollEventArgs(ScrollEventType.ThumbPosition, m_vScroll.Value, value, ScrollOrientation.VerticalScroll); // setting the scroll value does not cause a Scroll event m_vScroll.Value = value; // so we have to fake it OnVScroll(m_vScroll, e); } } public int VScrollValue() { if (m_vScroll.Visible == false) return 0; return m_vScroll.Value; } int HScrollValue() { if (m_hScroll.Visible == false) return 0; return m_hScroll.Value; } void UpdateScrollBars() { if (ClientRectangle.Width < 0) return; int maxvisiblerows = MaxVisibleRows(); int totalrows = Nodes.VisibleNodeCount; m_vScroll.SmallChange = 1; m_vScroll.LargeChange = Math.Max(1, maxvisiblerows); m_vScroll.Enabled = true; m_vScroll.Minimum = 0; m_vScroll.Maximum = Math.Max(1,totalrows - 1); if (maxvisiblerows >= totalrows) { m_vScroll.Visible = false; SetVScrollValue(0); if (m_vScrollAlways) { m_vScroll.Visible = true; m_vScroll.Enabled = false; } } else { m_vScroll.Visible = true; int maxscrollvalue = m_vScroll.Maximum - m_vScroll.LargeChange; if (maxscrollvalue < m_vScroll.Value) SetVScrollValue(maxscrollvalue); } m_hScroll.Enabled = true; if (ClientRectangle.Width > MinWidth()) { m_hScrollPanel.Visible = false; m_hScroll.Value = 0; if (m_hScrollAlways) { m_hScroll.Enabled = false; m_hScrollPanel.Visible = true; m_hScroll.Minimum = 0; m_hScroll.Maximum = 0; m_hScroll.SmallChange = 1; m_hScroll.LargeChange = 1; m_hScrollFiller.Visible = m_vScroll.Visible; } } else { m_hScroll.Minimum = 0; m_hScroll.Maximum = Math.Max(1, MinWidth()); m_hScroll.SmallChange = 5; m_hScroll.LargeChange = Math.Max(1, ClientRectangle.Width); m_hScrollFiller.Visible = m_vScroll.Visible; m_hScrollPanel.Visible = true; } } int m_hotrow = -1; int CalcHitRow(Point mousepoint) { if (mousepoint.Y <= Columns.Options.HeaderHeight) return -1; return (mousepoint.Y - Columns.Options.HeaderHeight) / RowOptions.ItemHeight; } int VisibleRowToYPoint(int visibleRowIndex) { return Columns.Options.HeaderHeight + (visibleRowIndex * RowOptions.ItemHeight); } Rectangle CalcRowRectangle(int visibleRowIndex) { Rectangle r = ClientRectangle; r.Y = VisibleRowToYPoint(visibleRowIndex); if (r.Top < Columns.Options.HeaderHeight || r.Top > ClientRectangle.Height) return Rectangle.Empty; r.Height = RowOptions.ItemHeight; return r; } void MultiSelectAdd(Node clickedNode, Keys modifierKeys) { if (Control.ModifierKeys == Keys.None) { foreach (Node node in NodesSelection) { int newrow = NodeCollection.GetVisibleNodeIndex(node); InvalidateRow(newrow); } NodesSelection.Clear(); NodesSelection.Add(clickedNode); } if (Control.ModifierKeys == Keys.Shift) { if (NodesSelection.Count == 0) NodesSelection.Add(clickedNode); else { int startrow = NodeCollection.GetVisibleNodeIndex(NodesSelection[0]); int currow = NodeCollection.GetVisibleNodeIndex(clickedNode); if (currow > startrow) { Node startingNode = NodesSelection[0]; NodesSelection.Clear(); foreach (Node node in NodeCollection.ForwardNodeIterator(startingNode, clickedNode, true)) NodesSelection.Add(node); Invalidate(); } if (currow < startrow) { Node startingNode = NodesSelection[0]; NodesSelection.Clear(); foreach (Node node in NodeCollection.ReverseNodeIterator(startingNode, clickedNode, true)) NodesSelection.Add(node); Invalidate(); } } } if (Control.ModifierKeys == Keys.Control) { if (NodesSelection.Contains(clickedNode)) NodesSelection.Remove(clickedNode); else NodesSelection.Add(clickedNode); } InvalidateRow(NodeCollection.GetVisibleNodeIndex(clickedNode)); FocusedNode = clickedNode; } internal event MouseEventHandler AfterResizingColumn; protected override void OnMouseClick(MouseEventArgs e) { if (e.Button == MouseButtons.Left) { Point mousePoint = new Point(e.X, e.Y); Node clickedNode = CalcHitNode(mousePoint); if (clickedNode != null && Columns.Count > 0) { int clickedRow = CalcHitRow(mousePoint); Rectangle glyphRect = Rectangle.Empty; int treeColumn = GetTreeColumn(clickedNode); if (treeColumn >= 0) glyphRect = GetPlusMinusRectangle(clickedNode, Columns[treeColumn], clickedRow); if (clickedNode.HasChildren && glyphRect != Rectangle.Empty && glyphRect.Contains(mousePoint)) clickedNode.Expanded = !clickedNode.Expanded; var columnHit = CalcColumnHit(mousePoint); if (glyphRect == Rectangle.Empty && columnHit.Column != null && columnHit.Column.Index == treeColumn && GetNodeBitmap(clickedNode) != null) { OnNodeClicked(clickedNode); } if (MultiSelect) { MultiSelectAdd(clickedNode, Control.ModifierKeys); } else FocusedNode = clickedNode; } /* else { FocusedNode = null; NodesSelection.Clear(); }*/ } base.OnMouseClick(e); } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (m_movingColumn != null) { m_movingColumn.Moving = true; Cursor = Cursors.SizeAll; var idx = m_movingColumn.VisibleIndex; if (idx + 1 < Columns.VisibleColumns.Length) { var nextcol = Columns.VisibleColumns[idx + 1]; if (nextcol.CalculatedRect.X + (nextcol.CalculatedRect.Width * 3) / 4 < e.X) { Columns.SetVisibleIndex(m_movingColumn, idx + 1); } } if (idx - 1 >= 0) { var prevcol = Columns.VisibleColumns[idx - 1]; if (prevcol.CalculatedRect.Right - (prevcol.CalculatedRect.Width * 3) / 4 > e.X) { Columns.SetVisibleIndex(m_movingColumn, idx - 1); } } Columns.RecalcVisibleColumsRect(true); Invalidate(); return; } if (m_resizingColumn != null) { // if we've clicked on an autosize column, actually resize the next one along. if (m_resizingColumn.AutoSize) { if (Columns.VisibleColumns.Length > m_resizingColumn.VisibleIndex + 1) { TreeListColumn realResizeColumn = Columns.VisibleColumns[m_resizingColumn.VisibleIndex + 1]; int right = realResizeColumn.CalculatedRect.Right - m_resizingColumnScrollOffset; int width = right - e.X; if (width < 10) width = 10; bool resize = true; if (Columns.VisibleColumns.Length > realResizeColumn.VisibleIndex + 1) if (Columns.VisibleColumns[realResizeColumn.VisibleIndex + 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width) resize = false; if (realResizeColumn.VisibleIndex > 1) if (Columns.VisibleColumns[realResizeColumn.VisibleIndex - 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width) resize = false; if (resize) { realResizeColumn.Width = width; } } } else { int left = m_resizingColumnLeft; int width = e.X - left; if (width < 10) width = 10; bool resize = true; if (Columns.VisibleColumns.Length > m_resizingColumn.VisibleIndex + 1) if (Columns.VisibleColumns[m_resizingColumn.VisibleIndex + 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width) resize = false; if (m_resizingColumn.internalIndex > 1) if (Columns.VisibleColumns[m_resizingColumn.VisibleIndex - 1].CalculatedRect.Width <= 10 && m_resizingColumn.Width < width) resize = false; if (resize) m_resizingColumn.Width = width; } Columns.RecalcVisibleColumsRect(true); Invalidate(); return; } TreeListColumn hotcol = null; TreelistView.HitInfo info = Columns.CalcHitInfo(new Point(e.X, e.Y), HScrollValue()); if ((int)(info.HitType & HitInfo.eHitType.kColumnHeader) > 0) hotcol = info.Column; Node clickedNode = CalcHitNode(new Point(e.X, e.Y)); if ((int)(info.HitType & HitInfo.eHitType.kColumnHeaderResize) > 0) Cursor = Cursors.VSplit; else if (info.Column != null && info.Column.Index == GetTreeColumn(clickedNode) && GetNodeBitmap(clickedNode) != null && m_viewSetting.HoverHandTreeColumn) Cursor = Cursors.Hand; else Cursor = Cursors.Arrow; if (!this.DesignMode && clickedNode != null && clickedNode.ClippedText) { m_tooltipNode = clickedNode; m_tooltipTimer.Start(); } else { m_tooltipNode = null; m_tooltip.Hide(this); m_tooltipVisible = false; m_tooltipTimer.Stop(); } if (GetHoverNodeBitmap(clickedNode) != null && GetNodeBitmap(clickedNode) != GetHoverNodeBitmap(clickedNode)) Invalidate(); SetHotColumn(hotcol, true); int vScrollOffset = VScrollValue(); int newhotrow = -1; if (hotcol == null) { int row = (e.Y - Columns.Options.HeaderHeight) / RowOptions.ItemHeight; newhotrow = row + vScrollOffset; } if (newhotrow != m_hotrow) { InvalidateRow(m_hotrow); m_hotrow = newhotrow; InvalidateRow(m_hotrow); } } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); SetHotColumn(null, false); Cursor = Cursors.Arrow; Invalidate(); } protected override void OnMouseWheel(MouseEventArgs e) { m_tooltip.Hide(this); m_tooltipVisible = false; m_tooltipTimer.Stop(); int value = m_vScroll.Value - (e.Delta * SystemInformation.MouseWheelScrollLines / 120); if (m_vScroll.Visible) SetVScrollValue(value); base.OnMouseWheel(e); } protected override void OnMouseDown(MouseEventArgs e) { m_tooltip.Hide(this); m_tooltipVisible = false; m_tooltipTimer.Stop(); this.Focus(); if (e.Button == MouseButtons.Right) { Point mousePoint = new Point(e.X, e.Y); Node clickedNode = CalcHitNode(mousePoint); if (clickedNode != null) { // if multi select the selection is cleard if clicked node is not in selection if (MultiSelect) { if (NodesSelection.Contains(clickedNode) == false) MultiSelectAdd(clickedNode, Control.ModifierKeys); } FocusedNode = clickedNode; Invalidate(); } BeforeShowContextMenu(); } if (e.Button == MouseButtons.Left) { TreelistView.HitInfo info = Columns.CalcHitInfo(new Point(e.X, e.Y), HScrollValue()); if ((int)(info.HitType & HitInfo.eHitType.kColumnHeaderResize) > 0) { m_resizingColumn = info.Column; m_resizingColumnScrollOffset = HScrollValue(); m_resizingColumnLeft = m_resizingColumn.CalculatedRect.Left - m_resizingColumnScrollOffset; return; } if ((int)(info.HitType & HitInfo.eHitType.kColumnHeader) > 0 && m_viewSetting.UserRearrangeableColumns) { m_movingColumn = info.Column; return; } } base.OnMouseDown(e); } protected override void OnMouseUp(MouseEventArgs e) { if (m_resizingColumn != null) { m_resizingColumn = null; Columns.RecalcVisibleColumsRect(); UpdateScrollBars(); Invalidate(); if (AfterResizingColumn != null) AfterResizingColumn(this, e); } if (m_movingColumn != null) { m_movingColumn.Moving = false; m_movingColumn = null; Cursor = Cursors.Arrow; Columns.RecalcVisibleColumsRect(); UpdateScrollBars(); Invalidate(); } base.OnMouseUp(e); } protected override void OnMouseDoubleClick(MouseEventArgs e) { base.OnMouseDoubleClick(e); Point mousePoint = new Point(e.X, e.Y); Node clickedNode = CalcHitNode(mousePoint); if (clickedNode != null && clickedNode.HasChildren) clickedNode.Expanded = !clickedNode.Expanded; if (clickedNode != null) OnNodeDoubleClicked(clickedNode); } // Somewhere I read that it could be risky to do any handling in GetFocus / LostFocus. // The reason is that it will throw exception incase you make a call which recreates the windows handle (e.g. // change the border style. Instead one should always use OnEnter and OnLeave instead. That is why I'm using // OnEnter and OnLeave instead, even though I'm only doing Invalidate. protected override void OnEnter(EventArgs e) { base.OnEnter(e); Invalidate(); } protected override void OnLeave(EventArgs e) { m_tooltipNode = null; m_tooltip.Hide(this); m_tooltipVisible = false; m_tooltipTimer.Stop(); base.OnLeave(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { m_tooltipNode = null; m_tooltip.Hide(this); m_tooltipVisible = false; m_tooltipTimer.Stop(); base.OnLostFocus(e); Invalidate(); } void SetHotColumn(TreeListColumn col, bool ishot) { int scrolloffset = HScrollValue(); if (col != m_hotColumn) { if (m_hotColumn != null) { m_hotColumn.ishot = false; Rectangle r = m_hotColumn.CalculatedRect; r.X -= scrolloffset; Invalidate(r); } m_hotColumn = col; if (m_hotColumn != null) { m_hotColumn.ishot = ishot; Rectangle r = m_hotColumn.CalculatedRect; r.X -= scrolloffset; Invalidate(r); } } } internal int RowHeaderWidth() { if (RowOptions.ShowHeader) return RowOptions.HeaderWidth; return 0; } int MinWidth() { return RowHeaderWidth() + Columns.ColumnsWidth; } int MaxVisibleRows(out int remainder) { remainder = 0; if (ClientRectangle.Height < 0) return 0; int height = ClientRectangle.Height - Columns.Options.HeaderHeight; //return (int) Math.Ceiling((double)(ClientRectangle.Height - Columns.HeaderHeight) / (double)Nodes.ItemHeight); remainder = (ClientRectangle.Height - Columns.Options.HeaderHeight) % RowOptions.ItemHeight ; return Math.Max(0, (ClientRectangle.Height - Columns.Options.HeaderHeight) / RowOptions.ItemHeight); } int MaxVisibleRows() { int unused; return MaxVisibleRows(out unused); } public void BeginUpdate() { m_nodes.BeginUpdate(); } public void EndUpdate() { m_nodes.EndUpdate(); RecalcLayout(); Invalidate(); } protected override CreateParams CreateParams { get { const int WS_BORDER = 0x00800000; const int WS_EX_CLIENTEDGE = 0x00000200; CreateParams p = base.CreateParams; p.Style &= ~(int)WS_BORDER; p.ExStyle &= ~(int)WS_EX_CLIENTEDGE; switch (ViewOptions.BorderStyle) { case BorderStyle.Fixed3D: p.ExStyle |= (int)WS_EX_CLIENTEDGE; break; case BorderStyle.FixedSingle: p.Style |= (int)WS_BORDER; break; default: break; } return p; } } TreeListColumn m_hotColumn = null; object GetDataDesignMode(Node node, TreeListColumn column) { string id = string.Empty; while (node != null) { id = node.Owner.GetNodeIndex(node).ToString() + ":" + id; node = node.Parent; } return "<temp>" + id; } protected virtual object GetData(Node node, TreeListColumn column) { if (node[column.Index] != null) return node[column.Index]; return null; } public new Rectangle ClientRectangle { get { Rectangle r = base.ClientRectangle; if (m_vScroll.Visible) r.Width -= m_vScroll.Width+1; if (m_hScroll.Visible) r.Height -= m_hScroll.Height+1; return r; } } protected virtual TreelistView.TreeList.TextFormatting GetFormatting(TreelistView.Node node, TreelistView.TreeListColumn column) { return column.CellFormat; } protected virtual void PaintCellPlusMinus(Graphics dc, Rectangle glyphRect, Node node, TreeListColumn column) { CellPainter.PaintCellPlusMinus(dc, glyphRect, node, column, GetFormatting(node, column)); } protected virtual void PaintCellBackground(Graphics dc, Rectangle cellRect, Node node, TreeListColumn column) { if (this.DesignMode) CellPainter.PaintCellBackground(dc, cellRect, node, column, GetFormatting(node, column), GetDataDesignMode(node, column)); else CellPainter.PaintCellBackground(dc, cellRect, node, column, GetFormatting(node, column), GetData(node, column)); } protected virtual void PaintCellText(Graphics dc, Rectangle cellRect, Node node, TreeListColumn column) { if (this.DesignMode) CellPainter.PaintCellText(dc, cellRect, node, column, GetFormatting(node, column), GetDataDesignMode(node, column)); else CellPainter.PaintCellText(dc, cellRect, node, column, GetFormatting(node, column), GetData(node, column)); } protected virtual void PaintImage(Graphics dc, Rectangle imageRect, Node node, Image image) { if (image != null) dc.DrawImage(image, imageRect.X, imageRect.Y, imageRect.Width, imageRect.Height); } protected virtual void PaintNode(Graphics dc, Rectangle rowRect, Node node, TreeListColumn[] visibleColumns, int visibleRowIndex) { CellPainter.DrawSelectionBackground(dc, rowRect, node); foreach (TreeListColumn col in visibleColumns) { if (col.CalculatedRect.Right - HScrollValue() < RowHeaderWidth()) continue; Rectangle cellRect = rowRect; cellRect.X = col.CalculatedRect.X - HScrollValue(); cellRect.Width = col.CalculatedRect.Width; dc.SetClip(cellRect); if (col.Index == GetTreeColumn(node)) { int lineindet = 10; // add left margin cellRect.X += Columns.Options.LeftMargin; cellRect.Width -= Columns.Options.LeftMargin; // add indent size int indentSize = GetIndentSize(node) + 5; cellRect.X += indentSize; cellRect.Width -= indentSize; // save rectangle for line drawing below Rectangle lineCellRect = cellRect; cellRect.X += lineindet; cellRect.Width -= lineindet; Rectangle glyphRect = GetPlusMinusRectangle(node, col, visibleRowIndex); Rectangle plusminusRect = glyphRect; if (!ViewOptions.ShowLine && (!ViewOptions.ShowPlusMinus || (!ViewOptions.PadForPlusMinus && plusminusRect == Rectangle.Empty))) { cellRect.X -= (lineindet + 5); cellRect.Width += (lineindet + 5); } Point mousePoint = PointToClient(Cursor.Position); Node hoverNode = CalcHitNode(mousePoint); Image icon = hoverNode != null && hoverNode == node ? GetHoverNodeBitmap(node) : GetNodeBitmap(node); PaintCellBackground(dc, cellRect, node, col); if (ViewOptions.ShowLine) PaintLines(dc, lineCellRect, node); if (SelectedImage != null && (NodesSelection.Contains(node) || FocusedNode == node)) { // center the image vertically glyphRect.Y = cellRect.Y + (cellRect.Height / 2) - (SelectedImage.Height / 2); glyphRect.X = cellRect.X; glyphRect.Width = SelectedImage.Width; glyphRect.Height = SelectedImage.Height; PaintImage(dc, glyphRect, node, SelectedImage); cellRect.X += (glyphRect.Width + 2); cellRect.Width -= (glyphRect.Width + 2); } if (icon != null) { // center the image vertically glyphRect.Y = cellRect.Y + (cellRect.Height / 2) - (icon.Height / 2); glyphRect.X = cellRect.X; glyphRect.Width = icon.Width; glyphRect.Height = icon.Height; PaintImage(dc, glyphRect, node, icon); cellRect.X += (glyphRect.Width + 2); cellRect.Width -= (glyphRect.Width + 2); } PaintCellText(dc, cellRect, node, col); if (plusminusRect != Rectangle.Empty && ViewOptions.ShowPlusMinus) PaintCellPlusMinus(dc, plusminusRect, node, col); } else { PaintCellBackground(dc, cellRect, node, col); PaintCellText(dc, cellRect, node, col); } dc.ResetClip(); } } protected virtual void PaintLines(Graphics dc, Rectangle cellRect, Node node) { Pen pen = new Pen(Color.Gray); pen.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot; int halfPoint = cellRect.Top + (cellRect.Height / 2); // line should start from center at first root node if (node.Parent == null && node.PrevSibling == null) { cellRect.Y += (cellRect.Height / 2); cellRect.Height -= (cellRect.Height / 2); } if (node.NextSibling != null || node.HasChildren) // draw full height line dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, cellRect.Bottom); else dc.DrawLine(pen, cellRect.X, cellRect.Top, cellRect.X, halfPoint); dc.DrawLine(pen, cellRect.X, halfPoint, cellRect.X + 10, halfPoint); // now draw the lines for the parents sibling Node parent = node.Parent; while (parent != null) { Pen linePen = null; if (parent.TreeLineColor != Color.Transparent || parent.TreeLineWidth > 0.0f) linePen = new Pen(parent.TreeLineColor, parent.TreeLineWidth); cellRect.X -= ViewOptions.Indent; dc.DrawLine(linePen != null ? linePen : pen, cellRect.X, cellRect.Top, cellRect.X, cellRect.Bottom); parent = parent.Parent; if (linePen != null) linePen.Dispose(); } pen.Dispose(); } protected virtual int GetIndentSize(Node node) { int indent = 0; Node parent = node.Parent; while (parent != null) { indent += ViewOptions.Indent; parent = parent.Parent; } return indent; } protected virtual Rectangle GetPlusMinusRectangle(Node node, TreeListColumn firstColumn, int visibleRowIndex) { if (node.HasChildren == false) return Rectangle.Empty; int hScrollOffset = HScrollValue(); if (firstColumn.CalculatedRect.Right - hScrollOffset < RowHeaderWidth()) return Rectangle.Empty; //System.Diagnostics.Debug.Assert(firstColumn.VisibleIndex == 0); Rectangle glyphRect = firstColumn.CalculatedRect; glyphRect.X -= hScrollOffset; glyphRect.X += GetIndentSize(node); glyphRect.X += Columns.Options.LeftMargin; glyphRect.Width = 10; glyphRect.Y = VisibleRowToYPoint(visibleRowIndex); glyphRect.Height = RowOptions.ItemHeight; return glyphRect; } protected virtual Image GetNodeBitmap(Node node) { if (node != null) return node.Image; return null; } protected virtual Image GetHoverNodeBitmap(Node node) { if (node != null) return node.HoverImage; return null; } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); int hScrollOffset = HScrollValue(); int remainder = 0; int visiblerows = MaxVisibleRows(out remainder); if (remainder > 0) visiblerows++; bool drawColumnHeaders = true; // draw columns if (drawColumnHeaders) { Rectangle headerRect = e.ClipRectangle; Columns.Draw(e.Graphics, headerRect, hScrollOffset); } int visibleRowIndex = 0; TreeListColumn[] visibleColumns = this.Columns.VisibleColumns; int columnsWidth = Columns.ColumnsWidth; foreach (Node node in NodeCollection.ForwardNodeIterator(m_firstVisibleNode, true)) { Rectangle rowRect = CalcRowRectangle(visibleRowIndex); if (rowRect == Rectangle.Empty || rowRect.Bottom <= e.ClipRectangle.Top || rowRect.Top >= e.ClipRectangle.Bottom) { if (visibleRowIndex > visiblerows) break; visibleRowIndex++; continue; } rowRect.X = RowHeaderWidth() - hScrollOffset; rowRect.Width = columnsWidth; // draw the current node PaintNode(e.Graphics, rowRect, node, visibleColumns, visibleRowIndex); // drow row header for current node Rectangle headerRect = rowRect; headerRect.X = 0; headerRect.Width = RowHeaderWidth(); int absoluteRowIndex = visibleRowIndex + VScrollValue(); headerRect.Width = RowHeaderWidth(); m_rowPainter.DrawHeader(e.Graphics, headerRect, absoluteRowIndex == m_hotrow); visibleRowIndex++; } visibleRowIndex = 0; foreach (Node node in NodeCollection.ForwardNodeIterator(m_firstVisibleNode, true)) { Rectangle rowRect = CalcRowRectangle(visibleRowIndex); // draw horizontal grid line for current node if (ViewOptions.ShowGridLines) { Rectangle r = rowRect; r.X = RowHeaderWidth(); r.Width = columnsWidth - hScrollOffset; m_rowPainter.DrawHorizontalGridLine(e.Graphics, r, GridLineColour); } visibleRowIndex++; } // draw vertical grid lines if (ViewOptions.ShowGridLines) { // visible row count int remainRows = Nodes.VisibleNodeCount - m_vScroll.Value; if (visiblerows > remainRows) visiblerows = remainRows; Rectangle fullRect = ClientRectangle; if (drawColumnHeaders) fullRect.Y += Columns.Options.HeaderHeight; fullRect.Height = visiblerows * RowOptions.ItemHeight; Columns.Painter.DrawVerticalGridLines(Columns, e.Graphics, fullRect, hScrollOffset); } } protected override bool IsInputKey(Keys keyData) { if ((int)(keyData & Keys.Shift) > 0) return true; switch (keyData) { case Keys.Left: case Keys.Right: case Keys.Down: case Keys.Up: case Keys.PageUp: case Keys.PageDown: case Keys.Home: case Keys.End: return true; } return false; } protected override void OnKeyDown(KeyEventArgs e) { Node newnode = null; if (e.KeyCode == Keys.PageUp) { int remainder = 0; int diff = MaxVisibleRows(out remainder)-1; newnode = NodeCollection.GetNextNode(FocusedNode, -diff); if (newnode == null) newnode = Nodes.FirstVisibleNode(); } if (e.KeyCode == Keys.PageDown) { int remainder = 0; int diff = MaxVisibleRows(out remainder)-1; newnode = NodeCollection.GetNextNode(FocusedNode, diff); if (newnode == null) newnode = Nodes.LastVisibleNode(true); } if (e.KeyCode == Keys.Down) { newnode = NodeCollection.GetNextNode(FocusedNode, 1); } if (e.KeyCode == Keys.Up) { newnode = NodeCollection.GetNextNode(FocusedNode, -1); } if (e.KeyCode == Keys.Home) { newnode = Nodes.FirstNode; } if (e.KeyCode == Keys.End) { newnode = Nodes.LastVisibleNode(true); } if (e.KeyCode == Keys.Left) { if (FocusedNode != null) { if (FocusedNode.Expanded) { FocusedNode.Collapse(); EnsureVisible(FocusedNode); return; } if (FocusedNode.Parent != null) { FocusedNode = FocusedNode.Parent; EnsureVisible(FocusedNode); } } } if (e.KeyCode == Keys.Right) { if (FocusedNode != null) { if (FocusedNode.Expanded == false && FocusedNode.HasChildren) { FocusedNode.Expand(); EnsureVisible(FocusedNode); return; } if (FocusedNode.Expanded == true && FocusedNode.HasChildren) { FocusedNode = FocusedNode.Nodes.FirstNode; EnsureVisible(FocusedNode); } } } if (newnode != null) { if (MultiSelect) { // tree behavior is // keys none, the selected node is added as the focused and selected node // keys control, only focused node is moved, the selected nodes collection is not modified // keys shift, selection from first selected node to current node is done if (Control.ModifierKeys == Keys.Control) FocusedNode = newnode; else MultiSelectAdd(newnode, Control.ModifierKeys); } else FocusedNode = newnode; EnsureVisible(FocusedNode); } base.OnKeyDown(e); } internal void internalUpdateStyles() { base.UpdateStyles(); } #region ISupportInitialize Members public void BeginInit() { Columns.BeginInit(); } public void EndInit() { Columns.EndInit(); } #endregion internal new bool DesignMode { get { return base.DesignMode; } } } public class TreeListViewNodes : NodeCollection { TreeListView m_tree; bool m_isUpdating = false; public void BeginUpdate() { m_isUpdating = true; } public void EndUpdate() { m_isUpdating = false; } public TreeListViewNodes(TreeListView owner) : base(null) { m_tree = owner; OwnerView = owner; } protected override void UpdateNodeCount(int oldvalue, int newvalue) { base.UpdateNodeCount(oldvalue, newvalue); if (!m_isUpdating) m_tree.RecalcLayout(); } public override void Clear() { base.Clear(); m_tree.RecalcLayout(); } public override void NodetifyBeforeExpand(Node nodeToExpand, bool expanding) { if (!m_tree.DesignMode) m_tree.OnNotifyBeforeExpand(nodeToExpand, expanding); } public override void NodetifyAfterExpand(Node nodeToExpand, bool expanded) { m_tree.OnNotifyAfterExpand(nodeToExpand, expanded); } protected override int GetFieldIndex(string fieldname) { TreeListColumn col = m_tree.Columns[fieldname]; if (col != null) return col.Index; return -1; } } }
using System; using System.Diagnostics; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Umbraco.Cms.Core; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Hosting; using Umbraco.Cms.Core.Net; using Umbraco.Cms.Core.Routing; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Web; using Umbraco.Extensions; namespace Umbraco.Cms.Web.BackOffice.Security { /// <summary> /// Used to configure <see cref="CookieAuthenticationOptions"/> for the back office authentication type /// </summary> public class ConfigureBackOfficeCookieOptions : IConfigureNamedOptions<CookieAuthenticationOptions> { private readonly IServiceProvider _serviceProvider; private readonly IUmbracoContextAccessor _umbracoContextAccessor; private readonly SecuritySettings _securitySettings; private readonly GlobalSettings _globalSettings; private readonly IHostingEnvironment _hostingEnvironment; private readonly IRuntimeState _runtimeState; private readonly IDataProtectionProvider _dataProtection; private readonly IUserService _userService; private readonly IIpResolver _ipResolver; private readonly ISystemClock _systemClock; private readonly UmbracoRequestPaths _umbracoRequestPaths; private readonly IBasicAuthService _basicAuthService; /// <summary> /// Initializes a new instance of the <see cref="ConfigureBackOfficeCookieOptions"/> class. /// </summary> /// <param name="serviceProvider">The <see cref="IServiceProvider"/></param> /// <param name="umbracoContextAccessor">The <see cref="IUmbracoContextAccessor"/></param> /// <param name="securitySettings">The <see cref="SecuritySettings"/> options</param> /// <param name="globalSettings">The <see cref="GlobalSettings"/> options</param> /// <param name="hostingEnvironment">The <see cref="IHostingEnvironment"/></param> /// <param name="runtimeState">The <see cref="IRuntimeState"/></param> /// <param name="dataProtection">The <see cref="IDataProtectionProvider"/></param> /// <param name="userService">The <see cref="IUserService"/></param> /// <param name="ipResolver">The <see cref="IIpResolver"/></param> /// <param name="systemClock">The <see cref="ISystemClock"/></param> public ConfigureBackOfficeCookieOptions( IServiceProvider serviceProvider, IUmbracoContextAccessor umbracoContextAccessor, IOptions<SecuritySettings> securitySettings, IOptions<GlobalSettings> globalSettings, IHostingEnvironment hostingEnvironment, IRuntimeState runtimeState, IDataProtectionProvider dataProtection, IUserService userService, IIpResolver ipResolver, ISystemClock systemClock, UmbracoRequestPaths umbracoRequestPaths, IBasicAuthService basicAuthService) { _serviceProvider = serviceProvider; _umbracoContextAccessor = umbracoContextAccessor; _securitySettings = securitySettings.Value; _globalSettings = globalSettings.Value; _hostingEnvironment = hostingEnvironment; _runtimeState = runtimeState; _dataProtection = dataProtection; _userService = userService; _ipResolver = ipResolver; _systemClock = systemClock; _umbracoRequestPaths = umbracoRequestPaths; _basicAuthService = basicAuthService; } /// <inheritdoc /> public void Configure(string name, CookieAuthenticationOptions options) { if (name != Constants.Security.BackOfficeAuthenticationType) { return; } Configure(options); } /// <inheritdoc /> public void Configure(CookieAuthenticationOptions options) { options.SlidingExpiration = true; options.ExpireTimeSpan = _globalSettings.TimeOut; options.Cookie.Domain = _securitySettings.AuthCookieDomain; options.Cookie.Name = _securitySettings.AuthCookieName; options.Cookie.HttpOnly = true; options.Cookie.SecurePolicy = _globalSettings.UseHttps ? CookieSecurePolicy.Always : CookieSecurePolicy.SameAsRequest; options.Cookie.Path = "/"; // For any redirections that may occur for the back office, they all go to the same path var backOfficePath = _globalSettings.GetBackOfficePath(_hostingEnvironment); options.AccessDeniedPath = backOfficePath; options.LoginPath = backOfficePath; options.LogoutPath = backOfficePath; options.DataProtectionProvider = _dataProtection; // NOTE: This is borrowed directly from aspnetcore source // Note: the purpose for the data protector must remain fixed for interop to work. IDataProtector dataProtector = options.DataProtectionProvider.CreateProtector("Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware", Constants.Security.BackOfficeAuthenticationType, "v2"); var ticketDataFormat = new TicketDataFormat(dataProtector); options.TicketDataFormat = new BackOfficeSecureDataFormat(_globalSettings.TimeOut, ticketDataFormat); // Custom cookie manager so we can filter requests options.CookieManager = new BackOfficeCookieManager( _umbracoContextAccessor, _runtimeState, _umbracoRequestPaths, _basicAuthService ); options.Events = new CookieAuthenticationEvents { // IMPORTANT! If you set any of OnRedirectToLogin, OnRedirectToAccessDenied, OnRedirectToLogout, OnRedirectToReturnUrl // you need to be aware that this will bypass the default behavior of returning the correct status codes for ajax requests and // not redirecting for non-ajax requests. This is because the default behavior is baked into this class here: // https://github.com/dotnet/aspnetcore/blob/master/src/Security/Authentication/Cookies/src/CookieAuthenticationEvents.cs#L58 // It would be possible to re-use the default behavior if any of these need to be set but that must be taken into account else // our back office requests will not function correctly. For now we don't need to set/configure any of these callbacks because // the defaults work fine with our setup. OnValidatePrincipal = async ctx => { // We need to resolve the BackOfficeSecurityStampValidator per request as a requirement (even in aspnetcore they do this) BackOfficeSecurityStampValidator securityStampValidator = ctx.HttpContext.RequestServices.GetRequiredService<BackOfficeSecurityStampValidator>(); // Same goes for the signinmanager IBackOfficeSignInManager signInManager = ctx.HttpContext.RequestServices.GetRequiredService<IBackOfficeSignInManager>(); ClaimsIdentity backOfficeIdentity = ctx.Principal.GetUmbracoIdentity(); if (backOfficeIdentity == null) { ctx.RejectPrincipal(); await signInManager.SignOutAsync(); } // ensure the thread culture is set backOfficeIdentity.EnsureCulture(); await EnsureValidSessionId(ctx); await securityStampValidator.ValidateAsync(ctx); EnsureTicketRenewalIfKeepUserLoggedIn(ctx); // add or update a claim to track when the cookie expires, we use this to track time remaining backOfficeIdentity.AddOrUpdateClaim(new Claim( Constants.Security.TicketExpiresClaimType, ctx.Properties.ExpiresUtc.Value.ToString("o"), ClaimValueTypes.DateTime, Constants.Security.BackOfficeAuthenticationType, Constants.Security.BackOfficeAuthenticationType, backOfficeIdentity)); }, OnSigningIn = ctx => { // occurs when sign in is successful but before the ticket is written to the outbound cookie ClaimsIdentity backOfficeIdentity = ctx.Principal.GetUmbracoIdentity(); if (backOfficeIdentity != null) { // generate a session id and assign it // create a session token - if we are configured and not in an upgrade state then use the db, otherwise just generate one Guid session = _runtimeState.Level == RuntimeLevel.Run ? _userService.CreateLoginSession(backOfficeIdentity.GetId(), _ipResolver.GetCurrentRequestIpAddress()) : Guid.NewGuid(); // add our session claim backOfficeIdentity.AddClaim(new Claim(Constants.Security.SessionIdClaimType, session.ToString(), ClaimValueTypes.String, Constants.Security.BackOfficeAuthenticationType, Constants.Security.BackOfficeAuthenticationType, backOfficeIdentity)); // since it is a cookie-based authentication add that claim backOfficeIdentity.AddClaim(new Claim(ClaimTypes.CookiePath, "/", ClaimValueTypes.String, Constants.Security.BackOfficeAuthenticationType, Constants.Security.BackOfficeAuthenticationType, backOfficeIdentity)); } return Task.CompletedTask; }, OnSignedIn = ctx => { // occurs when sign in is successful and after the ticket is written to the outbound cookie // When we are signed in with the cookie, assign the principal to the current HttpContext ctx.HttpContext.SetPrincipalForRequest(ctx.Principal); return Task.CompletedTask; }, OnSigningOut = ctx => { // Clear the user's session on sign out if (ctx.HttpContext?.User?.Identity != null) { var claimsIdentity = ctx.HttpContext.User.Identity as ClaimsIdentity; var sessionId = claimsIdentity.FindFirstValue(Constants.Security.SessionIdClaimType); if (sessionId.IsNullOrWhiteSpace() == false && Guid.TryParse(sessionId, out Guid guidSession)) { _userService.ClearLoginSession(guidSession); } } // Remove all of our cookies var cookies = new[] { BackOfficeSessionIdValidator.CookieName, _securitySettings.AuthCookieName, Constants.Web.PreviewCookieName, Constants.Security.BackOfficeExternalCookieName, Constants.Web.AngularCookieName, Constants.Web.CsrfValidationCookieName, }; foreach (var cookie in cookies) { ctx.Options.CookieManager.DeleteCookie(ctx.HttpContext, cookie, new CookieOptions { Path = "/" }); } return Task.CompletedTask; } }; } /// <summary> /// Ensures that the user has a valid session id /// </summary> /// <remarks> /// So that we are not overloading the database this throttles it's check to every minute /// </remarks> private async Task EnsureValidSessionId(CookieValidatePrincipalContext context) { if (_runtimeState.Level != RuntimeLevel.Run) { return; } using IServiceScope scope = _serviceProvider.CreateScope(); BackOfficeSessionIdValidator validator = scope.ServiceProvider.GetRequiredService<BackOfficeSessionIdValidator>(); await validator.ValidateSessionAsync(TimeSpan.FromMinutes(1), context); } /// <summary> /// Ensures the ticket is renewed if the <see cref="SecuritySettings.KeepUserLoggedIn"/> is set to true /// and the current request is for the get user seconds endpoint /// </summary> /// <param name="context">The <see cref="CookieValidatePrincipalContext"/></param> private void EnsureTicketRenewalIfKeepUserLoggedIn(CookieValidatePrincipalContext context) { if (!_securitySettings.KeepUserLoggedIn) { return; } DateTimeOffset currentUtc = _systemClock.UtcNow; DateTimeOffset? issuedUtc = context.Properties.IssuedUtc; DateTimeOffset? expiresUtc = context.Properties.ExpiresUtc; if (expiresUtc.HasValue && issuedUtc.HasValue) { TimeSpan timeElapsed = currentUtc.Subtract(issuedUtc.Value); TimeSpan timeRemaining = expiresUtc.Value.Subtract(currentUtc); // if it's time to renew, then do it if (timeRemaining < timeElapsed) { context.ShouldRenew = true; } } } } }
using System; using System.Diagnostics; using AtomicReaderContext = YAF.Lucene.Net.Index.AtomicReaderContext; using BytesRef = YAF.Lucene.Net.Util.BytesRef; using FieldInvertState = YAF.Lucene.Net.Index.FieldInvertState; using NumericDocValues = YAF.Lucene.Net.Index.NumericDocValues; using SmallSingle = YAF.Lucene.Net.Util.SmallSingle; namespace YAF.Lucene.Net.Search.Similarities { /* * 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. */ /// <summary> /// A subclass of <see cref="Similarity"/> that provides a simplified API for its /// descendants. Subclasses are only required to implement the <see cref="Score(BasicStats, float, float)"/> /// and <see cref="ToString()"/> methods. Implementing /// <see cref="Explain(Explanation, BasicStats, int, float, float)"/> is optional, /// inasmuch as <see cref="SimilarityBase"/> already provides a basic explanation of the score /// and the term frequency. However, implementers of a subclass are encouraged to /// include as much detail about the scoring method as possible. /// <para/> /// Note: multi-word queries such as phrase queries are scored in a different way /// than Lucene's default ranking algorithm: whereas it "fakes" an IDF value for /// the phrase as a whole (since it does not know it), this class instead scores /// phrases as a summation of the individual term scores. /// <para/> /// @lucene.experimental /// </summary> public abstract class SimilarityBase : Similarity { /// <summary> /// For <see cref="Log2(double)"/>. Precomputed for efficiency reasons. </summary> private static readonly double LOG_2 = Math.Log(2); /// <summary> /// True if overlap tokens (tokens with a position of increment of zero) are /// discounted from the document's length. /// </summary> private bool discountOverlaps = true; // LUCENENET Specific: made private, since it can be get/set through property /// <summary> /// Sole constructor. (For invocation by subclass /// constructors, typically implicit.) /// </summary> public SimilarityBase() { } /// <summary> /// Determines whether overlap tokens (Tokens with /// 0 position increment) are ignored when computing /// norm. By default this is <c>true</c>, meaning overlap /// tokens do not count when computing norms. /// <para/> /// @lucene.experimental /// </summary> /// <seealso cref="ComputeNorm(FieldInvertState)"/> public virtual bool DiscountOverlaps { set { discountOverlaps = value; } get { return discountOverlaps; } } public override sealed SimWeight ComputeWeight(float queryBoost, CollectionStatistics collectionStats, params TermStatistics[] termStats) { BasicStats[] stats = new BasicStats[termStats.Length]; for (int i = 0; i < termStats.Length; i++) { stats[i] = NewStats(collectionStats.Field, queryBoost); FillBasicStats(stats[i], collectionStats, termStats[i]); } return stats.Length == 1 ? stats[0] : new MultiSimilarity.MultiStats(stats) as SimWeight; } /// <summary> /// Factory method to return a custom stats object </summary> protected internal virtual BasicStats NewStats(string field, float queryBoost) { return new BasicStats(field, queryBoost); } /// <summary> /// Fills all member fields defined in <see cref="BasicStats"/> in <paramref name="stats"/>. /// Subclasses can override this method to fill additional stats. /// </summary> protected internal virtual void FillBasicStats(BasicStats stats, CollectionStatistics collectionStats, TermStatistics termStats) { // #positions(field) must be >= #positions(term) Debug.Assert(collectionStats.SumTotalTermFreq == -1 || collectionStats.SumTotalTermFreq >= termStats.TotalTermFreq); long numberOfDocuments = collectionStats.MaxDoc; long docFreq = termStats.DocFreq; long totalTermFreq = termStats.TotalTermFreq; // codec does not supply totalTermFreq: substitute docFreq if (totalTermFreq == -1) { totalTermFreq = docFreq; } long numberOfFieldTokens; float avgFieldLength; long sumTotalTermFreq = collectionStats.SumTotalTermFreq; if (sumTotalTermFreq <= 0) { // field does not exist; // We have to provide something if codec doesnt supply these measures, // or if someone omitted frequencies for the field... negative values cause // NaN/Inf for some scorers. numberOfFieldTokens = docFreq; avgFieldLength = 1; } else { numberOfFieldTokens = sumTotalTermFreq; avgFieldLength = (float)numberOfFieldTokens / numberOfDocuments; } // TODO: add sumDocFreq for field (numberOfFieldPostings) stats.NumberOfDocuments = numberOfDocuments; stats.NumberOfFieldTokens = numberOfFieldTokens; stats.AvgFieldLength = avgFieldLength; stats.DocFreq = docFreq; stats.TotalTermFreq = totalTermFreq; } /// <summary> /// Scores the document <c>doc</c>. /// <para>Subclasses must apply their scoring formula in this class.</para> </summary> /// <param name="stats"> the corpus level statistics. </param> /// <param name="freq"> the term frequency. </param> /// <param name="docLen"> the document length. </param> /// <returns> the score. </returns> public abstract float Score(BasicStats stats, float freq, float docLen); /// <summary> /// Subclasses should implement this method to explain the score. <paramref name="expl"/> /// already contains the score, the name of the class and the doc id, as well /// as the term frequency and its explanation; subclasses can add additional /// clauses to explain details of their scoring formulae. /// <para>The default implementation does nothing.</para> /// </summary> /// <param name="expl"> the explanation to extend with details. </param> /// <param name="stats"> the corpus level statistics. </param> /// <param name="doc"> the document id. </param> /// <param name="freq"> the term frequency. </param> /// <param name="docLen"> the document length. </param> protected internal virtual void Explain(Explanation expl, BasicStats stats, int doc, float freq, float docLen) { } /// <summary> /// Explains the score. The implementation here provides a basic explanation /// in the format <em>Score(name-of-similarity, doc=doc-id, /// freq=term-frequency), computed from:</em>, and /// attaches the score (computed via the <see cref="Score(BasicStats, float, float)"/> /// method) and the explanation for the term frequency. Subclasses content with /// this format may add additional details in /// <see cref="Explain(Explanation, BasicStats, int, float, float)"/>. /// </summary> /// <param name="stats"> the corpus level statistics. </param> /// <param name="doc"> the document id. </param> /// <param name="freq"> the term frequency and its explanation. </param> /// <param name="docLen"> the document length. </param> /// <returns> the explanation. </returns> public virtual Explanation Explain(BasicStats stats, int doc, Explanation freq, float docLen) { Explanation result = new Explanation(); result.Value = Score(stats, freq.Value, docLen); result.Description = "score(" + this.GetType().Name + ", doc=" + doc + ", freq=" + freq.Value + "), computed from:"; result.AddDetail(freq); Explain(result, stats, doc, freq.Value, docLen); return result; } public override SimScorer GetSimScorer(SimWeight stats, AtomicReaderContext context) { if (stats is MultiSimilarity.MultiStats) { // a multi term query (e.g. phrase). return the summation, // scoring almost as if it were boolean query SimWeight[] subStats = ((MultiSimilarity.MultiStats)stats).subStats; SimScorer[] subScorers = new SimScorer[subStats.Length]; for (int i = 0; i < subScorers.Length; i++) { BasicStats basicstats = (BasicStats)subStats[i]; subScorers[i] = new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field)); } return new MultiSimilarity.MultiSimScorer(subScorers); } else { BasicStats basicstats = (BasicStats)stats; return new BasicSimScorer(this, basicstats, context.AtomicReader.GetNormValues(basicstats.Field)); } } /// <summary> /// Subclasses must override this method to return the name of the <see cref="Similarity"/> /// and preferably the values of parameters (if any) as well. /// </summary> public override abstract string ToString(); // ------------------------------ Norm handling ------------------------------ /// <summary> /// Norm -> document length map. </summary> private static readonly float[] NORM_TABLE = LoadNormTable(); private static float[] LoadNormTable() // LUCENENET: Avoid static constructors (see https://github.com/apache/lucenenet/pull/224#issuecomment-469284006) { float[] normTable = new float[256]; for (int i = 0; i < 256; i++) { float floatNorm = SmallSingle.SByte315ToSingle((sbyte)i); normTable[i] = 1.0f / (floatNorm * floatNorm); } return normTable; } /// <summary> /// Encodes the document length in the same way as <see cref="TFIDFSimilarity"/>. </summary> public override long ComputeNorm(FieldInvertState state) { float numTerms; if (discountOverlaps) { numTerms = state.Length - state.NumOverlap; } else { numTerms = state.Length; } return EncodeNormValue(state.Boost, numTerms); } /// <summary> /// Decodes a normalization factor (document length) stored in an index. </summary> /// <see cref="EncodeNormValue(float,float)"/> protected internal virtual float DecodeNormValue(byte norm) { return NORM_TABLE[norm & 0xFF]; // & 0xFF maps negative bytes to positive above 127 } /// <summary> /// Encodes the length to a byte via <see cref="SmallSingle"/>. </summary> protected internal virtual byte EncodeNormValue(float boost, float length) { return SmallSingle.SingleToByte315((boost / (float)Math.Sqrt(length))); } // ----------------------------- Static methods ------------------------------ /// <summary> /// Returns the base two logarithm of <c>x</c>. </summary> public static double Log2(double x) { // Put this to a 'util' class if we need more of these. return Math.Log(x) / LOG_2; } // --------------------------------- Classes --------------------------------- /// <summary> /// Delegates the <see cref="Score(int, float)"/> and /// <see cref="Explain(int, Explanation)"/> methods to /// <see cref="SimilarityBase.Score(BasicStats, float, float)"/> and /// <see cref="SimilarityBase.Explain(BasicStats, int, Explanation, float)"/>, /// respectively. /// </summary> private class BasicSimScorer : SimScorer { private readonly SimilarityBase outerInstance; private readonly BasicStats stats; private readonly NumericDocValues norms; internal BasicSimScorer(SimilarityBase outerInstance, BasicStats stats, NumericDocValues norms) { this.outerInstance = outerInstance; this.stats = stats; this.norms = norms; } public override float Score(int doc, float freq) { // We have to supply something in case norms are omitted return outerInstance.Score(stats, freq, norms == null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc))); } public override Explanation Explain(int doc, Explanation freq) { return outerInstance.Explain(stats, doc, freq, norms == null ? 1F : outerInstance.DecodeNormValue((byte)norms.Get(doc))); } public override float ComputeSlopFactor(int distance) { return 1.0f / (distance + 1); } public override float ComputePayloadFactor(int doc, int start, int end, BytesRef payload) { return 1f; } } } }
using System; using System.Configuration; using System.Globalization; using System.Linq; using System.Web; using Assman.ContentFiltering; using Assman.DependencyManagement; using Assman.PreCompilation; namespace Assman.Configuration { /// <summary> /// Represents the configuration section for resource management. /// </summary> public class AssmanConfiguration : ConfigurationSection { private const string SectionName = "assman"; private string _rootFilePath; private static readonly AssmanConfiguration _defaultSection = new AssmanConfiguration(); private static AssmanConfiguration _config; private static IConfigLoader _configLoader = new DefaultConfigLoader(); /// <summary> /// Gets the current configuration. /// </summary> public static AssmanConfiguration Current { get { if(_config == null) { _config = _configLoader.GetSection<AssmanConfiguration>(SectionName) ?? _defaultSection; } return _config; } set { _config = value; } } /// <summary> /// Gets or sets the <see cref="IConfigLoader"/> that is used by the resource consolidation framework /// to load config settings. /// </summary> public static IConfigLoader ConfigLoader { get { return _configLoader; } set { _configLoader = value; } } private IPathResolver _pathResolver; private IPathResolver PathResolver { get { if(_pathResolver == null) { _pathResolver = VirtualPathResolver.GetInstance(RootFilePath); } return _pathResolver; } } /// <summary> /// Gets the full filesytem path to the root of the website. /// </summary> public string RootFilePath { get { if (_rootFilePath == null) { var httpContext = HttpContext.Current; if(httpContext != null) _rootFilePath = httpContext.Server.MapPath("~"); } return _rootFilePath; } set { _rootFilePath = value; } } /// <summary> /// Gets or sets whether consolidation should be enabled. /// </summary> [ConfigurationProperty(PropertyNames.Consolidate, DefaultValue = ResourceModeCondition.Always)] public ResourceModeCondition Consolidate { get { return (ResourceModeCondition) this[PropertyNames.Consolidate]; } set { this[PropertyNames.Consolidate] = value; } } /// <summary> /// Gets or sets whether consolidation should be enabled. /// </summary> [ConfigurationProperty(PropertyNames.GZip, DefaultValue = ResourceModeCondition.Never)] public ResourceModeCondition GZip { get { return (ResourceModeCondition)this[PropertyNames.GZip]; } set { this[PropertyNames.GZip] = value; } } /// <summary> /// Gets or sets whether dependencies provided by the <see cref="IDependencyProvider"/>'s will be included automatically. /// </summary> [ConfigurationProperty(PropertyNames.ManageDependencies, DefaultValue = true)] public bool ManageDependencies { get { return (bool)this[PropertyNames.ManageDependencies]; } set { this[PropertyNames.ManageDependencies] = value; } } /// <summary> /// Gets or sets whether the same file is allowed to be part of multiple groups or not. /// </summary> [ConfigurationProperty(PropertyNames.MutuallyExclusiveGroups, DefaultValue = true)] public bool MutuallyExclusiveGroups { get { return (bool)this[PropertyNames.MutuallyExclusiveGroups]; } set { this[PropertyNames.MutuallyExclusiveGroups] = value; } } /// <summary> /// Gets or sets the version number that will be appended to the end of all resource url's. /// </summary> [ConfigurationProperty(PropertyNames.Version)] public string Version { get { return (string)this[PropertyNames.Version]; } set { this[PropertyNames.Version] = value; } } /// <summary> /// Gets the <see cref="ScriptGroupElement"/> used to configure client script resources. /// </summary> [ConfigurationProperty(PropertyNames.Scripts, IsRequired = false)] public ScriptsConfigurationElement Scripts { get { var element = this[PropertyNames.Scripts] as ScriptsConfigurationElement; if(element == null) { element = new ScriptsConfigurationElement(); this[PropertyNames.Scripts] = element; } return element; } } /// <summary> /// Gets the <see cref="StylesheetGroupElement"/> used to configure css resources. /// </summary> [ConfigurationProperty(PropertyNames.Stylesheets, IsRequired = false)] public StylesheetsConfigurationElement Stylesheets { get { var element = this[PropertyNames.Stylesheets] as StylesheetsConfigurationElement; if (element == null) { element = new StylesheetsConfigurationElement(); this[PropertyNames.Stylesheets] = element; } return element; } } /// <summary> /// Gets the assemblies that the library will search through for embedded resources. /// </summary> [ConfigurationProperty(PropertyNames.Assemblies, IsRequired = false)] [ConfigurationCollection(typeof(AssemblyElementCollection), AddItemName = "add", RemoveItemName = "remove", ClearItemsName = "clear")] public AssemblyElementCollection Assemblies { get { AssemblyElementCollection assemblies = this[PropertyNames.Assemblies] as AssemblyElementCollection; if(assemblies == null) { assemblies = new AssemblyElementCollection(); this[PropertyNames.Assemblies] = assemblies; } return assemblies; } } [ConfigurationProperty(PropertyNames.Plugins, IsRequired = false)] [ConfigurationCollection(typeof(PluginElementCollection), AddItemName = "add", RemoveItemName = "remove", ClearItemsName = "clear")] public PluginElementCollection Plugins { get { var finders = this[PropertyNames.Plugins] as PluginElementCollection; if(finders == null) { finders = new PluginElementCollection(); this[PropertyNames.Plugins] = finders; } return finders; } } private DateTime? _lastModified; public DateTime LastModified(IPathResolver pathResolver) { return _lastModified ?? ConfigurationHelper.LastModified(this, pathResolver); } public void LastModified(DateTime value) { _lastModified = value; } public AssmanContext BuildContext(ResourceMode resourceMode, bool usePreCompilationReportIfPresent = true) { IResourceFinder fileFinder = ResourceFinderFactory.Null; IPreCompiledReportPersister preCompiledPersister = NullPreCompiledPersister.Instance; if(!String.IsNullOrEmpty(RootFilePath)) { fileFinder = ResourceFinderFactory.GetInstance(RootFilePath); if(usePreCompilationReportIfPresent) preCompiledPersister = CompiledFilePersister.ForWebDirectory(RootFilePath); } return BuildContext(resourceMode, fileFinder, preCompiledPersister); } public AssmanContext BuildContext(ResourceMode resourceMode, IResourceFinder fileFinder, IPreCompiledReportPersister preCompiledPersister) { var context = AssmanContext.Create(resourceMode); context.ConfigurationLastModified = LastModified(PathResolver); context.ConsolidateScripts = Consolidate.IsTrue(resourceMode) && Scripts.Consolidate.IsTrue(resourceMode); context.ConsolidateStylesheets = Consolidate.IsTrue(resourceMode) && Stylesheets.Consolidate.IsTrue(resourceMode); context.GZip = GZip.IsTrue(resourceMode); context.ManageDependencies = ManageDependencies; context.MutuallyExclusiveGroups = MutuallyExclusiveGroups; context.AddFinder(fileFinder); context.AddAssemblies(Assemblies.GetAssemblies()); context.ScriptGroups.AddGlobalDependencies(Scripts.GlobalDependencies.Cast<GlobalDependenciesElement>().Select(e => e.Path)); context.ScriptGroups.AddRange(Scripts.Groups.Cast<IResourceGroupTemplate>()); context.StyleGroups.AddGlobalDependencies(Stylesheets.GlobalDependencies.Cast<GlobalDependenciesElement>().Select(e => e.Path)); context.StyleGroups.AddRange(Stylesheets.Groups.Cast<IResourceGroupTemplate>()); context.MapExtensionToContentPipeline(".js", DefaultPipelines.Javascript()); context.MapExtensionToContentPipeline(".css", DefaultPipelines.Css()); context.MapExtensionToDependencyProvider(".js", VisualStudioScriptDependencyProvider.GetInstance()); context.MapExtensionToDependencyProvider(".css", CssDependencyProvider.GetInstance()); PreCompilationReport preCompilationReport; if (preCompiledPersister.TryGetPreConsolidationInfo(out preCompilationReport)) { context.LoadPreCompilationReport(preCompilationReport); } foreach (var plugin in Plugins.GetPlugins()) { plugin.Initialize(context); } return context; } public void SavePreConsolidationReport(PreCompilationReport report) { var preConsolidationPersister = CompiledFilePersister.ForWebDirectory(RootFilePath); preConsolidationPersister.SavePreConsolidationInfo(report); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.Diagnostics; using Test.Utilities; using Xunit; namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests { public class SpecifyIFormatProviderTests : DiagnosticAnalyzerTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new SpecifyIFormatProviderAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new SpecifyIFormatProviderAnalyzer(); } [Fact] public void CA1305_StringReturningStringFormatOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static string SpecifyIFormatProvider1() { return string.Format(""Foo {0}"", ""bar""); } public static string SpecifyIFormatProvider2() { return string.Format(""Foo {0} {1}"", ""bar"", ""foo""); } public static string SpecifyIFormatProvider3() { return string.Format(""Foo {0} {1} {2}"", ""bar"", ""foo"", ""bar""); } public static string SpecifyIFormatProvider4() { return string.Format(""Foo {0} {1} {2} {3}"", ""bar"", ""foo"", ""bar"", """"); } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 16, "string.Format(string, object)", "IFormatProviderStringTest.SpecifyIFormatProvider1()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(15, 16, "string.Format(string, object, object)", "IFormatProviderStringTest.SpecifyIFormatProvider2()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(20, 16, "string.Format(string, object, object, object)", "IFormatProviderStringTest.SpecifyIFormatProvider3()", "string.Format(IFormatProvider, string, params object[])"), GetIFormatProviderAlternateStringRuleCSharpResultAt(25, 16, "string.Format(string, params object[])", "IFormatProviderStringTest.SpecifyIFormatProvider4()", "string.Format(IFormatProvider, string, params object[])")); } [Fact] public void CA1305_StringReturningUserMethodOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void SpecifyIFormatProvider() { IFormatProviderOverloads.LeadingIFormatProviderReturningString(""Bar""); IFormatProviderOverloads.TrailingIFormatProviderReturningString(""Bar""); IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(""Bar""); } } internal static class IFormatProviderOverloads { public static string LeadingIFormatProviderReturningString(string format) { return LeadingIFormatProviderReturningString(CultureInfo.CurrentCulture, format); } public static string LeadingIFormatProviderReturningString(IFormatProvider provider, string format) { return string.Format(provider, format); } public static string TrailingIFormatProviderReturningString(string format) { return TrailingIFormatProviderReturningString(format, CultureInfo.CurrentCulture); } public static string TrailingIFormatProviderReturningString(string format, IFormatProvider provider) { return string.Format(provider, format); } public static string TrailingIFormatProviderReturningString(IFormatProvider provider, string format) { return string.Format(provider, format); } public static string UserDefinedParamsMatchMethodOverload(string format, params object[] objects) { return null; } public static string UserDefinedParamsMatchMethodOverload(IFormatProvider provider, string format, params object[] objs) { return null; } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.LeadingIFormatProviderReturningString(string)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.LeadingIFormatProviderReturningString(IFormatProvider, string)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.TrailingIFormatProviderReturningString(string)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.TrailingIFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(string, params object[])", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(IFormatProvider, string, params object[])")); } [Fact] public void CA1305_StringReturningNoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void SpecifyIFormatProvider6() { IFormatProviderOverloads.IFormatProviderAsDerivedTypeOverload(""Bar""); } public static void SpecifyIFormatProvider7() { IFormatProviderOverloads.UserDefinedParamsMismatchMethodOverload(""Bar""); } } internal static class IFormatProviderOverloads { public static string IFormatProviderAsDerivedTypeOverload(string format) { return null; } public static string IFormatProviderAsDerivedTypeOverload(DerivedClass provider, string format) { return null; } public static string UserDefinedParamsMismatchMethodOverload(string format) { return null; } public static string UserDefinedParamsMismatchMethodOverload(IFormatProvider provider, string format, params object[] objs) { return null; } } public class DerivedClass : IFormatProvider { public object GetFormat(Type formatType) { throw new NotImplementedException(); } }"); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_CSharp() { VerifyCSharp(@" using System; using System.Globalization; public static class IFormatProviderStringTest { public static void TestMethod() { int x = Convert.ToInt32(""1""); long y = Convert.ToInt64(""1""); IFormatProviderOverloads.LeadingIFormatProvider(""1""); IFormatProviderOverloads.TrailingIFormatProvider(""1""); } } internal static class IFormatProviderOverloads { public static void LeadingIFormatProvider(string format) { LeadingIFormatProvider(CultureInfo.CurrentCulture, format); } public static void LeadingIFormatProvider(IFormatProvider provider, string format) { Console.WriteLine(string.Format(provider, format)); } public static void TrailingIFormatProvider(string format) { TrailingIFormatProvider(format, CultureInfo.CurrentCulture); } public static void TrailingIFormatProvider(string format, IFormatProvider provider) { Console.WriteLine(string.Format(provider, format)); } }", GetIFormatProviderAlternateRuleCSharpResultAt(9, 17, "Convert.ToInt32(string)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt32(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(10, 18, "Convert.ToInt64(string)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt64(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.LeadingIFormatProvider(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.LeadingIFormatProvider(IFormatProvider, string)"), GetIFormatProviderAlternateRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.TrailingIFormatProvider(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TrailingIFormatProvider(string, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_TargetMethodNoGenerics_CSharp() { VerifyCSharp(@" using System; public static class IFormatProviderStringTest { public static void TestMethod() { IFormatProviderOverloads.TargetMethodIsNonGeneric(""1""); IFormatProviderOverloads.TargetMethodIsGeneric<int>(""1""); // No Diagnostics because the target method can be generic } } internal static class IFormatProviderOverloads { public static void TargetMethodIsNonGeneric(string format) { } public static void TargetMethodIsNonGeneric<T>(string format, IFormatProvider provider) { } public static void TargetMethodIsGeneric<T>(string format) { } public static void TargetMethodIsGeneric(string format, IFormatProvider provider) { } }", GetIFormatProviderAlternateRuleCSharpResultAt(8, 9, "IFormatProviderOverloads.TargetMethodIsNonGeneric(string)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TargetMethodIsNonGeneric<T>(string, IFormatProvider)")); } [Fact] public void CA1305_StringReturningUICultureIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.InstalledUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture); } } internal static class IFormatProviderOverloads { public static string IFormatProviderReturningString(string format, IFormatProvider provider) { return null; } public static string IFormatProviderReturningString(string format, IFormatProvider provider, IFormatProvider provider2) { return null; } }", GetIFormatProviderAlternateStringRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(10, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(11, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderAlternateStringRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(12, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(string, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningUICultureIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningNonStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.InstalledUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture); IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture); } } internal static class IFormatProviderOverloads { public static void IFormatProviderReturningNonString(string format, IFormatProvider provider) { } public static void IFormatProviderReturningNonString(string format, IFormatProvider provider, IFormatProvider provider2) { } }", GetIFormatProviderAlternateRuleCSharpResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(10, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(11, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderAlternateRuleCSharpResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleCSharpResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(string, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_AcceptNullForIFormatProvider_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class UICultureAsIFormatProviderReturningStringTest { public static void TestMethod() { IFormatProviderOverloads.IFormatProviderReturningString(""1"", null); } } internal static class IFormatProviderOverloads { public static string IFormatProviderReturningString(string format, IFormatProvider provider) { return null; } }"); } [Fact] public void CA1305_DoesNotRecommendObsoleteOverload_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class TestClass { public static void TestMethod() { IFormatProviderOverloads.TrailingObsoleteIFormatProvider(""1""); } } internal static class IFormatProviderOverloads { public static string TrailingObsoleteIFormatProvider(string format) { return null; } [Obsolete] public static string TrailingObsoleteIFormatProvider(string format, IFormatProvider provider) { return null; } }"); } [Fact] public void CA1305_RuleException_NoDiagnostics_CSharp() { VerifyCSharp(@" using System; using System.Globalization; using System.Threading; public static class IFormatProviderStringTest { public static void TrailingThreadCurrentUICulture() { var s = new System.Resources.ResourceManager(null); Console.WriteLine(s.GetObject("""", Thread.CurrentThread.CurrentUICulture)); Console.WriteLine(s.GetStream("""", Thread.CurrentThread.CurrentUICulture)); Console.WriteLine(s.GetResourceSet(Thread.CurrentThread.CurrentUICulture, false, false)); var activator = Activator.CreateInstance(null, System.Reflection.BindingFlags.CreateInstance, null, null, Thread.CurrentThread.CurrentUICulture); Console.WriteLine(activator); } }"); } [Fact] public void CA1305_StringReturningStringFormatOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Function SpecifyIFormatProvider1() As String Return String.Format(""Foo {0}"", ""bar"") End Function Public Shared Function SpecifyIFormatProvider2() As String Return String.Format(""Foo {0} {1}"", ""bar"", ""foo"") End Function Public Shared Function SpecifyIFormatProvider3() As String Return String.Format(""Foo {0} {1} {2}"", ""bar"", ""foo"", ""bar"") End Function Public Shared Function SpecifyIFormatProvider4() As String Return String.Format(""Foo {0} {1} {2} {3}"", ""bar"", ""foo"", ""bar"", """") End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(11, 16, "String.Format(String, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider1()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(15, 16, "String.Format(String, Object, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider2()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(19, 16, "String.Format(String, Object, Object, Object)", "IFormatProviderStringTest.SpecifyIFormatProvider3()", "String.Format(IFormatProvider, String, ParamArray Object())"), GetIFormatProviderAlternateStringRuleBasicResultAt(23, 16, "String.Format(String, ParamArray Object())", "IFormatProviderStringTest.SpecifyIFormatProvider4()", "String.Format(IFormatProvider, String, ParamArray Object())")); } [Fact] public void CA1305_StringReturningUserMethodOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub SpecifyIFormatProvider() IFormatProviderOverloads.LeadingIFormatProviderReturningString(""Bar"") IFormatProviderOverloads.TrailingIFormatProviderReturningString(""Bar"") IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(""Bar"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function LeadingIFormatProviderReturningString(format As String) As String Return LeadingIFormatProviderReturningString(CultureInfo.CurrentCulture, format) End Function Public Shared Function LeadingIFormatProviderReturningString(provider As IFormatProvider, format As String) As String Return String.Format(provider, format) End Function Public Shared Function TrailingIFormatProviderReturningString(format As String) As String Return TrailingIFormatProviderReturningString(format, CultureInfo.CurrentCulture) End Function Public Shared Function TrailingIFormatProviderReturningString(format As String, provider As IFormatProvider) As String Return String.Format(provider, format) End Function Public Shared Function TrailingIFormatProviderReturningString(provider As IFormatProvider, format As String) As String Return String.Format(provider, format) End Function Public Shared Function UserDefinedParamsMatchMethodOverload(format As String, ParamArray objects As Object()) As String Return Nothing End Function Public Shared Function UserDefinedParamsMatchMethodOverload(provider As IFormatProvider, format As String, ParamArray objs As Object()) As String Return Nothing End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(10, 9, "IFormatProviderOverloads.LeadingIFormatProviderReturningString(String)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.LeadingIFormatProviderReturningString(IFormatProvider, String)"), GetIFormatProviderAlternateStringRuleBasicResultAt(11, 9, "IFormatProviderOverloads.TrailingIFormatProviderReturningString(String)", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.TrailingIFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(12, 9, "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(String, ParamArray Object())", "IFormatProviderStringTest.SpecifyIFormatProvider()", "IFormatProviderOverloads.UserDefinedParamsMatchMethodOverload(IFormatProvider, String, ParamArray Object())")); } [Fact] public void CA1305_StringReturningNoDiagnostics_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub SpecifyIFormatProvider6() IFormatProviderOverloads.IFormatProviderAsDerivedTypeOverload(""Bar"") End Sub Public Shared Sub SpecifyIFormatProvider7() IFormatProviderOverloads.UserDefinedParamsMismatchMethodOverload(""Bar"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function IFormatProviderAsDerivedTypeOverload(format As String) As String Return Nothing End Function Public Shared Function IFormatProviderAsDerivedTypeOverload(provider As DerivedClass, format As String) As String Return Nothing End Function Public Shared Function UserDefinedParamsMismatchMethodOverload(format As String) As String Return Nothing End Function Public Shared Function UserDefinedParamsMismatchMethodOverload(provider As IFormatProvider, format As String, ParamArray objs As Object()) As String Return Nothing End Function End Class Public Class DerivedClass Implements IFormatProvider Public Function GetFormat(formatType As Type) As Object Implements IFormatProvider.GetFormat Throw New NotImplementedException() End Function End Class"); } [Fact] public void CA1305_NonStringReturningStringFormatOverloads_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub TestMethod() Dim x As Integer = Convert.ToInt32(""1"") Dim y As Long = Convert.ToInt64(""1"") IFormatProviderOverloads.LeadingIFormatProvider(""1"") IFormatProviderOverloads.TrailingIFormatProvider(""1"") End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub LeadingIFormatProvider(format As String) LeadingIFormatProvider(CultureInfo.CurrentCulture, format) End Sub Public Shared Sub LeadingIFormatProvider(provider As IFormatProvider, format As String) Console.WriteLine(String.Format(provider, format)) End Sub Public Shared Sub TrailingIFormatProvider(format As String) TrailingIFormatProvider(format, CultureInfo.CurrentCulture) End Sub Public Shared Sub TrailingIFormatProvider(format As String, provider As IFormatProvider) Console.WriteLine(String.Format(provider, format)) End Sub End Class", GetIFormatProviderAlternateRuleBasicResultAt(10, 28, "Convert.ToInt32(String)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt32(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(11, 25, "Convert.ToInt64(String)", "IFormatProviderStringTest.TestMethod()", "Convert.ToInt64(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(12, 9, "IFormatProviderOverloads.LeadingIFormatProvider(String)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.LeadingIFormatProvider(IFormatProvider, String)"), GetIFormatProviderAlternateRuleBasicResultAt(13, 9, "IFormatProviderOverloads.TrailingIFormatProvider(String)", "IFormatProviderStringTest.TestMethod()", "IFormatProviderOverloads.TrailingIFormatProvider(String, IFormatProvider)")); } [Fact] public void CA1305_StringReturningUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class UICultureAsIFormatProviderReturningStringTest Private Sub New() End Sub Public Shared Sub TestMethod() IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", CultureInfo.InstalledUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Function IFormatProviderReturningString(format As String, provider As IFormatProvider) As String Return Nothing End Function Public Shared Function IFormatProviderReturningString(format As String, provider As IFormatProvider, provider2 As IFormatProvider) As String Return Nothing End Function End Class", GetIFormatProviderAlternateStringRuleBasicResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(10, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(11, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderAlternateStringRuleBasicResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureStringRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningString(String, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class UICultureAsIFormatProviderReturningNonStringTest Private Sub New() End Sub Public Shared Sub TestMethod() IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", CultureInfo.InstalledUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture) IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", Thread.CurrentThread.CurrentUICulture, CultureInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider) End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider, provider2 As IFormatProvider) End Sub End Class", GetIFormatProviderAlternateRuleBasicResultAt(10, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(10, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(11, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(11, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderAlternateRuleBasicResultAt(12, 9, "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)", "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "Thread.CurrentUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)"), GetIFormatProviderUICultureRuleBasicResultAt(13, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "CultureInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider, IFormatProvider)")); } [Fact] public void CA1305_NonStringReturningComputerInfoInstalledUICultureIFormatProvider_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Imports Microsoft.VisualBasic.Devices Public NotInheritable Class UICultureAsIFormatProviderReturningNonStringTest Private Sub New() End Sub Public Shared Sub TestMethod() Dim computerInfo As New Microsoft.VisualBasic.Devices.ComputerInfo() IFormatProviderOverloads.IFormatProviderReturningNonString(""1"", computerInfo.InstalledUICulture) End Sub End Class Friend NotInheritable Class IFormatProviderOverloads Private Sub New() End Sub Public Shared Sub IFormatProviderReturningNonString(format As String, provider As IFormatProvider) End Sub End Class", GetIFormatProviderUICultureRuleBasicResultAt(12, 9, "UICultureAsIFormatProviderReturningNonStringTest.TestMethod()", "ComputerInfo.InstalledUICulture", "IFormatProviderOverloads.IFormatProviderReturningNonString(String, IFormatProvider)")); } [Fact] public void CA1305_RuleException_NoDiagnostics_VisualBasic() { VerifyBasic(@" Imports System Imports System.Globalization Imports System.Threading Public NotInheritable Class IFormatProviderStringTest Private Sub New() End Sub Public Shared Sub TrailingThreadCurrentUICulture() Dim s = New System.Resources.ResourceManager(Nothing) Console.WriteLine(s.GetObject("""", Thread.CurrentThread.CurrentUICulture)) Console.WriteLine(s.GetStream("""", Thread.CurrentThread.CurrentUICulture)) Console.WriteLine(s.GetResourceSet(Thread.CurrentThread.CurrentUICulture, False, False)) Dim activator__1 = Activator.CreateInstance(Nothing, System.Reflection.BindingFlags.CreateInstance, Nothing, Nothing, Thread.CurrentThread.CurrentUICulture) Console.WriteLine(activator__1) End Sub End Class"); } private DiagnosticResult GetIFormatProviderAlternateStringRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureStringRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureRuleCSharpResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetCSharpResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateStringRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderAlternateRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.IFormatProviderAlternateRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureStringRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureStringRule, arg1, arg2, arg3); } private DiagnosticResult GetIFormatProviderUICultureRuleBasicResultAt(int line, int column, string arg1, string arg2, string arg3) { return GetBasicResultAt(line, column, SpecifyIFormatProviderAnalyzer.UICultureRule, arg1, arg2, arg3); } } }
#if !BESTHTTP_DISABLE_ALTERNATE_SSL && (!UNITY_WEBGL || UNITY_EDITOR) using System; using System.Diagnostics; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Math.Raw { internal abstract class Nat160 { private const ulong M = 0xFFFFFFFFUL; public static uint Add(uint[] x, uint[] y, uint[] z) { ulong c = 0; c += (ulong)x[0] + y[0]; z[0] = (uint)c; c >>= 32; c += (ulong)x[1] + y[1]; z[1] = (uint)c; c >>= 32; c += (ulong)x[2] + y[2]; z[2] = (uint)c; c >>= 32; c += (ulong)x[3] + y[3]; z[3] = (uint)c; c >>= 32; c += (ulong)x[4] + y[4]; z[4] = (uint)c; c >>= 32; return (uint)c; } public static uint AddBothTo(uint[] x, uint[] y, uint[] z) { ulong c = 0; c += (ulong)x[0] + y[0] + z[0]; z[0] = (uint)c; c >>= 32; c += (ulong)x[1] + y[1] + z[1]; z[1] = (uint)c; c >>= 32; c += (ulong)x[2] + y[2] + z[2]; z[2] = (uint)c; c >>= 32; c += (ulong)x[3] + y[3] + z[3]; z[3] = (uint)c; c >>= 32; c += (ulong)x[4] + y[4] + z[4]; z[4] = (uint)c; c >>= 32; return (uint)c; } public static uint AddTo(uint[] x, uint[] z) { ulong c = 0; c += (ulong)x[0] + z[0]; z[0] = (uint)c; c >>= 32; c += (ulong)x[1] + z[1]; z[1] = (uint)c; c >>= 32; c += (ulong)x[2] + z[2]; z[2] = (uint)c; c >>= 32; c += (ulong)x[3] + z[3]; z[3] = (uint)c; c >>= 32; c += (ulong)x[4] + z[4]; z[4] = (uint)c; c >>= 32; return (uint)c; } public static uint AddTo(uint[] x, int xOff, uint[] z, int zOff, uint cIn) { ulong c = cIn; c += (ulong)x[xOff + 0] + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += (ulong)x[xOff + 1] + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += (ulong)x[xOff + 2] + z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += (ulong)x[xOff + 3] + z[zOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; c += (ulong)x[xOff + 4] + z[zOff + 4]; z[zOff + 4] = (uint)c; c >>= 32; c += (ulong)x[xOff + 5] + z[zOff + 5]; return (uint)c; } public static uint AddToEachOther(uint[] u, int uOff, uint[] v, int vOff) { ulong c = 0; c += (ulong)u[uOff + 0] + v[vOff + 0]; u[uOff + 0] = (uint)c; v[vOff + 0] = (uint)c; c >>= 32; c += (ulong)u[uOff + 1] + v[vOff + 1]; u[uOff + 1] = (uint)c; v[vOff + 1] = (uint)c; c >>= 32; c += (ulong)u[uOff + 2] + v[vOff + 2]; u[uOff + 2] = (uint)c; v[vOff + 2] = (uint)c; c >>= 32; c += (ulong)u[uOff + 3] + v[vOff + 3]; u[uOff + 3] = (uint)c; v[vOff + 3] = (uint)c; c >>= 32; c += (ulong)u[uOff + 4] + v[vOff + 4]; u[uOff + 4] = (uint)c; v[vOff + 4] = (uint)c; c >>= 32; return (uint)c; } public static void Copy(uint[] x, uint[] z) { z[0] = x[0]; z[1] = x[1]; z[2] = x[2]; z[3] = x[3]; z[4] = x[4]; } public static uint[] Create() { return new uint[5]; } public static uint[] CreateExt() { return new uint[10]; } public static bool Diff(uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) { bool pos = Gte(x, xOff, y, yOff); if (pos) { Sub(x, xOff, y, yOff, z, zOff); } else { Sub(y, yOff, x, xOff, z, zOff); } return pos; } public static bool Eq(uint[] x, uint[] y) { for (int i = 4; i >= 0; --i) { if (x[i] != y[i]) return false; } return true; } public static uint[] FromBigInteger(BigInteger x) { if (x.SignValue < 0 || x.BitLength > 160) throw new ArgumentException(); uint[] z = Create(); int i = 0; while (x.SignValue != 0) { z[i++] = (uint)x.IntValue; x = x.ShiftRight(32); } return z; } public static uint GetBit(uint[] x, int bit) { if (bit == 0) { return x[0] & 1; } int w = bit >> 5; if (w < 0 || w >= 5) { return 0; } int b = bit & 31; return (x[w] >> b) & 1; } public static bool Gte(uint[] x, uint[] y) { for (int i = 4; i >= 0; --i) { uint x_i = x[i], y_i = y[i]; if (x_i < y_i) return false; if (x_i > y_i) return true; } return true; } public static bool Gte(uint[] x, int xOff, uint[] y, int yOff) { for (int i = 4; i >= 0; --i) { uint x_i = x[xOff + i], y_i = y[yOff + i]; if (x_i < y_i) return false; if (x_i > y_i) return true; } return true; } public static bool IsOne(uint[] x) { if (x[0] != 1) { return false; } for (int i = 1; i < 5; ++i) { if (x[i] != 0) { return false; } } return true; } public static bool IsZero(uint[] x) { for (int i = 0; i < 5; ++i) { if (x[i] != 0) { return false; } } return true; } public static void Mul(uint[] x, uint[] y, uint[] zz) { ulong y_0 = y[0]; ulong y_1 = y[1]; ulong y_2 = y[2]; ulong y_3 = y[3]; ulong y_4 = y[4]; { ulong c = 0, x_0 = x[0]; c += x_0 * y_0; zz[0] = (uint)c; c >>= 32; c += x_0 * y_1; zz[1] = (uint)c; c >>= 32; c += x_0 * y_2; zz[2] = (uint)c; c >>= 32; c += x_0 * y_3; zz[3] = (uint)c; c >>= 32; c += x_0 * y_4; zz[4] = (uint)c; c >>= 32; zz[5] = (uint)c; } for (int i = 1; i < 5; ++i) { ulong c = 0, x_i = x[i]; c += x_i * y_0 + zz[i + 0]; zz[i + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[i + 1]; zz[i + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[i + 2]; zz[i + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[i + 3]; zz[i + 3] = (uint)c; c >>= 32; c += x_i * y_4 + zz[i + 4]; zz[i + 4] = (uint)c; c >>= 32; zz[i + 5] = (uint)c; } } public static void Mul(uint[] x, int xOff, uint[] y, int yOff, uint[] zz, int zzOff) { ulong y_0 = y[yOff + 0]; ulong y_1 = y[yOff + 1]; ulong y_2 = y[yOff + 2]; ulong y_3 = y[yOff + 3]; ulong y_4 = y[yOff + 4]; { ulong c = 0, x_0 = x[xOff + 0]; c += x_0 * y_0; zz[zzOff + 0] = (uint)c; c >>= 32; c += x_0 * y_1; zz[zzOff + 1] = (uint)c; c >>= 32; c += x_0 * y_2; zz[zzOff + 2] = (uint)c; c >>= 32; c += x_0 * y_3; zz[zzOff + 3] = (uint)c; c >>= 32; c += x_0 * y_4; zz[zzOff + 4] = (uint)c; c >>= 32; zz[zzOff + 5] = (uint)c; } for (int i = 1; i < 5; ++i) { ++zzOff; ulong c = 0, x_i = x[xOff + i]; c += x_i * y_0 + zz[zzOff + 0]; zz[zzOff + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[zzOff + 1]; zz[zzOff + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[zzOff + 2]; zz[zzOff + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[zzOff + 3]; zz[zzOff + 3] = (uint)c; c >>= 32; c += x_i * y_4 + zz[zzOff + 4]; zz[zzOff + 4] = (uint)c; c >>= 32; zz[zzOff + 5] = (uint)c; } } public static uint MulAddTo(uint[] x, uint[] y, uint[] zz) { ulong y_0 = y[0]; ulong y_1 = y[1]; ulong y_2 = y[2]; ulong y_3 = y[3]; ulong y_4 = y[4]; ulong zc = 0; for (int i = 0; i < 5; ++i) { ulong c = 0, x_i = x[i]; c += x_i * y_0 + zz[i + 0]; zz[i + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[i + 1]; zz[i + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[i + 2]; zz[i + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[i + 3]; zz[i + 3] = (uint)c; c >>= 32; c += x_i * y_4 + zz[i + 4]; zz[i + 4] = (uint)c; c >>= 32; c += zc + zz[i + 5]; zz[i + 5] = (uint)c; zc = c >> 32; } return (uint)zc; } public static uint MulAddTo(uint[] x, int xOff, uint[] y, int yOff, uint[] zz, int zzOff) { ulong y_0 = y[yOff + 0]; ulong y_1 = y[yOff + 1]; ulong y_2 = y[yOff + 2]; ulong y_3 = y[yOff + 3]; ulong y_4 = y[yOff + 4]; ulong zc = 0; for (int i = 0; i < 5; ++i) { ulong c = 0, x_i = x[xOff + i]; c += x_i * y_0 + zz[zzOff + 0]; zz[zzOff + 0] = (uint)c; c >>= 32; c += x_i * y_1 + zz[zzOff + 1]; zz[zzOff + 1] = (uint)c; c >>= 32; c += x_i * y_2 + zz[zzOff + 2]; zz[zzOff + 2] = (uint)c; c >>= 32; c += x_i * y_3 + zz[zzOff + 3]; zz[zzOff + 3] = (uint)c; c >>= 32; c += x_i * y_4 + zz[zzOff + 4]; zz[zzOff + 4] = (uint)c; c >>= 32; c += zc + zz[zzOff + 5]; zz[zzOff + 5] = (uint)c; zc = c >> 32; ++zzOff; } return (uint)zc; } public static ulong Mul33Add(uint w, uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) { Debug.Assert(w >> 31 == 0); ulong c = 0, wVal = w; ulong x0 = x[xOff + 0]; c += wVal * x0 + y[yOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; ulong x1 = x[xOff + 1]; c += wVal * x1 + x0 + y[yOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; ulong x2 = x[xOff + 2]; c += wVal * x2 + x1 + y[yOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; ulong x3 = x[xOff + 3]; c += wVal * x3 + x2 + y[yOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; ulong x4 = x[xOff + 4]; c += wVal * x4 + x3 + y[yOff + 4]; z[zOff + 4] = (uint)c; c >>= 32; c += x4; return c; } public static uint MulWordAddExt(uint x, uint[] yy, int yyOff, uint[] zz, int zzOff) { Debug.Assert(yyOff <= 5); Debug.Assert(zzOff <= 5); ulong c = 0, xVal = x; c += xVal * yy[yyOff + 0] + zz[zzOff + 0]; zz[zzOff + 0] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 1] + zz[zzOff + 1]; zz[zzOff + 1] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 2] + zz[zzOff + 2]; zz[zzOff + 2] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 3] + zz[zzOff + 3]; zz[zzOff + 3] = (uint)c; c >>= 32; c += xVal * yy[yyOff + 4] + zz[zzOff + 4]; zz[zzOff + 4] = (uint)c; c >>= 32; return (uint)c; } public static uint Mul33DWordAdd(uint x, ulong y, uint[] z, int zOff) { Debug.Assert(x >> 31 == 0); Debug.Assert(zOff <= 1); ulong c = 0, xVal = x; ulong y00 = y & M; c += xVal * y00 + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; ulong y01 = y >> 32; c += xVal * y01 + y00 + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += y01 + z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += z[zOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(5, z, zOff, 4); } public static uint Mul33WordAdd(uint x, uint y, uint[] z, int zOff) { Debug.Assert(x >> 31 == 0); Debug.Assert(zOff <= 2); ulong c = 0, yVal = y; c += yVal * x + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += yVal + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(5, z, zOff, 3); } public static uint MulWordDwordAdd(uint x, ulong y, uint[] z, int zOff) { Debug.Assert(zOff <= 2); ulong c = 0, xVal = x; c += xVal * y + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += xVal * (y >> 32) + z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += z[zOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(5, z, zOff, 3); } public static uint MulWordsAdd(uint x, uint y, uint[] z, int zOff) { Debug.Assert(zOff <= 3); ulong c = 0, xVal = x, yVal = y; c += yVal * xVal + z[zOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += z[zOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; return c == 0 ? 0 : Nat.IncAt(5, z, zOff, 2); } public static uint MulWord(uint x, uint[] y, uint[] z, int zOff) { ulong c = 0, xVal = x; int i = 0; do { c += xVal * y[i]; z[zOff + i] = (uint)c; c >>= 32; } while (++i < 5); return (uint)c; } public static void Square(uint[] x, uint[] zz) { ulong x_0 = x[0]; ulong zz_1; uint c = 0, w; { int i = 4, j = 10; do { ulong xVal = x[i--]; ulong p = xVal * xVal; zz[--j] = (c << 31) | (uint)(p >> 33); zz[--j] = (uint)(p >> 1); c = (uint)p; } while (i > 0); { ulong p = x_0 * x_0; zz_1 = (ulong)(c << 31) | (p >> 33); zz[0] = (uint)p; c = (uint)(p >> 32) & 1; } } ulong x_1 = x[1]; ulong zz_2 = zz[2]; { zz_1 += x_1 * x_0; w = (uint)zz_1; zz[1] = (w << 1) | c; c = w >> 31; zz_2 += zz_1 >> 32; } ulong x_2 = x[2]; ulong zz_3 = zz[3]; ulong zz_4 = zz[4]; { zz_2 += x_2 * x_0; w = (uint)zz_2; zz[2] = (w << 1) | c; c = w >> 31; zz_3 += (zz_2 >> 32) + x_2 * x_1; zz_4 += zz_3 >> 32; zz_3 &= M; } ulong x_3 = x[3]; ulong zz_5 = zz[5]; ulong zz_6 = zz[6]; { zz_3 += x_3 * x_0; w = (uint)zz_3; zz[3] = (w << 1) | c; c = w >> 31; zz_4 += (zz_3 >> 32) + x_3 * x_1; zz_5 += (zz_4 >> 32) + x_3 * x_2; zz_4 &= M; zz_6 += zz_5 >> 32; zz_5 &= M; } ulong x_4 = x[4]; ulong zz_7 = zz[7]; ulong zz_8 = zz[8]; { zz_4 += x_4 * x_0; w = (uint)zz_4; zz[4] = (w << 1) | c; c = w >> 31; zz_5 += (zz_4 >> 32) + x_4 * x_1; zz_6 += (zz_5 >> 32) + x_4 * x_2; zz_7 += (zz_6 >> 32) + x_4 * x_3; zz_8 += zz_7 >> 32; } w = (uint)zz_5; zz[5] = (w << 1) | c; c = w >> 31; w = (uint)zz_6; zz[6] = (w << 1) | c; c = w >> 31; w = (uint)zz_7; zz[7] = (w << 1) | c; c = w >> 31; w = (uint)zz_8; zz[8] = (w << 1) | c; c = w >> 31; w = zz[9] + (uint)(zz_8 >> 32); zz[9] = (w << 1) | c; } public static void Square(uint[] x, int xOff, uint[] zz, int zzOff) { ulong x_0 = x[xOff + 0]; ulong zz_1; uint c = 0, w; { int i = 4, j = 10; do { ulong xVal = x[xOff + i--]; ulong p = xVal * xVal; zz[zzOff + --j] = (c << 31) | (uint)(p >> 33); zz[zzOff + --j] = (uint)(p >> 1); c = (uint)p; } while (i > 0); { ulong p = x_0 * x_0; zz_1 = (ulong)(c << 31) | (p >> 33); zz[zzOff + 0] = (uint)p; c = (uint)(p >> 32) & 1; } } ulong x_1 = x[xOff + 1]; ulong zz_2 = zz[zzOff + 2]; { zz_1 += x_1 * x_0; w = (uint)zz_1; zz[zzOff + 1] = (w << 1) | c; c = w >> 31; zz_2 += zz_1 >> 32; } ulong x_2 = x[xOff + 2]; ulong zz_3 = zz[zzOff + 3]; ulong zz_4 = zz[zzOff + 4]; { zz_2 += x_2 * x_0; w = (uint)zz_2; zz[zzOff + 2] = (w << 1) | c; c = w >> 31; zz_3 += (zz_2 >> 32) + x_2 * x_1; zz_4 += zz_3 >> 32; zz_3 &= M; } ulong x_3 = x[xOff + 3]; ulong zz_5 = zz[zzOff + 5]; ulong zz_6 = zz[zzOff + 6]; { zz_3 += x_3 * x_0; w = (uint)zz_3; zz[zzOff + 3] = (w << 1) | c; c = w >> 31; zz_4 += (zz_3 >> 32) + x_3 * x_1; zz_5 += (zz_4 >> 32) + x_3 * x_2; zz_4 &= M; zz_6 += zz_5 >> 32; zz_5 &= M; } ulong x_4 = x[xOff + 4]; ulong zz_7 = zz[zzOff + 7]; ulong zz_8 = zz[zzOff + 8]; { zz_4 += x_4 * x_0; w = (uint)zz_4; zz[zzOff + 4] = (w << 1) | c; c = w >> 31; zz_5 += (zz_4 >> 32) + x_4 * x_1; zz_6 += (zz_5 >> 32) + x_4 * x_2; zz_7 += (zz_6 >> 32) + x_4 * x_3; zz_8 += zz_7 >> 32; } w = (uint)zz_5; zz[zzOff + 5] = (w << 1) | c; c = w >> 31; w = (uint)zz_6; zz[zzOff + 6] = (w << 1) | c; c = w >> 31; w = (uint)zz_7; zz[zzOff + 7] = (w << 1) | c; c = w >> 31; w = (uint)zz_8; zz[zzOff + 8] = (w << 1) | c; c = w >> 31; w = zz[zzOff + 9] + (uint)(zz_8 >> 32); zz[zzOff + 9] = (w << 1) | c; } public static int Sub(uint[] x, uint[] y, uint[] z) { long c = 0; c += (long)x[0] - y[0]; z[0] = (uint)c; c >>= 32; c += (long)x[1] - y[1]; z[1] = (uint)c; c >>= 32; c += (long)x[2] - y[2]; z[2] = (uint)c; c >>= 32; c += (long)x[3] - y[3]; z[3] = (uint)c; c >>= 32; c += (long)x[4] - y[4]; z[4] = (uint)c; c >>= 32; return (int)c; } public static int Sub(uint[] x, int xOff, uint[] y, int yOff, uint[] z, int zOff) { long c = 0; c += (long)x[xOff + 0] - y[yOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += (long)x[xOff + 1] - y[yOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += (long)x[xOff + 2] - y[yOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += (long)x[xOff + 3] - y[yOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; c += (long)x[xOff + 4] - y[yOff + 4]; z[zOff + 4] = (uint)c; c >>= 32; return (int)c; } public static int SubBothFrom(uint[] x, uint[] y, uint[] z) { long c = 0; c += (long)z[0] - x[0] - y[0]; z[0] = (uint)c; c >>= 32; c += (long)z[1] - x[1] - y[1]; z[1] = (uint)c; c >>= 32; c += (long)z[2] - x[2] - y[2]; z[2] = (uint)c; c >>= 32; c += (long)z[3] - x[3] - y[3]; z[3] = (uint)c; c >>= 32; c += (long)z[4] - x[4] - y[4]; z[4] = (uint)c; c >>= 32; return (int)c; } public static int SubFrom(uint[] x, uint[] z) { long c = 0; c += (long)z[0] - x[0]; z[0] = (uint)c; c >>= 32; c += (long)z[1] - x[1]; z[1] = (uint)c; c >>= 32; c += (long)z[2] - x[2]; z[2] = (uint)c; c >>= 32; c += (long)z[3] - x[3]; z[3] = (uint)c; c >>= 32; c += (long)z[4] - x[4]; z[4] = (uint)c; c >>= 32; return (int)c; } public static int SubFrom(uint[] x, int xOff, uint[] z, int zOff) { long c = 0; c += (long)z[zOff + 0] - x[xOff + 0]; z[zOff + 0] = (uint)c; c >>= 32; c += (long)z[zOff + 1] - x[xOff + 1]; z[zOff + 1] = (uint)c; c >>= 32; c += (long)z[zOff + 2] - x[xOff + 2]; z[zOff + 2] = (uint)c; c >>= 32; c += (long)z[zOff + 3] - x[xOff + 3]; z[zOff + 3] = (uint)c; c >>= 32; c += (long)z[zOff + 4] - x[xOff + 4]; z[zOff + 4] = (uint)c; c >>= 32; return (int)c; } public static BigInteger ToBigInteger(uint[] x) { byte[] bs = new byte[20]; for (int i = 0; i < 5; ++i) { uint x_i = x[i]; if (x_i != 0) { Pack.UInt32_To_BE(x_i, bs, (4 - i) << 2); } } return new BigInteger(1, bs); } public static void Zero(uint[] z) { z[0] = 0; z[1] = 0; z[2] = 0; z[3] = 0; z[4] = 0; } } } #endif
// // ImportManager.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Globalization; using Mono.Unix; using Hyena; using Hyena.Jobs; using Hyena.Collections; using Banshee.IO; using Banshee.Base; using Banshee.ServiceStack; namespace Banshee.Collection { public class ImportManager : QueuePipeline<string> { #region Importing Pipeline Element private class ImportElement : QueuePipelineElement<string> { private ImportManager manager; public ImportElement (ImportManager manager) { this.manager = manager; } public override void Enqueue (string item) { base.Enqueue (item); manager.UpdateScannerProgress (); } protected override string ProcessItem (string item) { try { if (manager.Debug) Log.InformationFormat ("ImportElement processing {0}", item); manager.OnImportRequested (item); } catch (Exception e) { Hyena.Log.Exception (e); } return null; } } #endregion public bool Debug { get { return scanner_element.Debug; } set { scanner_element.Debug = value; } } private static NumberFormatInfo number_format = new NumberFormatInfo (); private DirectoryScannerPipelineElement scanner_element; private ImportElement import_element; private readonly object user_job_mutex = new object (); private UserJob user_job; private uint timer_id; public event ImportEventHandler ImportRequested; public ImportManager () { AddElement (scanner_element = new DirectoryScannerPipelineElement ()); AddElement (import_element = new ImportElement (this)); } #region Public API public override void Enqueue (string path) { CreateUserJob (); base.Enqueue (path); } public void Enqueue (string [] paths) { CreateUserJob (); foreach (string path in paths) { base.Enqueue (path); } } public bool IsImportInProgress { get { return import_element.Processing; } } private bool keep_user_job_hidden = false; public bool KeepUserJobHidden { get { return keep_user_job_hidden; } set { keep_user_job_hidden = value; } } #endregion #region User Job / Interaction private void CreateUserJob () { lock (user_job_mutex) { if (user_job != null || KeepUserJobHidden) { return; } timer_id = Log.DebugTimerStart (); user_job = new UserJob (Title, Catalog.GetString ("Scanning for media")); user_job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database); user_job.PriorityHints = PriorityHints.SpeedSensitive | PriorityHints.DataLossIfStopped; user_job.IconNames = new string [] { "system-search", "gtk-find" }; user_job.CancelMessage = CancelMessage; user_job.CanCancel = true; user_job.CancelRequested += OnCancelRequested; if (!KeepUserJobHidden) { user_job.Register (); } } } private void DestroyUserJob () { lock (user_job_mutex) { if (user_job == null) { return; } if (!KeepUserJobHidden) { Log.DebugTimerPrint (timer_id, Title + " duration: {0}"); } user_job.CancelRequested -= OnCancelRequested; user_job.Finish (); user_job = null; } } private void OnCancelRequested (object o, EventArgs args) { scanner_element.Cancel (); } protected void UpdateProgress (string message) { CreateUserJob (); if (user_job != null) { double new_progress = (double)import_element.ProcessedCount / (double)import_element.TotalCount; double old_progress = user_job.Progress; if (new_progress >= 0.0 && new_progress <= 1.0 && Math.Abs (new_progress - old_progress) > 0.001) { lock (number_format) { string disp_progress = String.Format (ProgressMessage, import_element.ProcessedCount, import_element.TotalCount); user_job.Title = disp_progress; user_job.Status = String.IsNullOrEmpty (message) ? Catalog.GetString ("Scanning...") : message; user_job.Progress = new_progress; } } } } private DateTime last_enqueue_display = DateTime.Now; private void UpdateScannerProgress () { CreateUserJob (); if (user_job != null) { if (DateTime.Now - last_enqueue_display > TimeSpan.FromMilliseconds (400)) { lock (number_format) { number_format.NumberDecimalDigits = 0; user_job.Status = String.Format (Catalog.GetString ("Scanning ({0} files)..."), import_element.TotalCount.ToString ("N", number_format)); last_enqueue_display = DateTime.Now; } } } } #endregion #region Protected Import Hooks protected virtual void OnImportRequested (string path) { ImportEventHandler handler = ImportRequested; if (handler != null && path != null) { ImportEventArgs args = new ImportEventArgs (path); handler (this, args); UpdateProgress (args.ReturnMessage); } else { UpdateProgress (null); } } protected override void OnFinished () { DestroyUserJob (); base.OnFinished (); } #endregion #region Properties private string title = Catalog.GetString ("Importing Media"); public string Title { get { return title; } set { title = value; } } private string cancel_message = Catalog.GetString ( "The import process is currently running. Would you like to stop it?"); public string CancelMessage { get { return cancel_message; } set { cancel_message = value; } } private string progress_message = Catalog.GetString ("Importing {0} of {1}"); public string ProgressMessage { get { return progress_message; } set { progress_message = value; } } public bool Threaded { set { import_element.Threaded = scanner_element.Threaded = value; } } public bool SkipHiddenChildren { set { scanner_element.SkipHiddenChildren = value; } } protected int TotalCount { get { return import_element == null ? 0 : import_element.TotalCount; } } #endregion } }
using FluentAssertions; using IdentityServer.UnitTests.Common; using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using IdentityServer4.Stores.Serialization; using IdentityServer4.UnitTests.Common; using System; using System.Collections.Generic; using System.Security.Claims; using System.Threading.Tasks; using Xunit; namespace IdentityServer.UnitTests.Services.Default { public class DefaultRefreshTokenServiceTests { private DefaultRefreshTokenService _subject; private DefaultRefreshTokenStore _store; private ClaimsPrincipal _user = new IdentityServerUser("123").CreatePrincipal(); private StubClock _clock = new StubClock(); public DefaultRefreshTokenServiceTests() { _store = new DefaultRefreshTokenStore( new InMemoryPersistedGrantStore(), new PersistentGrantSerializer(), new DefaultHandleGenerationService(), TestLogger.Create<DefaultRefreshTokenStore>()); _subject = new DefaultRefreshTokenService( _clock, _store, TestLogger.Create<DefaultRefreshTokenService>()); } [Fact] public async Task CreateRefreshToken_token_exists_in_store() { var client = new Client(); var accessToken = new Token(); var handle = await _subject.CreateRefreshTokenAsync(_user, accessToken, client); (await _store.GetRefreshTokenAsync(handle)).Should().NotBeNull(); } [Fact] public async Task CreateRefreshToken_should_match_absolute_lifetime() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.ReUse, RefreshTokenExpiration = TokenExpiration.Absolute, AbsoluteRefreshTokenLifetime = 10 }; var handle = await _subject.CreateRefreshTokenAsync(_user, new Token(), client); var refreshToken = (await _store.GetRefreshTokenAsync(handle)); refreshToken.Should().NotBeNull(); refreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime); } [Fact] public async Task CreateRefreshToken_should_match_sliding_lifetime() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.ReUse, RefreshTokenExpiration = TokenExpiration.Sliding, SlidingRefreshTokenLifetime = 10 }; var handle = await _subject.CreateRefreshTokenAsync(_user, new Token(), client); var refreshToken = (await _store.GetRefreshTokenAsync(handle)); refreshToken.Should().NotBeNull(); refreshToken.Lifetime.Should().Be(client.SlidingRefreshTokenLifetime); } [Fact] public async Task UpdateRefreshToken_one_time_use_should_create_new_token() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.OneTimeOnly }; var refreshToken = new RefreshToken { CreationTime = DateTime.UtcNow, Lifetime = 10, AccessToken = new Token { ClientId = client.ClientId, Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Claims = new List<Claim>() { new Claim("sub", "123") } } }; var handle = await _store.StoreRefreshTokenAsync(refreshToken); (await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client)) .Should().NotBeNull() .And .NotBe(handle); } [Fact] public async Task UpdateRefreshToken_sliding_with_non_zero_absolute_should_update_lifetime() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.ReUse, RefreshTokenExpiration = TokenExpiration.Sliding, SlidingRefreshTokenLifetime = 10, AbsoluteRefreshTokenLifetime = 100 }; var now = DateTime.UtcNow; _clock.UtcNowFunc = () => now; var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-10), AccessToken = new Token { ClientId = client.ClientId, Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Claims = new List<Claim>() { new Claim("sub", "123") } } }); var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client); newHandle.Should().NotBeNull().And.Be(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); newRefreshToken.Should().NotBeNull(); newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); } [Fact] public async Task UpdateRefreshToken_lifetime_exceeds_absolute_should_be_absolute_lifetime() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.ReUse, RefreshTokenExpiration = TokenExpiration.Sliding, SlidingRefreshTokenLifetime = 10, AbsoluteRefreshTokenLifetime = 1000 }; var now = DateTime.UtcNow; _clock.UtcNowFunc = () => now; var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-1000), AccessToken = new Token { ClientId = client.ClientId, Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Claims = new List<Claim>() { new Claim("sub", "123") } } }); var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client); newHandle.Should().NotBeNull().And.Be(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); newRefreshToken.Should().NotBeNull(); newRefreshToken.Lifetime.Should().Be(client.AbsoluteRefreshTokenLifetime); } [Fact] public async Task UpdateRefreshToken_sliding_with_zero_absolute_should_update_lifetime() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.ReUse, RefreshTokenExpiration = TokenExpiration.Sliding, SlidingRefreshTokenLifetime = 10, AbsoluteRefreshTokenLifetime = 0 }; var now = DateTime.UtcNow; _clock.UtcNowFunc = () => now; var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-1000), AccessToken = new Token { ClientId = client.ClientId, Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Claims = new List<Claim>() { new Claim("sub", "123") } } }); var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client); newHandle.Should().NotBeNull().And.Be(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); newRefreshToken.Should().NotBeNull(); newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); } [Fact] public async Task UpdateRefreshToken_for_onetime_and_sliding_with_zero_absolute_should_update_lifetime() { var client = new Client { ClientId = "client1", RefreshTokenUsage = TokenUsage.OneTimeOnly, RefreshTokenExpiration = TokenExpiration.Sliding, SlidingRefreshTokenLifetime = 10, AbsoluteRefreshTokenLifetime = 0 }; var now = DateTime.UtcNow; _clock.UtcNowFunc = () => now; var handle = await _store.StoreRefreshTokenAsync(new RefreshToken { CreationTime = now.AddSeconds(-1000), AccessToken = new Token { ClientId = client.ClientId, Audiences = { "aud" }, CreationTime = DateTime.UtcNow, Claims = new List<Claim>() { new Claim("sub", "123") } } }); var refreshToken = await _store.GetRefreshTokenAsync(handle); var newHandle = await _subject.UpdateRefreshTokenAsync(handle, refreshToken, client); newHandle.Should().NotBeNull().And.NotBe(handle); var newRefreshToken = await _store.GetRefreshTokenAsync(newHandle); newRefreshToken.Should().NotBeNull(); newRefreshToken.Lifetime.Should().Be((int)(now - newRefreshToken.CreationTime).TotalSeconds + client.SlidingRefreshTokenLifetime); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Portions derived from React Native: // Copyright (c) 2015-present, Facebook, Inc. // Licensed under the MIT License. using Newtonsoft.Json.Linq; using ReactNative.Bridge; using ReactNative.Tracing; using ReactNative.UIManager.LayoutAnimation; using System; using System.Collections.Generic; using System.Linq; using ReactNative.Modules.I18N; #if WINDOWS_UWP using ReactNative.Accessibility; using Windows.Foundation; using Windows.UI.Core; using Windows.UI.Popups; using Windows.UI.Xaml; using Windows.UI.Xaml.Media; #else using System.Windows; using System.Windows.Media; using System.Windows.Threading; #endif namespace ReactNative.UIManager { /// <summary> /// Delegate of <see cref="UIManagerModule"/> that owns the native view /// hierarchy and mapping between native view names used in JavaScript and /// corresponding instances of <see cref="IViewManager"/>. The /// <see cref="UIManagerModule"/> communicates with this class by it's /// public interface methods: /// - <see cref="UpdateProps(int, JObject)"/> /// - <see cref="UpdateLayout(int, int, Dimensions)"/> /// - <see cref="CreateView(ThemedReactContext, int, string, JObject)"/> /// - <see cref="ManageChildren(int, int[], ViewAtIndex[], int[])"/> /// executing all the scheduled operations at the end of the JavaScript batch. /// </summary> /// <remarks> /// All native view management methods listed above must be called from the /// dispatcher thread. /// /// The <see cref="ReactContext"/> instance that is passed to views that /// this manager creates differs from the one that we pass to the /// constructor. Instead we wrap the provided instance of /// <see cref="ReactContext"/> in an instance of <see cref="ThemedReactContext"/> /// that additionally provides a correct theme based on the root view for /// a view tree that we attach newly created views to. Therefore this view /// manager will create a copy of <see cref="ThemedReactContext"/> that /// wraps the instance of <see cref="ReactContext"/> for each root view /// added to the manager (see /// <see cref="AddRootView(int, SizeMonitoringCanvas, ThemedReactContext)"/>). /// /// TODO: /// 1) AnimationRegistry /// 2) ShowPopupMenu /// </remarks> public class NativeViewHierarchyManager { private readonly IDictionary<int, IViewManager> _tagsToViewManagers; private readonly IDictionary<int, object> _tagsToViews; private readonly IDictionary<int, bool> _rootTags; private readonly ViewManagerRegistry _viewManagers; private readonly RootViewManager _rootViewManager; private readonly LayoutAnimationController _layoutAnimator; private readonly DeletedTagsBatchReporter _deletedTagsBatchReporter; private class DeletedTagsBatchReporter { private readonly Action<List<int>> _onDropView; private List<int> _pendingDeletedTags; public DeletedTagsBatchReporter(Action<List<int>> onDropView) { _onDropView = onDropView; } public void Report(int tag) { if (_onDropView == null) return; if (_pendingDeletedTags == null) { _pendingDeletedTags = new List<int>(); } _pendingDeletedTags.Add(tag); } public void Send() { if (_onDropView == null || _pendingDeletedTags == null) return; var pendingDeletedTags = _pendingDeletedTags; _pendingDeletedTags = null; _onDropView(pendingDeletedTags); } } /// <summary> /// Instantiates the <see cref="NativeViewHierarchyManager"/>. /// </summary> /// <param name="viewManagers">The view manager registry.</param> /// <param name="dispatcher">The dispatcher of the view.</param> /// <param name="onDropView">Notification callback to be passed lists of dropped views tags.</param> public NativeViewHierarchyManager(ViewManagerRegistry viewManagers, #if WINDOWS_UWP CoreDispatcher dispatcher, #else #pragma warning disable CS1573 Dispatcher dispatcher, #pragma warning restore CS1573 #endif Action<List<int>> onDropView ) { _viewManagers = viewManagers; _layoutAnimator = new LayoutAnimationController(); _tagsToViews = new Dictionary<int, object>(); _tagsToViewManagers = new Dictionary<int, IViewManager>(); _rootTags = new Dictionary<int, bool>(); _rootViewManager = new RootViewManager(); #if WINDOWS_UWP Dispatcher = dispatcher; #endif _deletedTagsBatchReporter = new DeletedTagsBatchReporter(onDropView); } /// <summary> /// Signals if layout animation is enabled. /// </summary> public bool LayoutAnimationEnabled { private get; set; } /// <summary> /// Updates the props of the view with the given tag. /// </summary> /// <param name="tag">The view tag.</param> /// <param name="props">The props.</param> public void UpdateProps(int tag, JObject props) { AssertOnCorrectDispatcher(); var viewManager = ResolveViewManager(tag); var viewToUpdate = ResolveView(tag); viewManager.UpdateProps(viewToUpdate, props); } /// <summary> /// Updates the extra data for the view with the given tag. /// </summary> /// <param name="tag">The view tag.</param> /// <param name="extraData">The extra data.</param> public void UpdateViewExtraData(int tag, object extraData) { AssertOnCorrectDispatcher(); var viewManager = ResolveViewManager(tag); var viewToUpdate = ResolveView(tag); viewManager.UpdateExtraData(viewToUpdate, extraData); } /// <summary> /// Updates the layout of a view. /// </summary> /// <param name="parentTag">The parent view tag.</param> /// <param name="tag">The view tag.</param> /// <param name="dimensions">The dimensions.</param> public void UpdateLayout(int parentTag, int tag, Dimensions dimensions) { AssertOnCorrectDispatcher(); using (Tracer.Trace(Tracer.TRACE_TAG_REACT_VIEW, "NativeViewHierarcyManager.UpdateLayout") .With("parentTag", parentTag) .With("tag", tag) .Start()) { var viewToUpdate = ResolveView(tag); var viewManager = ResolveViewManager(tag); if (!_tagsToViewManagers.TryGetValue(parentTag, out var parentViewManager) || !(parentViewManager is IViewParentManager parentViewParentManager)) { throw new InvalidOperationException($"Trying to use view with tag '{tag}' as a parent, but its manager doesn't extend ViewParentManager."); } if (!parentViewParentManager.NeedsCustomLayoutForChildren) { UpdateLayout(viewToUpdate, viewManager, dimensions); } } } /// <summary> /// Creates a view with the given tag and class name. /// </summary> /// <param name="themedContext">The context.</param> /// <param name="tag">The tag.</param> /// <param name="className">The class name.</param> /// <param name="initialProps">The initial props.</param> public void CreateView(ThemedReactContext themedContext, int tag, string className, JObject initialProps) { AssertOnCorrectDispatcher(); using (Tracer.Trace(Tracer.TRACE_TAG_REACT_VIEW, "NativeViewHierarcyManager.CreateView") .With("tag", tag) .With("className", className) .Start()) { var viewManager = _viewManagers.Get(className); var view = viewManager.CreateView(themedContext); _tagsToViews.Add(tag, view); _tagsToViewManagers.Add(tag, viewManager); ViewExtensions.SetTag(view, tag); ViewExtensions.SetReactContext(view, themedContext); #if WINDOWS_UWP if (view is UIElement element) { AccessibilityHelper.OnViewInstanceCreated(element); } #endif if (initialProps != null) { viewManager.UpdateProps(view, initialProps); } } } /// <summary> /// Sets up the Layout Animation Manager. /// </summary> /// <param name="config"></param> /// <param name="success"></param> /// <param name="error"></param> public void ConfigureLayoutAnimation(JObject config, ICallback success, ICallback error) { _layoutAnimator.InitializeFromConfig(config); } /// <summary> /// Clears out the <see cref="LayoutAnimationController"/> and processes accessibility changes /// </summary> public void OnBatchComplete() { _layoutAnimator.Reset(); #if WINDOWS_UWP AccessibilityHelper.OnBatchComplete(); #endif } /// <summary> /// Manages the children of a React view. /// </summary> /// <param name="tag">The tag of the view to manager.</param> /// <param name="indexesToRemove">Child indices to remove.</param> /// <param name="viewsToAdd">Views to add.</param> /// <param name="tagsToDelete">Tags to delete.</param> public void ManageChildren(int tag, int[] indexesToRemove, ViewAtIndex[] viewsToAdd, int[] tagsToDelete) { if (!_tagsToViewManagers.TryGetValue(tag, out var viewManager)) { throw new InvalidOperationException($"Trying to manage children with tag '{tag}' which doesn't exist."); } var viewParentManager = (IViewParentManager)viewManager; var viewToManage = _tagsToViews[tag]; var lastIndexToRemove = viewParentManager.GetChildCount(viewToManage); if (indexesToRemove != null) { for (var i = indexesToRemove.Length - 1; i >= 0; --i) { var indexToRemove = indexesToRemove[i]; if (indexToRemove < 0) { throw new InvalidOperationException($"Trying to remove a negative index '{indexToRemove}' on view tag '{tag}'."); } if (indexToRemove >= viewParentManager.GetChildCount(viewToManage)) { throw new InvalidOperationException($"Trying to remove a view index '{indexToRemove}' greater than the child could for view tag '{tag}'."); } if (indexToRemove >= lastIndexToRemove) { throw new InvalidOperationException($"Trying to remove an out of order index '{indexToRemove}' (last index was '{lastIndexToRemove}') for view tag '{tag}'."); } if (viewParentManager.GetChildAt(viewToManage, indexToRemove) is FrameworkElement viewToRemove && _layoutAnimator.ShouldAnimateLayout(viewToRemove) && tagsToDelete.Contains(viewToRemove.GetTag())) { // The view will be removed and dropped by the 'delete' // layout animation instead, so do nothing. } else { viewParentManager.RemoveChildAt(viewToManage, indexToRemove); } lastIndexToRemove = indexToRemove; } } if (viewsToAdd != null) { for (var i = 0; i < viewsToAdd.Length; ++i) { var viewAtIndex = viewsToAdd[i]; if (!_tagsToViews.TryGetValue(viewAtIndex.Tag, out var viewToAdd)) { throw new InvalidOperationException($"Trying to add unknown view tag '{viewAtIndex.Tag}'."); } viewParentManager.AddView(viewToManage, viewToAdd, viewAtIndex.Index); } } if (tagsToDelete != null) { for (var i = 0; i < tagsToDelete.Length; ++i) { var tagToDelete = tagsToDelete[i]; if (!_tagsToViews.TryGetValue(tagToDelete, out var viewToDestroy)) { throw new InvalidOperationException($"Trying to destroy unknown view tag '{tagToDelete}'."); } if (_layoutAnimator.ShouldAnimateLayout(viewToDestroy)) { var viewToDestroyManager = ResolveViewManager(tagToDelete); _layoutAnimator.DeleteView(viewToDestroyManager, viewToDestroy, () => { if (viewParentManager.TryRemoveView(viewToManage, viewToDestroy)) { DropView(viewToDestroy); } }); } else { DropView(viewToDestroy); } } } _deletedTagsBatchReporter.Send(); } /// <summary> /// Simplified version of <see cref="UIManagerModule.manageChildren(int, int[], int[], int[], int[], int[])"/> /// that only deals with adding children views. /// </summary> /// <param name="tag">The view tag to manage.</param> /// <param name="childrenTags">The children tags.</param> public void SetChildren(int tag, int[] childrenTags) { var viewToManage = _tagsToViews[tag]; var viewManager = (IViewParentManager)ResolveViewManager(tag); for (var i = 0; i < childrenTags.Length; ++i) { var viewToAdd = _tagsToViews[childrenTags[i]]; if (viewToAdd == null) { throw new InvalidOperationException($"Trying to add unknown view tag: {childrenTags[i]}."); } viewManager.AddView(viewToManage, viewToAdd, i); } } /// <summary> /// Remove the root view with the given tag. /// </summary> /// <param name="rootViewTag">The root view tag.</param> public void RemoveRootView(int rootViewTag) { AssertOnCorrectDispatcher(); if (!_rootTags.ContainsKey(rootViewTag)) { throw new InvalidOperationException($"View with tag '{rootViewTag}' is not registered as a root view."); } var rootView = _tagsToViews[rootViewTag]; DropView(rootView); _rootTags.Remove(rootViewTag); #if WINDOWS_UWP if (rootView is UIElement element) { AccessibilityHelper.OnRootViewRemoved(element); } #endif _deletedTagsBatchReporter.Send(); } /// <summary> /// Measures a view and sets the output buffer to (x, y, width, height). /// Measurements are relative to the RootView. /// </summary> /// <param name="tag">The view tag.</param> /// <param name="outputBuffer">The output buffer.</param> public void Measure(int tag, double[] outputBuffer) { AssertOnCorrectDispatcher(); if (!_tagsToViews.TryGetValue(tag, out var view)) { throw new ArgumentOutOfRangeException(nameof(tag)); } if (!_tagsToViewManagers.TryGetValue(tag, out var viewManager)) { throw new InvalidOperationException($"Could not find view manager for tag '{tag}."); } // TODO: can we get the relative coordinates without conversion? var uiElement = ViewConversion.GetDependencyObject<UIElement>(view); var rootView = RootViewHelper.GetRootView(uiElement); if (rootView == null) { throw new InvalidOperationException($"Native view '{tag}' is no longer on screen."); } // TODO: better way to get relative position? var rootTransform = uiElement.TransformToVisual(rootView); #if WINDOWS_UWP var positionInRoot = rootTransform.TransformPoint(new Point(0, 0)); #else var positionInRoot = rootTransform.Transform(new Point(0, 0)); #endif var dimensions = viewManager.GetDimensions(view); outputBuffer[0] = positionInRoot.X; outputBuffer[1] = positionInRoot.Y; outputBuffer[2] = dimensions.Width; outputBuffer[3] = dimensions.Height; } /// <summary> /// Measures a view and sets the output buffer to (x, y, width, height). /// Measurements are relative to the window. /// </summary> /// <param name="tag">The view tag.</param> /// <param name="outputBuffer">The output buffer.</param> public void MeasureInWindow(int tag, double[] outputBuffer) { AssertOnCorrectDispatcher(); if (!_tagsToViews.TryGetValue(tag, out var view)) { throw new ArgumentOutOfRangeException(nameof(tag)); } if (!_tagsToViewManagers.TryGetValue(tag, out var viewManager)) { throw new InvalidOperationException($"Could not find view manager for tag '{tag}."); } // // The top level Xaml element (Window.Current.Content) and the root view the element with tag is associated with have to // have consistent FlowDirection for the result to be fully correct // var uiElement = ViewConversion.GetDependencyObject<UIElement>(view); #if WINDOWS_UWP var windowTransform = uiElement.TransformToVisual(Window.Current.Content); var positionInWindow = windowTransform.TransformPoint(new Point(0, 0)); #else var windowTransform = uiElement.TransformToVisual(Application.Current.Windows.OfType<Window>().FirstOrDefault(w => w.IsActive)); var positionInWindow = windowTransform.Transform(new Point(0, 0)); #endif var dimensions = viewManager.GetDimensions(view); outputBuffer[0] = positionInWindow.X; outputBuffer[1] = positionInWindow.Y; outputBuffer[2] = dimensions.Width; outputBuffer[3] = dimensions.Height; } /// <summary> /// Adds a root view with the given tag. /// </summary> /// <param name="tag">The tag.</param> /// <param name="view">The root view.</param> /// <param name="themedContext">The themed context.</param> public void AddRootView(int tag, SizeMonitoringCanvas view, ThemedReactContext themedContext) { AddRootViewParent(tag, view, themedContext); } /// <summary> /// Refreshes RTL/LTR direction on all root views. /// </summary> public void UpdateRootViewNodesDirection() { foreach (var tag in _rootTags.Keys.ToList()) { if (_tagsToViews[tag] is FrameworkElement element) { element.FlowDirection = I18NUtil.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; } } } /// <summary> /// Find the view target for touch coordinates. /// </summary> /// <param name="reactTag">The view tag.</param> /// <param name="touchX">The x-coordinate of the touch event.</param> /// <param name="touchY">The y-coordinate of the touch event.</param> /// <returns>The view target.</returns> public int FindTargetForTouch(int reactTag, double touchX, double touchY) { if (!_tagsToViews.TryGetValue(reactTag, out var view)) { throw new InvalidOperationException($"Could not find view with tag '{reactTag}'."); } var uiElement = ViewConversion.GetDependencyObject<UIElement>(view); #if WINDOWS_UWP var target = VisualTreeHelper.FindElementsInHostCoordinates(new Point(touchX, touchY), uiElement) #else var sources = new List<DependencyObject>(); // ToDo: Consider a pooled structure to improve performance in touch heavy applications VisualTreeHelper.HitTest( uiElement, null, hit => { sources.Add(hit.VisualHit); return HitTestResultBehavior.Continue; }, new PointHitTestParameters(new Point(touchX, touchY))); var target = sources #endif .OfType<FrameworkElement>() .Where(e => e.HasTag()) .FirstOrDefault(); if (target == null) { throw new InvalidOperationException($"Could not find React view at coordinates '{touchX},{touchY}'."); } return target.GetTag(); } /// <summary> /// Dispatches a command to a view. /// </summary> /// <param name="reactTag">The view tag.</param> /// <param name="commandId">The command identifier.</param> /// <param name="args">The command arguments.</param> public void DispatchCommand(int reactTag, int commandId, JArray args) { AssertOnCorrectDispatcher(); if (!_tagsToViews.TryGetValue(reactTag, out var view)) { throw new InvalidOperationException($"Trying to send command to a non-existent view with tag '{reactTag}."); } var viewManager = ResolveViewManager(reactTag); viewManager.ReceiveCommand(view, commandId, args); } /// <summary> /// Shows a popup menu. /// </summary> /// <param name="tag"> /// The tag of the anchor view (the popup menu is /// displayed next to this view); this needs to be the tag of a native /// view (shadow views cannot be anchors). /// </param> /// <param name="items">The menu items as an array of strings.</param> /// <param name="success"> /// A callback used with the position of the selected item as the first /// argument, or no arguments if the menu is dismissed. /// </param> public void ShowPopupMenu(int tag, string[] items, ICallback success) { #if WINDOWS_UWP AssertOnCorrectDispatcher(); var view = ResolveView(tag); var menu = new PopupMenu(); for (var i = 0; i < items.Length; ++i) { menu.Commands.Add(new UICommand( items[i], cmd => { success.Invoke(cmd.Id); }, i)); } #endif // TODO: figure out where to popup the menu // TODO: add continuation that calls the callback with empty args throw new NotImplementedException(); } /// <summary> /// Checks whether a view exists. /// </summary> /// <param name="tag">The tag of the view.</param> /// <returns> /// <code>true</code> if the view still exists, otherwise <code>false</code>. /// </returns> public bool ViewExists(int tag) { return _tagsToViews.ContainsKey(tag); } /// <summary> /// Resolves a view. /// </summary> /// <param name="tag">The tag of the view.</param> public object ResolveView(int tag) { if (!_tagsToViews.TryGetValue(tag, out var view)) { throw new InvalidOperationException($"Trying to resolve view with tag '{tag}' which doesn't exist."); } return view; } /// <summary> /// Resolves a view's view manager. /// </summary> /// <param name="tag">The tag of the view.</param> public IViewManager ResolveViewManager(int tag) { if (!_tagsToViewManagers.TryGetValue(tag, out var viewManager)) { throw new InvalidOperationException($"ViewManager for tag '{tag}' could not be found."); } return viewManager; } internal void DropAllViews() { AssertOnCorrectDispatcher(); foreach (var tag in _rootTags.Keys.ToList()) { RemoveRootView(tag); } } #if WINDOWS_UWP internal CoreDispatcher Dispatcher { get; private set; } #endif private void AddRootViewParent(int tag, FrameworkElement view, ThemedReactContext themedContext) { AssertOnCorrectDispatcher(); _tagsToViews.Add(tag, view); _tagsToViewManagers.Add(tag, _rootViewManager); _rootTags.Add(tag, true); // Keeping here for symmetry, tag on root views is set early, in UIManagerModule.AddMeasuredRootViewAsync ViewExtensions.SetTag(view, tag); ViewExtensions.SetReactContext(view, themedContext); // Initialize the top level Xaml Flow Direction view.FlowDirection = I18NUtil.IsRightToLeft ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; #if WINDOWS_UWP AccessibilityHelper.OnRootViewAdded(view); #endif } private void DropView(object view) { AssertOnCorrectDispatcher(); var tag = ViewExtensions.GetTag(view); if (!_rootTags.ContainsKey(tag)) { // For non-root views, we notify the view manager with `OnDropViewInstance` var mgr = ResolveViewManager(tag); mgr.OnDropViewInstance(ViewExtensions.GetReactContext(view), view); } if (_tagsToViewManagers.TryGetValue(tag, out var viewManager)) { if (viewManager is IViewParentManager viewParentManager) { for (var i = viewParentManager.GetChildCount(view) - 1; i >= 0; --i) { var child = viewParentManager.GetChildAt(view, i); if (_tagsToViews.TryGetValue(child.GetTag(), out var managedChild)) { DropView(managedChild); } } viewParentManager.RemoveAllChildren(view); } } #if WINDOWS_UWP if (view is UIElement element) { AccessibilityHelper.OnDropViewInstance(element); } #endif _tagsToViews.Remove(tag); _tagsToViewManagers.Remove(tag); ViewExtensions.ClearData(view); _deletedTagsBatchReporter.Report(tag); } private void UpdateLayout(object viewToUpdate, IViewManager viewManager, Dimensions dimensions) { if (_layoutAnimator.ShouldAnimateLayout(viewToUpdate)) { _layoutAnimator.ApplyLayoutUpdate(viewManager, viewToUpdate, dimensions); } else { viewManager.SetDimensions(viewToUpdate, dimensions); } } private void AssertOnCorrectDispatcher() { #if WINDOWS_UWP #if DEBUG if (!DispatcherHelpers.IsOnDispatcher(Dispatcher)) { // Each NativeViewHierarxhyManager object has a dedicated Dispatcher thread affinity. // Accessing from a wrong thread is fatal. throw new InvalidOperationException("Thread does not have correct dispatcher access."); } #endif #else DispatcherHelpers.AssertOnDispatcher(); #endif } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using JoinRpg.Data.Interfaces; using JoinRpg.DataModel; using JoinRpg.Domain; using JoinRpg.Helpers; using JoinRpg.Portal.Controllers.Common; using JoinRpg.Portal.Infrastructure; using JoinRpg.Portal.Infrastructure.Authorization; using JoinRpg.Services.Interfaces; using JoinRpg.Services.Interfaces.Projects; using JoinRpg.Web.Helpers; using JoinRpg.Web.Models; using JoinRpg.Web.Models.Plot; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace JoinRpg.Portal.Controllers { [Route("{projectId}/plot/[action]")] public class PlotController : ControllerGameBase { private readonly IPlotService _plotService; private readonly IPlotRepository _plotRepository; private IUriService UriService { get; } public PlotController( IProjectRepository projectRepository, IProjectService projectService, IPlotService plotService, IPlotRepository plotRepository, IUriService uriService, IUserRepository userRepository) : base(projectRepository, projectService, userRepository) { _plotService = plotService; _plotRepository = plotRepository; UriService = uriService; } [MasterAuthorize(Permission.CanManagePlots)] [HttpGet] public async Task<ActionResult> Create(int projectId) { var project1 = await ProjectRepository.GetProjectAsync(projectId); return View(new AddPlotFolderViewModel { ProjectId = project1.ProjectId, ProjectName = project1.ProjectName, }); } [HttpPost, ValidateAntiForgeryToken, MasterAuthorize(Permission.CanManagePlots)] public async Task<ActionResult> Create(AddPlotFolderViewModel viewModel) { if (!ModelState.IsValid) { return View(viewModel); } try { await _plotService.CreatePlotFolder(viewModel.ProjectId, viewModel.PlotFolderTitleAndTags, viewModel.TodoField); return RedirectToAction("Index", "PlotList", new { viewModel.ProjectId }); } catch (Exception exception) { ModelState.AddException(exception); return View(viewModel); } } [HttpGet, RequireMasterOrPublish] public async Task<ActionResult> Edit(int projectId, int plotFolderId) { var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new EditPlotFolderViewModel(folder, CurrentUserIdOrDefault, UriService)); } [HttpPost, ValidateAntiForgeryToken, MasterAuthorize(Permission.CanManagePlots)] public async Task<ActionResult> Edit(EditPlotFolderViewModel viewModel) { try { await _plotService.EditPlotFolder(viewModel.ProjectId, viewModel.PlotFolderId, viewModel.PlotFolderTitleAndTags, viewModel.TodoField); return ReturnToPlot(viewModel.ProjectId, viewModel.PlotFolderId); } catch (Exception exception) { ModelState.AddException(exception); var folder = await _plotRepository.GetPlotFolderAsync(viewModel.ProjectId, viewModel.PlotFolderId); viewModel.Fill(folder, CurrentUserId, UriService); return View(viewModel); } } #region Create elements & handouts [HttpGet, MasterAuthorize()] public async Task<ActionResult> CreateElement(int projectId, int plotFolderId) { var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new AddPlotElementViewModel() { ProjectId = projectId, PlotFolderId = plotFolderId, PlotFolderName = folder.MasterTitle, }); } [HttpGet, MasterAuthorize()] public async Task<ActionResult> CreateHandout(int projectId, int plotFolderId) { var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new AddPlotHandoutViewModel() { ProjectId = projectId, PlotFolderId = plotFolderId, PlotFolderName = folder.MasterTitle, }); } [HttpPost, MasterAuthorize(), ValidateAntiForgeryToken] public async Task<ActionResult> CreateHandout(int projectId, int plotFolderId, string content, string todoField, [CanBeNull] ICollection<string> targets, PlotElementTypeView elementType) { try { return await CreateElementImpl(projectId, plotFolderId, content, todoField, targets, elementType); } catch (Exception exception) { ModelState.AddException(exception); var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new AddPlotHandoutViewModel() { ProjectId = projectId, PlotFolderId = plotFolderId, PlotFolderName = folder.MasterTitle, Content = content, TodoField = todoField, }); } } [HttpPost, MasterAuthorize(), ValidateAntiForgeryToken] public async Task<ActionResult> CreateElement(int projectId, int plotFolderId, string content, string todoField, [CanBeNull] ICollection<string> targets, PlotElementTypeView elementType) { try { return await CreateElementImpl(projectId, plotFolderId, content, todoField, targets, elementType); } catch (Exception exception) { ModelState.AddException(exception); var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new AddPlotElementViewModel() { ProjectId = projectId, PlotFolderId = plotFolderId, PlotFolderName = folder.MasterTitle, Content = content, TodoField = todoField, }); } } private async Task<ActionResult> CreateElementImpl(int projectId, int plotFolderId, string content, string todoField, ICollection<string> targets, PlotElementTypeView elementType) { var targetGroups = targets.OrEmptyList().GetUnprefixedGroups(); var targetChars = targets.OrEmptyList().GetUnprefixedChars(); await _plotService.CreatePlotElement(projectId, plotFolderId, content, todoField, targetGroups, targetChars, (PlotElementType)elementType); return ReturnToPlot(projectId, plotFolderId); } #endregion #region private methods #endregion [HttpGet, MasterAuthorize(Permission.CanManagePlots)] public async Task<ActionResult> Delete(int projectId, int plotFolderId) { var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new EditPlotFolderViewModel(folder, CurrentUserId, UriService)); } [HttpPost, MasterAuthorize(Permission.CanManagePlots), ValidateAntiForgeryToken] public async Task<ActionResult> Delete(int projectId, int plotFolderId, [UsedImplicitly] IFormCollection collection) { try { await _plotService.DeleteFolder(projectId, plotFolderId); return RedirectToAction("Index", "PlotList", new { projectId }); } catch (Exception) { return await Delete(projectId, plotFolderId); } } [HttpPost, MasterAuthorize(Permission.CanManagePlots), ValidateAntiForgeryToken] public async Task<ActionResult> DeleteElement(int plotelementid, int plotFolderId, int projectId) { try { await _plotService.DeleteElement(projectId, plotFolderId, plotelementid); return ReturnToPlot(projectId, plotFolderId); } catch (Exception) { return await Edit(projectId, plotFolderId); } } private ActionResult ReturnToPlot(int projectId, int plotFolderId) => RedirectToAction("Edit", new { projectId, plotFolderId }); [HttpGet, MasterAuthorize()] public async Task<ActionResult> EditElement(int plotelementid, int plotFolderId, int projectId) { var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } var viewModel = new EditPlotElementViewModel(folder.Elements.Single(e => e.PlotElementId == plotelementid), folder.HasMasterAccess(CurrentUserId, acl => acl.CanManagePlots), UriService); return View(viewModel); } [HttpPost, MasterAuthorize()] public async Task<ActionResult> EditElement(int plotelementid, int plotFolderId, int projectId, string content, string todoField, [CanBeNull] ICollection<string> targets) { try { var project = await ProjectRepository.GetProjectAsync(projectId); if (project.HasMasterAccess(CurrentUserId, acl => acl.CanManagePlots)) { var targetGroups = targets.OrEmptyList().GetUnprefixedGroups(); var targetChars = targets.OrEmptyList().GetUnprefixedChars(); await _plotService.EditPlotElement(projectId, plotFolderId, plotelementid, content, todoField, targetGroups, targetChars); } else { await _plotService.EditPlotElementText(projectId, plotFolderId, plotelementid, content, todoField); } return ReturnToPlot(projectId, plotFolderId); } catch (Exception) { return await Edit(projectId, plotFolderId); } } //TODO: Make this POST [HttpGet] [MasterAuthorize(Permission.CanEditRoles)] public async Task<ActionResult> MoveElementForCharacter(int projectid, int listItemId, int parentObjectId, int direction) { try { await _plotService.MoveElement(projectid, listItemId, parentObjectId, direction); return RedirectToAction("Details", "Character", new { projectId = projectid, characterId = parentObjectId }); } catch { return RedirectToAction("Details", "Character", new { projectId = projectid, characterId = parentObjectId }); } } [HttpPost] [MasterAuthorize(Permission.CanManagePlots)] [ValidateAntiForgeryToken] public async Task<ActionResult> PublishElement(PublishPlotElementViewModel model) { try { await _plotService.PublishElementVersion(model); return ReturnToPlot(model.ProjectId, model.PlotFolderId); } catch (Exception) { throw; // return await Edit(model.ProjectId, model.PlotFolderId); } } [HttpPost] [MasterAuthorize(Permission.CanManagePlots)] [ValidateAntiForgeryToken] public async Task<ActionResult> UnPublishElement(PublishPlotElementViewModel model) { try { model.Version = null; await _plotService.PublishElementVersion(model); return ReturnToPlot(model.ProjectId, model.PlotFolderId); } catch (Exception) { throw; //return await Edit(model.ProjectId, model.PlotFolderId); } } [HttpGet, MasterAuthorize()] public async Task<ActionResult> ShowElementVersion(int projectId, int plotFolderId, int plotElementId, int version) { var folder = await _plotRepository.GetPlotFolderAsync(projectId, plotFolderId); if (folder == null) { return NotFound(); } return View(new PlotElementListItemViewModel(folder.Elements.Single(e => e.PlotElementId == plotElementId), CurrentUserId, UriService, version)); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Contracts; using System.Globalization; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Text; using Microsoft.Win32; namespace System.IO { public sealed class DirectoryInfo : FileSystemInfo { [System.Security.SecuritySafeCritical] public DirectoryInfo(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); Init(path); } [System.Security.SecurityCritical] private void Init(String path) { // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((path.Length == 2) && (path[1] == ':')) { OriginalPath = "."; } else { OriginalPath = path; } String fullPath = PathHelpers.GetFullPathInternal(path); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } [System.Security.SecuritySafeCritical] internal DirectoryInfo(String fullPath, IFileSystemObject fileSystemObject) : base(fileSystemObject) { Debug.Assert(PathHelpers.GetRootLength(fullPath) > 0, "fullPath must be fully qualified!"); // Fast path when we know a DirectoryInfo exists. OriginalPath = Path.GetFileName(fullPath); FullPath = fullPath; DisplayPath = GetDisplayName(OriginalPath, FullPath); } public override String Name { get { // DisplayPath is dir name for coreclr Debug.Assert(GetDirName(FullPath) == DisplayPath || DisplayPath == "."); return DisplayPath; } } public DirectoryInfo Parent { [System.Security.SecuritySafeCritical] get { String parentName; // FullPath might be either "c:\bar" or "c:\bar\". Handle // those cases, as well as avoiding mangling "c:\". String s = FullPath; if (s.Length > 3 && s[s.Length - 1] == Path.DirectorySeparatorChar) s = FullPath.Substring(0, FullPath.Length - 1); parentName = Path.GetDirectoryName(s); if (parentName == null) return null; DirectoryInfo dir = new DirectoryInfo(parentName, null); return dir; } } [System.Security.SecuritySafeCritical] public DirectoryInfo CreateSubdirectory(String path) { if (path == null) throw new ArgumentNullException("path"); Contract.EndContractBlock(); return CreateSubdirectoryHelper(path); } [System.Security.SecurityCritical] // auto-generated private DirectoryInfo CreateSubdirectoryHelper(String path) { Contract.Requires(path != null); PathHelpers.ThrowIfEmptyOrRootedPath(path); String newDirs = Path.Combine(FullPath, path); String fullPath = Path.GetFullPath(newDirs); if (0 != String.Compare(FullPath, 0, fullPath, 0, FullPath.Length, PathInternal.GetComparison())) { throw new ArgumentException(SR.Format(SR.Argument_InvalidSubPath, path, DisplayPath)); } FileSystem.Current.CreateDirectory(fullPath); // Check for read permission to directory we hand back by calling this constructor. return new DirectoryInfo(fullPath); } [System.Security.SecurityCritical] public void Create() { FileSystem.Current.CreateDirectory(FullPath); } // Tests if the given path refers to an existing DirectoryInfo on disk. // // Your application must have Read permission to the directory's // contents. // public override bool Exists { [System.Security.SecuritySafeCritical] // auto-generated get { try { return FileSystemObject.Exists; } catch { return false; } } } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). [SecurityCritical] public FileInfo[] GetFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). public FileInfo[] GetFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFiles(searchPattern, searchOption); } // Returns an array of Files in the current DirectoryInfo matching the // given search criteria (ie, "*.txt"). private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileInfo> enble = (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); List<FileInfo> fileList = new List<FileInfo>(enble); return fileList.ToArray(); } // Returns an array of Files in the DirectoryInfo specified by path public FileInfo[] GetFiles() { return InternalGetFiles("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current directory. public DirectoryInfo[] GetDirectories() { return InternalGetDirectories("*", SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). public FileSystemInfo[] GetFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetFileSystemInfos(searchPattern, searchOption); } // Returns an array of strongly typed FileSystemInfo entries in the path with the // given search criteria (ie, "*.txt"). private FileSystemInfo[] InternalGetFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<FileSystemInfo> enumerable = FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); List<FileSystemInfo> fileList = new List<FileSystemInfo>(enumerable); return fileList.ToArray(); } // Returns an array of strongly typed FileSystemInfo entries which will contain a listing // of all the files and directories. public FileSystemInfo[] GetFileSystemInfos() { return InternalGetFileSystemInfos("*", SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, SearchOption.TopDirectoryOnly); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). public DirectoryInfo[] GetDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalGetDirectories(searchPattern, searchOption); } // Returns an array of Directories in the current DirectoryInfo matching the // given search criteria (ie, "System*" could match the System & System32 // directories). private DirectoryInfo[] InternalGetDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); IEnumerable<DirectoryInfo> enumerable = (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); List<DirectoryInfo> fileList = new List<DirectoryInfo>(enumerable); return fileList.ToArray(); } public IEnumerable<DirectoryInfo> EnumerateDirectories() { return InternalEnumerateDirectories("*", SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<DirectoryInfo> EnumerateDirectories(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateDirectories(searchPattern, searchOption); } private IEnumerable<DirectoryInfo> InternalEnumerateDirectories(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<DirectoryInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Directories); } public IEnumerable<FileInfo> EnumerateFiles() { return InternalEnumerateFiles("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileInfo> EnumerateFiles(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFiles(searchPattern, searchOption); } private IEnumerable<FileInfo> InternalEnumerateFiles(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return (IEnumerable<FileInfo>)FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Files); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos() { return InternalEnumerateFileSystemInfos("*", SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, SearchOption.TopDirectoryOnly); } public IEnumerable<FileSystemInfo> EnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { if (searchPattern == null) throw new ArgumentNullException("searchPattern"); if ((searchOption != SearchOption.TopDirectoryOnly) && (searchOption != SearchOption.AllDirectories)) throw new ArgumentOutOfRangeException("searchOption", SR.ArgumentOutOfRange_Enum); Contract.EndContractBlock(); return InternalEnumerateFileSystemInfos(searchPattern, searchOption); } private IEnumerable<FileSystemInfo> InternalEnumerateFileSystemInfos(String searchPattern, SearchOption searchOption) { Contract.Requires(searchPattern != null); Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly); return FileSystem.Current.EnumerateFileSystemInfos(FullPath, searchPattern, searchOption, SearchTarget.Both); } // Returns the root portion of the given path. The resulting string // consists of those rightmost characters of the path that constitute the // root of the path. Possible patterns for the resulting string are: An // empty string (a relative path on the current drive), "\" (an absolute // path on the current drive), "X:" (a relative path on a given drive, // where X is the drive letter), "X:\" (an absolute path on a given drive), // and "\\server\share" (a UNC path for a given server and share name). // The resulting string is null if path is null. // public DirectoryInfo Root { [System.Security.SecuritySafeCritical] get { String rootPath = Path.GetPathRoot(FullPath); return new DirectoryInfo(rootPath); } } [System.Security.SecuritySafeCritical] public void MoveTo(String destDirName) { if (destDirName == null) throw new ArgumentNullException("destDirName"); if (destDirName.Length == 0) throw new ArgumentException(SR.Argument_EmptyFileName, "destDirName"); Contract.EndContractBlock(); String fullDestDirName = PathHelpers.GetFullPathInternal(destDirName); if (fullDestDirName[fullDestDirName.Length - 1] != Path.DirectorySeparatorChar) fullDestDirName = fullDestDirName + PathHelpers.DirectorySeparatorCharAsString; String fullSourcePath; if (FullPath.Length > 0 && FullPath[FullPath.Length - 1] == Path.DirectorySeparatorChar) fullSourcePath = FullPath; else fullSourcePath = FullPath + PathHelpers.DirectorySeparatorCharAsString; StringComparison pathComparison = PathInternal.GetComparison(); if (String.Equals(fullSourcePath, fullDestDirName, pathComparison)) throw new IOException(SR.IO_SourceDestMustBeDifferent); String sourceRoot = Path.GetPathRoot(fullSourcePath); String destinationRoot = Path.GetPathRoot(fullDestDirName); if (!String.Equals(sourceRoot, destinationRoot, pathComparison)) throw new IOException(SR.IO_SourceDestMustHaveSameRoot); FileSystem.Current.MoveDirectory(FullPath, fullDestDirName); FullPath = fullDestDirName; OriginalPath = destDirName; DisplayPath = GetDisplayName(OriginalPath, FullPath); // Flush any cached information about the directory. Invalidate(); } [System.Security.SecuritySafeCritical] public override void Delete() { FileSystem.Current.RemoveDirectory(FullPath, false); } [System.Security.SecuritySafeCritical] public void Delete(bool recursive) { FileSystem.Current.RemoveDirectory(FullPath, recursive); } // Returns the fully qualified path public override String ToString() { return DisplayPath; } private static String GetDisplayName(String originalPath, String fullPath) { Debug.Assert(originalPath != null); Debug.Assert(fullPath != null); String displayName = ""; // Special case "<DriveLetter>:" to point to "<CurrentDirectory>" instead if ((originalPath.Length == 2) && (originalPath[1] == ':')) { displayName = "."; } else { displayName = GetDirName(fullPath); } return displayName; } private static String GetDirName(String fullPath) { Debug.Assert(fullPath != null); String dirName = null; if (fullPath.Length > 3) { String s = fullPath; if (fullPath[fullPath.Length - 1] == Path.DirectorySeparatorChar) { s = fullPath.Substring(0, fullPath.Length - 1); } dirName = Path.GetFileName(s); } else { dirName = fullPath; // For rooted paths, like "c:\" } return dirName; } } }
using System; using System.Collections.Generic; using Shouldly; using Xunit; namespace AutoMapper.UnitTests.CustomMapping { public class NullableConverter : AutoMapperSpecBase { public enum GreekLetters { Alpha = 11, Beta = 12, Gamma = 13 } protected override MapperConfiguration CreateConfiguration() => new(c => { c.CreateMap<int?, GreekLetters>().ConvertUsing(n => n == null ? GreekLetters.Beta : GreekLetters.Gamma); }); [Fact] public void Should_map_nullable() { Mapper.Map<int?, GreekLetters>(null).ShouldBe(GreekLetters.Beta); Mapper.Map<int?, GreekLetters>(42).ShouldBe(GreekLetters.Gamma); } } public class MissingConverter : AutoMapperSpecBase { protected override MapperConfiguration CreateConfiguration() => new(c => { c.ConstructServicesUsing(t => null); c.CreateMap<int, int>().ConvertUsing<ITypeConverter<int, int>>(); }); [Fact] public void Should_report_the_missing_converter() { new Action(()=>Mapper.Map<int, int>(0)) .ShouldThrowException<AutoMapperMappingException>(e=>e.Message.ShouldBe("Cannot create an instance of type AutoMapper.ITypeConverter`2[System.Int32,System.Int32]")); } } public class DecimalAndNullableDecimal : AutoMapperSpecBase { Destination _destination; class Source { public decimal Value1 { get; set; } public decimal? Value2 { get; set; } public decimal? Value3 { get; set; } } class Destination { public decimal? Value1 { get; set; } public decimal Value2 { get; set; } public decimal? Value3 { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>(); cfg.CreateMap<decimal?, decimal>().ConvertUsing(source => source ?? decimal.MaxValue); cfg.CreateMap<decimal, decimal?>().ConvertUsing(source => source == decimal.MaxValue ? new decimal?() : source); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { Value1 = decimal.MaxValue }); } [Fact] public void Should_treat_max_value_as_null() { _destination.Value1.ShouldBeNull(); _destination.Value2.ShouldBe(decimal.MaxValue); _destination.Value3.ShouldBeNull(); } } public class When_converting_to_string : AutoMapperSpecBase { Destination _destination; class Source { public Id TheId { get; set; } } class Destination { public string TheId { get; set; } } interface IId { string Serialize(); } class Id : IId { public string Prefix { get; set; } public string Value { get; set; } public string Serialize() { return Prefix + "_" + Value; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>(); cfg.CreateMap<IId, string>().ConvertUsing(id => id.Serialize()); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { TheId = new Id { Prefix = "p", Value = "v" } }); } [Fact] public void Should_use_the_type_converter() { _destination.TheId.ShouldBe("p_v"); } } public class When_specifying_type_converters_for_object_mapper_types : AutoMapperSpecBase { Destination _destination; class Source { public IDictionary<int, int> Values { get; set; } } class Destination { public IDictionary<int, int> Values { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof(IDictionary<,>), typeof(IDictionary<,>)).ConvertUsing(typeof(DictionaryConverter<,>)); cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { _destination = Mapper.Map<Destination>(new Source { Values = new Dictionary<int, int>() }); } [Fact] public void Should_override_the_built_in_mapper() { _destination.Values.ShouldBeSameAs(DictionaryConverter<int, int>.Instance); } private class DictionaryConverter<TKey, TValue> : ITypeConverter<IDictionary<TKey, TValue>, IDictionary<TKey, TValue>> { public static readonly IDictionary<TKey, TValue> Instance = new Dictionary<TKey, TValue>(); public IDictionary<TKey, TValue> Convert(IDictionary<TKey, TValue> source, IDictionary<TKey, TValue> destination, ResolutionContext context) { return Instance; } } } public class When_specifying_type_converters : AutoMapperSpecBase { private Destination _result; public class Source { public string Value1 { get; set; } public string Value2 { get; set; } public string Value3 { get; set; } } public class Destination { public int Value1 { get; set; } public DateTime Value2 { get; set; } public Type Value3 { get; set; } } public class DateTimeTypeConverter : ITypeConverter<string, DateTime> { public DateTime Convert(string source, DateTime destination, ResolutionContext context) { return System.Convert.ToDateTime(source); } } public class TypeTypeConverter : ITypeConverter<string, Type> { public Type Convert(string source, Type destination, ResolutionContext context) { Type type = typeof(TypeTypeConverter).Assembly.GetType(source); return type; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<string, int>().ConvertUsing((string arg) => Convert.ToInt32(arg)); cfg.CreateMap<string, DateTime>().ConvertUsing(new DateTimeTypeConverter()); cfg.CreateMap<string, Type>().ConvertUsing<TypeTypeConverter>(); cfg.CreateMap<Source, Destination>(); }); protected override void Because_of() { var source = new Source { Value1 = "5", Value2 = "01/01/2000", Value3 = "AutoMapper.UnitTests.CustomMapping.When_specifying_type_converters+Destination" }; _result = Mapper.Map<Source, Destination>(source); } [Fact] public void Should_convert_type_using_expression() { _result.Value1.ShouldBe(5); } [Fact] public void Should_convert_type_using_instance() { _result.Value2.ShouldBe(new DateTime(2000, 1, 1)); } [Fact] public void Should_convert_type_using_Func_that_returns_instance() { _result.Value3.ShouldBe(typeof(Destination)); } } public class When_specifying_type_converters_on_types_with_incompatible_members : AutoMapperSpecBase { private ParentDestination _result; public class Source { public string Foo { get; set; } } public class Destination { public int Type { get; set; } } public class ParentSource { public Source Value { get; set; } } public class ParentDestination { public Destination Value { get; set; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>().ConvertUsing(arg => new Destination {Type = Convert.ToInt32(arg.Foo)}); cfg.CreateMap<ParentSource, ParentDestination>(); }); protected override void Because_of() { var source = new ParentSource { Value = new Source { Foo = "5", } }; _result = Mapper.Map<ParentSource, ParentDestination>(source); } [Fact] public void Should_convert_type_using_expression() { _result.Value.Type.ShouldBe(5); } } public class When_specifying_a_type_converter_for_a_non_generic_configuration : NonValidatingSpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomConverter : ITypeConverter<Source, Destination> { public Destination Convert(Source source, Destination destination, ResolutionContext context) { return new Destination { OtherValue = source.Value + 10 }; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap<Source, Destination>().ConvertUsing<CustomConverter>(); }); protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_converter_specified() { _result.OtherValue.ShouldBe(15); } } public class When_specifying_a_non_generic_type_converter_for_a_non_generic_configuration : AutoMapperSpecBase { private Destination _result; public class Source { public int Value { get; set; } } public class Destination { public int OtherValue { get; set; } } public class CustomConverter : ITypeConverter<Source, Destination> { public Destination Convert(Source source, Destination destination, ResolutionContext context) { return new Destination { OtherValue = source.Value + 10 }; } } protected override MapperConfiguration CreateConfiguration() => new(cfg => { cfg.CreateMap(typeof (Source), typeof (Destination)).ConvertUsing(typeof (CustomConverter)); }); protected override void Because_of() { _result = Mapper.Map<Source, Destination>(new Source {Value = 5}); } [Fact] public void Should_use_converter_specified() { _result.OtherValue.ShouldBe(15); } } }
// 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. using UnityEngine; using System; using System.Collections; using System.ComponentModel; using Gvr.Internal; /// Main entry point for Standalone headset APIs. /// /// To use this API, use the GvrHeadset prefab. There can be only one /// such prefab in a scene. /// /// This is a singleton object. public class GvrHeadset : MonoBehaviour { private static GvrHeadset instance; private IHeadsetProvider headsetProvider; private HeadsetState headsetState; private IEnumerator standaloneUpdate; private WaitForEndOfFrame waitForEndOfFrame = new WaitForEndOfFrame(); // Delegates for GVR events. private OnSafetyRegionEvent safetyRegionDelegate; private OnRecenterEvent recenterDelegate; // Delegate definitions. /// This delegate is called when the headset crosses the safety region boundary. public delegate void OnSafetyRegionEvent(bool enter); /// This delegate is called after the headset is recentered. /// |recenterType| indicates the reason recentering occurred. /// |recenterFlags| are flags related to recentering. See |GvrRecenterFlags|. /// |recenteredPosition| is the positional offset from the session start pose. /// |recenteredOrientation| is the rotational offset from the session start pose. public delegate void OnRecenterEvent(GvrRecenterEventType recenterType, GvrRecenterFlags recenterFlags, Vector3 recenteredPosition, Quaternion recenteredOrientation); #region DELEGATE_HANDLERS public static event OnSafetyRegionEvent OnSafetyRegionChange { add { if (instance != null) { instance.safetyRegionDelegate += value; } } remove { if (instance != null) { instance.safetyRegionDelegate -= value; } } } public static event OnRecenterEvent OnRecenter { add { if (instance != null) { instance.recenterDelegate += value; } } remove { if (instance != null) { instance.recenterDelegate -= value; } } } #endregion // DELEGATE_HANDLERS #region GVR_STANDALONE_PROPERTIES /// Returns |true| if the current headset supports positionally tracked, 6DOF head poses. /// Returns |false| if only rotation-based head poses are supported. public static bool SupportsPositionalTracking { get { if (instance == null) { return false; } return instance.headsetProvider.SupportsPositionalTracking; } } /// If a floor is found, populates floorHeight with the detected height. /// Otherwise, leaves the value unchanged. /// Returns true if value retrieval was successful, false otherwise (depends on tracking state). public static bool TryGetFloorHeight(ref float floorHeight) { if (instance == null) { return false; } return instance.headsetProvider.TryGetFloorHeight(ref floorHeight); } /// If the last recentering transform is available, populates position and rotation with that /// transform. /// Returns true if value retrieval was successful, false otherwise (unlikely). public static bool TryGetRecenterTransform(ref Vector3 position, ref Quaternion rotation) { if (instance == null) { return false; } return instance.headsetProvider.TryGetRecenterTransform(ref position, ref rotation); } /// Populates safetyType with the available safety region feature on the /// currently-running device. /// Returns true if value retrieval was successful, false otherwise (unlikely). public static bool TryGetSafetyRegionType(ref GvrSafetyRegionType safetyType) { if (instance == null) { return false; } return instance.headsetProvider.TryGetSafetyRegionType(ref safetyType); } /// If the safety region is of type GvrSafetyRegionType.Cylinder, populates innerRadius with the /// inner radius size (where fog starts appearing) of the safety cylinder in meters. /// Assumes the safety region type has been previously checked by the caller. /// Returns true if value retrieval was successful, false otherwise (if region type is /// GvrSafetyRegionType.Invalid). public static bool TryGetSafetyCylinderInnerRadius(ref float innerRadius) { if (instance == null) { return false; } return instance.headsetProvider.TryGetSafetyCylinderInnerRadius(ref innerRadius); } /// If the safety region is of type GvrSafetyRegionType.Cylinder, populates outerRadius with the /// outer radius size (where fog is 100% opaque) of the safety cylinder in meters. /// Assumes the safety region type has been previously checked by the caller. /// Returns true if value retrieval was successful, false otherwise (if region type is /// GvrSafetyRegionType.Invalid). public static bool TryGetSafetyCylinderOuterRadius(ref float outerRadius) { if (instance == null) { return false; } return instance.headsetProvider.TryGetSafetyCylinderOuterRadius(ref outerRadius); } #endregion // GVR_STANDALONE_PROPERTIES private GvrHeadset() { headsetState.Initialize(); } void Awake() { if (instance != null) { Debug.LogError("More than one GvrHeadset instance was found in your scene. " + "Ensure that there is only one GvrHeadset."); this.enabled = false; return; } instance = this; if (headsetProvider == null) { headsetProvider = HeadsetProviderFactory.CreateProvider(); } } void OnEnable() { if (!SupportsPositionalTracking) { return; } standaloneUpdate = EndOfFrame(); StartCoroutine(standaloneUpdate); } void OnDisable() { if (!SupportsPositionalTracking) { return; } StopCoroutine(standaloneUpdate); } void OnDestroy() { if (!SupportsPositionalTracking) { return; } instance = null; } private void UpdateStandalone() { // Events are stored in a queue, so poll until we get Invalid. headsetProvider.PollEventState(ref headsetState); while (headsetState.eventType != GvrEventType.Invalid) { switch (headsetState.eventType) { case GvrEventType.Recenter: if (recenterDelegate != null) { recenterDelegate(headsetState.recenterEventType, (GvrRecenterFlags) headsetState.recenterEventFlags, headsetState.recenteredPosition, headsetState.recenteredRotation); } break; case GvrEventType.SafetyRegionEnter: if (safetyRegionDelegate != null) { safetyRegionDelegate(true); } break; case GvrEventType.SafetyRegionExit: if (safetyRegionDelegate != null) { safetyRegionDelegate(false); } break; case GvrEventType.Invalid: throw new InvalidEnumArgumentException("Invalid headset event: " + headsetState.eventType); default: // Fallthrough, should never get here. break; } headsetProvider.PollEventState(ref headsetState); } } IEnumerator EndOfFrame() { while (true) { // This must be done at the end of the frame to ensure that all GameObjects had a chance // to read transient state (e.g. events, etc) for the current frame before it gets reset. yield return waitForEndOfFrame; UpdateStandalone(); } } }
// 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 System { using System; using System.Reflection; using System.Reflection.Emit; using System.Runtime; using System.Runtime.ConstrainedExecution; using System.Diagnostics; using System.Runtime.Serialization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Runtime.Versioning; using System.Text; using System.Globalization; using System.Security; using Microsoft.Win32.SafeHandles; using System.Diagnostics.Contracts; using StackCrawlMark = System.Threading.StackCrawlMark; [Serializable] public unsafe struct RuntimeTypeHandle : ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. internal RuntimeTypeHandle GetNativeHandle() { // Create local copy to avoid a race condition RuntimeType type = m_type; if (type == null) throw new ArgumentNullException(null, SR.Arg_InvalidHandle); return new RuntimeTypeHandle(type); } // Returns type for interop with EE. The type is guaranteed to be non-null. internal RuntimeType GetTypeChecked() { // Create local copy to avoid a race condition RuntimeType type = m_type; if (type == null) throw new ArgumentNullException(null, SR.Arg_InvalidHandle); return type; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsInstanceOfType(RuntimeType type, Object o); internal unsafe static Type GetTypeHelper(Type typeStart, Type[] genericArgs, IntPtr pModifiers, int cModifiers) { Type type = typeStart; if (genericArgs != null) { type = type.MakeGenericType(genericArgs); } if (cModifiers > 0) { int* arModifiers = (int*)pModifiers.ToPointer(); for (int i = 0; i < cModifiers; i++) { if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.Ptr) type = type.MakePointerType(); else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.ByRef) type = type.MakeByRefType(); else if ((CorElementType)Marshal.ReadInt32((IntPtr)arModifiers, i * sizeof(int)) == CorElementType.SzArray) type = type.MakeArrayType(); else type = type.MakeArrayType(Marshal.ReadInt32((IntPtr)arModifiers, ++i * sizeof(int))); } } return type; } public static bool operator ==(RuntimeTypeHandle left, object right) { return left.Equals(right); } public static bool operator ==(object left, RuntimeTypeHandle right) { return right.Equals(left); } public static bool operator !=(RuntimeTypeHandle left, object right) { return !left.Equals(right); } public static bool operator !=(object left, RuntimeTypeHandle right) { return !right.Equals(left); } // This is the RuntimeType for the type private RuntimeType m_type; public override int GetHashCode() { return m_type != null ? m_type.GetHashCode() : 0; } public override bool Equals(object obj) { if (!(obj is RuntimeTypeHandle)) return false; RuntimeTypeHandle handle = (RuntimeTypeHandle)obj; return handle.m_type == m_type; } public bool Equals(RuntimeTypeHandle handle) { return handle.m_type == m_type; } public IntPtr Value { get { return m_type != null ? m_type.m_handle : IntPtr.Zero; } } [MethodImpl(MethodImplOptions.InternalCall)] internal static extern IntPtr GetValueInternal(RuntimeTypeHandle handle); internal RuntimeTypeHandle(RuntimeType type) { m_type = type; } internal static bool IsTypeDefinition(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); if (!((corElemType >= CorElementType.Void && corElemType < CorElementType.Ptr) || corElemType == CorElementType.ValueType || corElemType == CorElementType.Class || corElemType == CorElementType.TypedByRef || corElemType == CorElementType.I || corElemType == CorElementType.U || corElemType == CorElementType.Object)) return false; if (HasInstantiation(type) && !IsGenericTypeDefinition(type)) return false; return true; } internal static bool IsPrimitive(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); return (corElemType >= CorElementType.Boolean && corElemType <= CorElementType.R8) || corElemType == CorElementType.I || corElemType == CorElementType.U; } internal static bool IsByRef(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); return (corElemType == CorElementType.ByRef); } internal static bool IsPointer(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); return (corElemType == CorElementType.Ptr); } internal static bool IsArray(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); return (corElemType == CorElementType.Array || corElemType == CorElementType.SzArray); } internal static bool IsSZArray(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); return (corElemType == CorElementType.SzArray); } internal static bool HasElementType(RuntimeType type) { CorElementType corElemType = GetCorElementType(type); return ((corElemType == CorElementType.Array || corElemType == CorElementType.SzArray) // IsArray || (corElemType == CorElementType.Ptr) // IsPointer || (corElemType == CorElementType.ByRef)); // IsByRef } internal static IntPtr[] CopyRuntimeTypeHandles(RuntimeTypeHandle[] inHandles, out int length) { if (inHandles == null || inHandles.Length == 0) { length = 0; return null; } IntPtr[] outHandles = new IntPtr[inHandles.Length]; for (int i = 0; i < inHandles.Length; i++) { outHandles[i] = inHandles[i].Value; } length = outHandles.Length; return outHandles; } internal static IntPtr[] CopyRuntimeTypeHandles(Type[] inHandles, out int length) { if (inHandles == null || inHandles.Length == 0) { length = 0; return null; } IntPtr[] outHandles = new IntPtr[inHandles.Length]; for (int i = 0; i < inHandles.Length; i++) { outHandles[i] = inHandles[i].GetTypeHandleInternal().Value; } length = outHandles.Length; return outHandles; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object CreateInstance(RuntimeType type, bool publicOnly, ref bool canBeCached, ref RuntimeMethodHandleInternal ctor); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object Allocate(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object CreateInstanceForAnotherGenericParameter(RuntimeType type, RuntimeType genericParameter); internal RuntimeType GetRuntimeType() { return m_type; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static CorElementType GetCorElementType(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeAssembly GetAssembly(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeModule GetModule(RuntimeType type); [CLSCompliant(false)] public ModuleHandle GetModuleHandle() { return new ModuleHandle(RuntimeTypeHandle.GetModule(m_type)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeType GetBaseType(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static TypeAttributes GetAttributes(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeType GetElementType(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool CompareCanonicalHandles(RuntimeType left, RuntimeType right); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static int GetArrayRank(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static int GetToken(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeMethodHandleInternal GetMethodAt(RuntimeType type, int slot); // This is managed wrapper for MethodTable::IntroducedMethodIterator internal struct IntroducedMethodEnumerator { private bool _firstCall; private RuntimeMethodHandleInternal _handle; internal IntroducedMethodEnumerator(RuntimeType type) { _handle = RuntimeTypeHandle.GetFirstIntroducedMethod(type); _firstCall = true; } public bool MoveNext() { if (_firstCall) { _firstCall = false; } else if (_handle.Value != IntPtr.Zero) { RuntimeTypeHandle.GetNextIntroducedMethod(ref _handle); } return !(_handle.Value == IntPtr.Zero); } public RuntimeMethodHandleInternal Current { get { return _handle; } } // Glue to make this work nicely with C# foreach statement public IntroducedMethodEnumerator GetEnumerator() { return this; } } internal static IntroducedMethodEnumerator GetIntroducedMethods(RuntimeType type) { return new IntroducedMethodEnumerator(type); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern RuntimeMethodHandleInternal GetFirstIntroducedMethod(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void GetNextIntroducedMethod(ref RuntimeMethodHandleInternal method); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool GetFields(RuntimeType type, IntPtr* result, int* count); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static Type[] GetInterfaces(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetConstraints(RuntimeTypeHandle handle, ObjectHandleOnStack types); internal Type[] GetConstraints() { Type[] types = null; GetConstraints(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types)); return types; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static IntPtr GetGCHandle(RuntimeTypeHandle handle, GCHandleType type); internal IntPtr GetGCHandle(GCHandleType type) { return GetGCHandle(GetNativeHandle(), type); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static int GetNumVirtuals(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void VerifyInterfaceIsImplemented(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle); internal void VerifyInterfaceIsImplemented(RuntimeTypeHandle interfaceHandle) { VerifyInterfaceIsImplemented(GetNativeHandle(), interfaceHandle.GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle handle, RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle); internal int GetInterfaceMethodImplementationSlot(RuntimeTypeHandle interfaceHandle, RuntimeMethodHandleInternal interfaceMethodHandle) { return GetInterfaceMethodImplementationSlot(GetNativeHandle(), interfaceHandle.GetNativeHandle(), interfaceMethodHandle); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsComObject(RuntimeType type, bool isGenericCOM); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsInterface(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private extern static bool _IsVisible(RuntimeTypeHandle typeHandle); internal static bool IsVisible(RuntimeType type) { return _IsVisible(new RuntimeTypeHandle(type)); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsSecurityCritical(RuntimeTypeHandle typeHandle); internal bool IsSecurityCritical() { return IsSecurityCritical(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsSecuritySafeCritical(RuntimeTypeHandle typeHandle); internal bool IsSecuritySafeCritical() { return IsSecuritySafeCritical(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsSecurityTransparent(RuntimeTypeHandle typeHandle); internal bool IsSecurityTransparent() { return IsSecurityTransparent(GetNativeHandle()); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsValueType(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void ConstructName(RuntimeTypeHandle handle, TypeNameFormatFlags formatFlags, StringHandleOnStack retString); internal string ConstructName(TypeNameFormatFlags formatFlags) { string name = null; ConstructName(GetNativeHandle(), formatFlags, JitHelpers.GetStringHandleOnStack(ref name)); return name; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static void* _GetUtf8Name(RuntimeType type); internal static Utf8String GetUtf8Name(RuntimeType type) { return new Utf8String(_GetUtf8Name(type)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool CanCastTo(RuntimeType type, RuntimeType target); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeType GetDeclaringType(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static IRuntimeMethodInfo GetDeclaringMethod(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetDefaultConstructor(RuntimeTypeHandle handle, ObjectHandleOnStack method); internal IRuntimeMethodInfo GetDefaultConstructor() { IRuntimeMethodInfo ctor = null; GetDefaultConstructor(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref ctor)); return ctor; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, bool loadTypeFromPartialName, ObjectHandleOnStack type, ObjectHandleOnStack keepalive); // Wrapper function to reduce the need for ifdefs. internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, bool loadTypeFromPartialName) { return GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, ref stackMark, IntPtr.Zero, loadTypeFromPartialName); } internal static RuntimeType GetTypeByName(string name, bool throwOnError, bool ignoreCase, bool reflectionOnly, ref StackCrawlMark stackMark, IntPtr pPrivHostBinder, bool loadTypeFromPartialName) { if (name == null || name.Length == 0) { if (throwOnError) throw new TypeLoadException(SR.Arg_TypeLoadNullStr); return null; } RuntimeType type = null; Object keepAlive = null; GetTypeByName(name, throwOnError, ignoreCase, reflectionOnly, JitHelpers.GetStackCrawlMarkHandle(ref stackMark), pPrivHostBinder, loadTypeFromPartialName, JitHelpers.GetObjectHandleOnStack(ref type), JitHelpers.GetObjectHandleOnStack(ref keepAlive)); GC.KeepAlive(keepAlive); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetTypeByNameUsingCARules(string name, RuntimeModule scope, ObjectHandleOnStack type); internal static RuntimeType GetTypeByNameUsingCARules(string name, RuntimeModule scope) { if (name == null || name.Length == 0) throw new ArgumentException(null, nameof(name)); Contract.EndContractBlock(); RuntimeType type = null; GetTypeByNameUsingCARules(name, scope.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static void GetInstantiation(RuntimeTypeHandle type, ObjectHandleOnStack types, bool fAsRuntimeTypeArray); internal RuntimeType[] GetInstantiationInternal() { RuntimeType[] types = null; GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), true); return types; } internal Type[] GetInstantiationPublic() { Type[] types = null; GetInstantiation(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref types), false); return types; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void Instantiate(RuntimeTypeHandle handle, IntPtr* pInst, int numGenericArgs, ObjectHandleOnStack type); internal RuntimeType Instantiate(Type[] inst) { // defensive copy to be sure array is not mutated from the outside during processing int instCount; IntPtr[] instHandles = CopyRuntimeTypeHandles(inst, out instCount); fixed (IntPtr* pInst = instHandles) { RuntimeType type = null; Instantiate(GetNativeHandle(), pInst, instCount, JitHelpers.GetObjectHandleOnStack(ref type)); GC.KeepAlive(inst); return type; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void MakeArray(RuntimeTypeHandle handle, int rank, ObjectHandleOnStack type); internal RuntimeType MakeArray(int rank) { RuntimeType type = null; MakeArray(GetNativeHandle(), rank, JitHelpers.GetObjectHandleOnStack(ref type)); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void MakeSZArray(RuntimeTypeHandle handle, ObjectHandleOnStack type); internal RuntimeType MakeSZArray() { RuntimeType type = null; MakeSZArray(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void MakeByRef(RuntimeTypeHandle handle, ObjectHandleOnStack type); internal RuntimeType MakeByRef() { RuntimeType type = null; MakeByRef(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void MakePointer(RuntimeTypeHandle handle, ObjectHandleOnStack type); internal RuntimeType MakePointer() { RuntimeType type = null; MakePointer(GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static bool IsCollectible(RuntimeTypeHandle handle); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool HasInstantiation(RuntimeType type); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetGenericTypeDefinition(RuntimeTypeHandle type, ObjectHandleOnStack retType); internal static RuntimeType GetGenericTypeDefinition(RuntimeType type) { RuntimeType retType = type; if (HasInstantiation(retType) && !IsGenericTypeDefinition(retType)) GetGenericTypeDefinition(retType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref retType)); return retType; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsGenericTypeDefinition(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsGenericVariable(RuntimeType type); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static int GetGenericVariableIndex(RuntimeType type); internal int GetGenericVariableIndex() { RuntimeType type = GetTypeChecked(); if (!IsGenericVariable(type)) throw new InvalidOperationException(SR.Arg_NotGenericParameter); return GetGenericVariableIndex(type); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool ContainsGenericVariables(RuntimeType handle); internal bool ContainsGenericVariables() { return ContainsGenericVariables(GetTypeChecked()); } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static bool SatisfiesConstraints(RuntimeType paramType, IntPtr* pTypeContext, int typeContextLength, IntPtr* pMethodContext, int methodContextLength, RuntimeType toType); internal static bool SatisfiesConstraints(RuntimeType paramType, RuntimeType[] typeContext, RuntimeType[] methodContext, RuntimeType toType) { int typeContextLength; int methodContextLength; IntPtr[] typeContextHandles = CopyRuntimeTypeHandles(typeContext, out typeContextLength); IntPtr[] methodContextHandles = CopyRuntimeTypeHandles(methodContext, out methodContextLength); fixed (IntPtr* pTypeContextHandles = typeContextHandles, pMethodContextHandles = methodContextHandles) { bool result = SatisfiesConstraints(paramType, pTypeContextHandles, typeContextLength, pMethodContextHandles, methodContextLength, toType); GC.KeepAlive(typeContext); GC.KeepAlive(methodContext); return result; } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static IntPtr _GetMetadataImport(RuntimeType type); internal static MetadataImport GetMetadataImport(RuntimeType type) { return new MetadataImport(_GetMetadataImport(type), type); } private RuntimeTypeHandle(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); RuntimeType m = (RuntimeType)info.GetValue("TypeObj", typeof(RuntimeType)); m_type = m; if (m_type == null) throw new SerializationException(SR.Serialization_InsufficientState); } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); if (m_type == null) throw new SerializationException(SR.Serialization_InvalidFieldState); info.AddValue("TypeObj", m_type, typeof(RuntimeType)); } } // This type is used to remove the expense of having a managed reference object that is dynamically // created when we can prove that we don't need that object. Use of this type requires code to ensure // that the underlying native resource is not freed. // Cases in which this may be used: // 1. When native code calls managed code passing one of these as a parameter // 2. When managed code acquires one of these from an IRuntimeMethodInfo, and ensure that the IRuntimeMethodInfo is preserved // across the lifetime of the RuntimeMethodHandleInternal instance // 3. When another object is used to keep the RuntimeMethodHandleInternal alive. See delegates, CreateInstance cache, Signature structure // When in doubt, do not use. internal struct RuntimeMethodHandleInternal { internal static RuntimeMethodHandleInternal EmptyHandle { get { return new RuntimeMethodHandleInternal(); } } internal bool IsNullHandle() { return m_handle.IsNull(); } internal IntPtr Value { get { return m_handle; } } internal RuntimeMethodHandleInternal(IntPtr value) { m_handle = value; } internal IntPtr m_handle; } internal class RuntimeMethodInfoStub : IRuntimeMethodInfo { public RuntimeMethodInfoStub(RuntimeMethodHandleInternal methodHandleValue, object keepalive) { m_keepalive = keepalive; m_value = methodHandleValue; } public RuntimeMethodInfoStub(IntPtr methodHandleValue, object keepalive) { m_keepalive = keepalive; m_value = new RuntimeMethodHandleInternal(methodHandleValue); } private object m_keepalive; // These unused variables are used to ensure that this class has the same layout as RuntimeMethodInfo #pragma warning disable 169 private object m_a; private object m_b; private object m_c; private object m_d; private object m_e; private object m_f; private object m_g; #pragma warning restore 169 public RuntimeMethodHandleInternal m_value; RuntimeMethodHandleInternal IRuntimeMethodInfo.Value { get { return m_value; } } } internal interface IRuntimeMethodInfo { RuntimeMethodHandleInternal Value { get; } } [Serializable] public unsafe struct RuntimeMethodHandle : ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. internal static IRuntimeMethodInfo EnsureNonNullMethodInfo(IRuntimeMethodInfo method) { if (method == null) throw new ArgumentNullException(null, SR.Arg_InvalidHandle); return method; } private IRuntimeMethodInfo m_value; internal RuntimeMethodHandle(IRuntimeMethodInfo method) { m_value = method; } internal IRuntimeMethodInfo GetMethodInfo() { return m_value; } // Used by EE private static IntPtr GetValueInternal(RuntimeMethodHandle rmh) { return rmh.Value; } // ISerializable interface private RuntimeMethodHandle(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); MethodBase m = (MethodBase)info.GetValue("MethodObj", typeof(MethodBase)); m_value = m.MethodHandle.m_value; if (m_value == null) throw new SerializationException(SR.Serialization_InsufficientState); } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); if (m_value == null) throw new SerializationException(SR.Serialization_InvalidFieldState); // This is either a RuntimeMethodInfo or a RuntimeConstructorInfo MethodBase methodInfo = RuntimeType.GetMethodBase(m_value); info.AddValue("MethodObj", methodInfo, typeof(MethodBase)); } public IntPtr Value { get { return m_value != null ? m_value.Value.Value : IntPtr.Zero; } } public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(Value); } public override bool Equals(object obj) { if (!(obj is RuntimeMethodHandle)) return false; RuntimeMethodHandle handle = (RuntimeMethodHandle)obj; return handle.Value == Value; } public static bool operator ==(RuntimeMethodHandle left, RuntimeMethodHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeMethodHandle left, RuntimeMethodHandle right) { return !left.Equals(right); } public bool Equals(RuntimeMethodHandle handle) { return handle.Value == Value; } [Pure] internal bool IsNullHandle() { return m_value == null; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static IntPtr GetFunctionPointer(RuntimeMethodHandleInternal handle); public IntPtr GetFunctionPointer() { IntPtr ptr = GetFunctionPointer(EnsureNonNullMethodInfo(m_value).Value); GC.KeepAlive(m_value); return ptr; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal unsafe extern static void CheckLinktimeDemands(IRuntimeMethodInfo method, RuntimeModule module, bool isDecoratedTargetSecurityTransparent); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static bool IsCAVisibleFromDecoratedType( RuntimeTypeHandle attrTypeHandle, IRuntimeMethodInfo attrCtor, RuntimeTypeHandle sourceTypeHandle, RuntimeModule sourceModule); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern IRuntimeMethodInfo _GetCurrentMethod(ref StackCrawlMark stackMark); internal static IRuntimeMethodInfo GetCurrentMethod(ref StackCrawlMark stackMark) { return _GetCurrentMethod(ref stackMark); } [Pure] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern MethodAttributes GetAttributes(RuntimeMethodHandleInternal method); internal static MethodAttributes GetAttributes(IRuntimeMethodInfo method) { MethodAttributes retVal = RuntimeMethodHandle.GetAttributes(method.Value); GC.KeepAlive(method); return retVal; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern MethodImplAttributes GetImplAttributes(IRuntimeMethodInfo method); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format, StringHandleOnStack retString); internal static string ConstructInstantiation(IRuntimeMethodInfo method, TypeNameFormatFlags format) { string name = null; ConstructInstantiation(EnsureNonNullMethodInfo(method), format, JitHelpers.GetStringHandleOnStack(ref name)); return name; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeType GetDeclaringType(RuntimeMethodHandleInternal method); internal static RuntimeType GetDeclaringType(IRuntimeMethodInfo method) { RuntimeType type = RuntimeMethodHandle.GetDeclaringType(method.Value); GC.KeepAlive(method); return type; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static int GetSlot(RuntimeMethodHandleInternal method); internal static int GetSlot(IRuntimeMethodInfo method) { Contract.Requires(method != null); int slot = RuntimeMethodHandle.GetSlot(method.Value); GC.KeepAlive(method); return slot; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static int GetMethodDef(IRuntimeMethodInfo method); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static string GetName(RuntimeMethodHandleInternal method); internal static string GetName(IRuntimeMethodInfo method) { string name = RuntimeMethodHandle.GetName(method.Value); GC.KeepAlive(method); return name; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static void* _GetUtf8Name(RuntimeMethodHandleInternal method); internal static Utf8String GetUtf8Name(RuntimeMethodHandleInternal method) { return new Utf8String(_GetUtf8Name(method)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool MatchesNameHash(RuntimeMethodHandleInternal method, uint hash); [DebuggerStepThroughAttribute] [Diagnostics.DebuggerHidden] [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static object InvokeMethod(object target, object[] arguments, Signature sig, bool constructor); #region Private Invocation Helpers internal static INVOCATION_FLAGS GetSecurityFlags(IRuntimeMethodInfo handle) { return (INVOCATION_FLAGS)RuntimeMethodHandle.GetSpecialSecurityFlags(handle); } [MethodImplAttribute(MethodImplOptions.InternalCall)] static extern internal uint GetSpecialSecurityFlags(IRuntimeMethodInfo method); #endregion [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetMethodInstantiation(RuntimeMethodHandleInternal method, ObjectHandleOnStack types, bool fAsRuntimeTypeArray); internal static RuntimeType[] GetMethodInstantiationInternal(IRuntimeMethodInfo method) { RuntimeType[] types = null; GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), true); GC.KeepAlive(method); return types; } internal static RuntimeType[] GetMethodInstantiationInternal(RuntimeMethodHandleInternal method) { RuntimeType[] types = null; GetMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref types), true); return types; } internal static Type[] GetMethodInstantiationPublic(IRuntimeMethodInfo method) { RuntimeType[] types = null; GetMethodInstantiation(EnsureNonNullMethodInfo(method).Value, JitHelpers.GetObjectHandleOnStack(ref types), false); GC.KeepAlive(method); return types; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool HasMethodInstantiation(RuntimeMethodHandleInternal method); internal static bool HasMethodInstantiation(IRuntimeMethodInfo method) { bool fRet = RuntimeMethodHandle.HasMethodInstantiation(method.Value); GC.KeepAlive(method); return fRet; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeMethodHandleInternal GetStubIfNeeded(RuntimeMethodHandleInternal method, RuntimeType declaringType, RuntimeType[] methodInstantiation); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static RuntimeMethodHandleInternal GetMethodFromCanonical(RuntimeMethodHandleInternal method, RuntimeType declaringType); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsGenericMethodDefinition(RuntimeMethodHandleInternal method); internal static bool IsGenericMethodDefinition(IRuntimeMethodInfo method) { bool fRet = RuntimeMethodHandle.IsGenericMethodDefinition(method.Value); GC.KeepAlive(method); return fRet; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsTypicalMethodDefinition(IRuntimeMethodInfo method); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetTypicalMethodDefinition(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod); internal static IRuntimeMethodInfo GetTypicalMethodDefinition(IRuntimeMethodInfo method) { if (!IsTypicalMethodDefinition(method)) GetTypicalMethodDefinition(method, JitHelpers.GetObjectHandleOnStack(ref method)); return method; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void StripMethodInstantiation(IRuntimeMethodInfo method, ObjectHandleOnStack outMethod); internal static IRuntimeMethodInfo StripMethodInstantiation(IRuntimeMethodInfo method) { IRuntimeMethodInfo strippedMethod = method; StripMethodInstantiation(method, JitHelpers.GetObjectHandleOnStack(ref strippedMethod)); return strippedMethod; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static bool IsDynamicMethod(RuntimeMethodHandleInternal method); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static void Destroy(RuntimeMethodHandleInternal method); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static Resolver GetResolver(RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static MethodBody GetMethodBody(IRuntimeMethodInfo method, RuntimeType declaringType); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static bool IsConstructor(RuntimeMethodHandleInternal method); [MethodImpl(MethodImplOptions.InternalCall)] internal extern static LoaderAllocator GetLoaderAllocator(RuntimeMethodHandleInternal method); } // This type is used to remove the expense of having a managed reference object that is dynamically // created when we can prove that we don't need that object. Use of this type requires code to ensure // that the underlying native resource is not freed. // Cases in which this may be used: // 1. When native code calls managed code passing one of these as a parameter // 2. When managed code acquires one of these from an RtFieldInfo, and ensure that the RtFieldInfo is preserved // across the lifetime of the RuntimeFieldHandleInternal instance // 3. When another object is used to keep the RuntimeFieldHandleInternal alive. // When in doubt, do not use. internal struct RuntimeFieldHandleInternal { internal bool IsNullHandle() { return m_handle.IsNull(); } internal IntPtr Value { get { return m_handle; } } internal RuntimeFieldHandleInternal(IntPtr value) { m_handle = value; } internal IntPtr m_handle; } internal interface IRuntimeFieldInfo { RuntimeFieldHandleInternal Value { get; } } [StructLayout(LayoutKind.Sequential)] internal class RuntimeFieldInfoStub : IRuntimeFieldInfo { // These unused variables are used to ensure that this class has the same layout as RuntimeFieldInfo #pragma warning disable 169 private object m_keepalive; private object m_c; private object m_d; private int m_b; private object m_e; private RuntimeFieldHandleInternal m_fieldHandle; #pragma warning restore 169 RuntimeFieldHandleInternal IRuntimeFieldInfo.Value { get { return m_fieldHandle; } } } [Serializable] public unsafe struct RuntimeFieldHandle : ISerializable { // Returns handle for interop with EE. The handle is guaranteed to be non-null. internal RuntimeFieldHandle GetNativeHandle() { // Create local copy to avoid a race condition IRuntimeFieldInfo field = m_ptr; if (field == null) throw new ArgumentNullException(null, SR.Arg_InvalidHandle); return new RuntimeFieldHandle(field); } private IRuntimeFieldInfo m_ptr; internal RuntimeFieldHandle(IRuntimeFieldInfo fieldInfo) { m_ptr = fieldInfo; } internal IRuntimeFieldInfo GetRuntimeFieldInfo() { return m_ptr; } public IntPtr Value { get { return m_ptr != null ? m_ptr.Value.Value : IntPtr.Zero; } } internal bool IsNullHandle() { return m_ptr == null; } public override int GetHashCode() { return ValueType.GetHashCodeOfPtr(Value); } public override bool Equals(object obj) { if (!(obj is RuntimeFieldHandle)) return false; RuntimeFieldHandle handle = (RuntimeFieldHandle)obj; return handle.Value == Value; } public unsafe bool Equals(RuntimeFieldHandle handle) { return handle.Value == Value; } public static bool operator ==(RuntimeFieldHandle left, RuntimeFieldHandle right) { return left.Equals(right); } public static bool operator !=(RuntimeFieldHandle left, RuntimeFieldHandle right) { return !left.Equals(right); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern String GetName(RtFieldInfo field); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern unsafe void* _GetUtf8Name(RuntimeFieldHandleInternal field); internal static unsafe Utf8String GetUtf8Name(RuntimeFieldHandleInternal field) { return new Utf8String(_GetUtf8Name(field)); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool MatchesNameHash(RuntimeFieldHandleInternal handle, uint hash); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern FieldAttributes GetAttributes(RuntimeFieldHandleInternal field); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeType GetApproxDeclaringType(RuntimeFieldHandleInternal field); internal static RuntimeType GetApproxDeclaringType(IRuntimeFieldInfo field) { RuntimeType type = GetApproxDeclaringType(field.Value); GC.KeepAlive(field); return type; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetToken(RtFieldInfo field); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, ref bool domainInitialized); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern Object GetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, RuntimeType contextType); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SetValue(RtFieldInfo field, Object obj, Object value, RuntimeType fieldType, FieldAttributes fieldAttr, RuntimeType declaringType, ref bool domainInitialized); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void SetValueDirect(RtFieldInfo field, RuntimeType fieldType, void* pTypedRef, Object value, RuntimeType contextType); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeFieldHandleInternal GetStaticFieldForGenericType(RuntimeFieldHandleInternal field, RuntimeType declaringType); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool AcquiresContextFromThis(RuntimeFieldHandleInternal field); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsSecurityCritical(RuntimeFieldHandle fieldHandle); internal bool IsSecurityCritical() { return IsSecurityCritical(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsSecuritySafeCritical(RuntimeFieldHandle fieldHandle); internal bool IsSecuritySafeCritical() { return IsSecuritySafeCritical(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool IsSecurityTransparent(RuntimeFieldHandle fieldHandle); internal bool IsSecurityTransparent() { return IsSecurityTransparent(GetNativeHandle()); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal static extern void CheckAttributeAccess(RuntimeFieldHandle fieldHandle, RuntimeModule decoratedTarget); // ISerializable interface private RuntimeFieldHandle(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); FieldInfo f = (RuntimeFieldInfo)info.GetValue("FieldObj", typeof(RuntimeFieldInfo)); if (f == null) throw new SerializationException(SR.Serialization_InsufficientState); m_ptr = f.FieldHandle.m_ptr; if (m_ptr == null) throw new SerializationException(SR.Serialization_InsufficientState); } public void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) throw new ArgumentNullException(nameof(info)); Contract.EndContractBlock(); if (m_ptr == null) throw new SerializationException(SR.Serialization_InvalidFieldState); RuntimeFieldInfo fldInfo = (RuntimeFieldInfo)RuntimeType.GetFieldInfo(this.GetRuntimeFieldInfo()); info.AddValue("FieldObj", fldInfo, typeof(RuntimeFieldInfo)); } } public unsafe struct ModuleHandle { // Returns handle for interop with EE. The handle is guaranteed to be non-null. #region Public Static Members public static readonly ModuleHandle EmptyHandle = GetEmptyMH(); #endregion unsafe static private ModuleHandle GetEmptyMH() { return new ModuleHandle(); } #region Private Data Members private RuntimeModule m_ptr; #endregion #region Constructor internal ModuleHandle(RuntimeModule module) { m_ptr = module; } #endregion #region Internal FCalls internal RuntimeModule GetRuntimeModule() { return m_ptr; } public override int GetHashCode() { return m_ptr != null ? m_ptr.GetHashCode() : 0; } public override bool Equals(object obj) { if (!(obj is ModuleHandle)) return false; ModuleHandle handle = (ModuleHandle)obj; return handle.m_ptr == m_ptr; } public unsafe bool Equals(ModuleHandle handle) { return handle.m_ptr == m_ptr; } public static bool operator ==(ModuleHandle left, ModuleHandle right) { return left.Equals(right); } public static bool operator !=(ModuleHandle left, ModuleHandle right) { return !left.Equals(right); } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern IRuntimeMethodInfo GetDynamicMethod(DynamicMethod method, RuntimeModule module, string name, byte[] sig, Resolver resolver); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern int GetToken(RuntimeModule module); private static void ValidateModulePointer(RuntimeModule module) { // Make sure we have a valid Module to resolve against. if (module == null) throw new InvalidOperationException(SR.InvalidOperation_NullModuleHandle); } // SQL-CLR LKG9 Compiler dependency public RuntimeTypeHandle GetRuntimeTypeHandleFromMetadataToken(int typeToken) { return ResolveTypeHandle(typeToken); } public RuntimeTypeHandle ResolveTypeHandle(int typeToken) { return new RuntimeTypeHandle(ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, null, null)); } public RuntimeTypeHandle ResolveTypeHandle(int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) { return new RuntimeTypeHandle(ModuleHandle.ResolveTypeHandleInternal(GetRuntimeModule(), typeToken, typeInstantiationContext, methodInstantiationContext)); } internal static RuntimeType ResolveTypeHandleInternal(RuntimeModule module, int typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) { ValidateModulePointer(module); if (!ModuleHandle.GetMetadataImport(module).IsValidToken(typeToken)) throw new ArgumentOutOfRangeException(nameof(typeToken), SR.Format(SR.Argument_InvalidToken, typeToken, new ModuleHandle(module))); int typeInstCount, methodInstCount; IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles) { RuntimeType type = null; ResolveType(module, typeToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref type)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); return type; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void ResolveType(RuntimeModule module, int typeToken, IntPtr* typeInstArgs, int typeInstCount, IntPtr* methodInstArgs, int methodInstCount, ObjectHandleOnStack type); // SQL-CLR LKG9 Compiler dependency public RuntimeMethodHandle GetRuntimeMethodHandleFromMetadataToken(int methodToken) { return ResolveMethodHandle(methodToken); } public RuntimeMethodHandle ResolveMethodHandle(int methodToken) { return ResolveMethodHandle(methodToken, null, null); } internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken) { return ModuleHandle.ResolveMethodHandleInternal(module, methodToken, null, null); } public RuntimeMethodHandle ResolveMethodHandle(int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) { return new RuntimeMethodHandle(ResolveMethodHandleInternal(GetRuntimeModule(), methodToken, typeInstantiationContext, methodInstantiationContext)); } internal static IRuntimeMethodInfo ResolveMethodHandleInternal(RuntimeModule module, int methodToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) { int typeInstCount, methodInstCount; IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); RuntimeMethodHandleInternal handle = ResolveMethodHandleInternalCore(module, methodToken, typeInstantiationContextHandles, typeInstCount, methodInstantiationContextHandles, methodInstCount); IRuntimeMethodInfo retVal = new RuntimeMethodInfoStub(handle, RuntimeMethodHandle.GetLoaderAllocator(handle)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); return retVal; } internal static RuntimeMethodHandleInternal ResolveMethodHandleInternalCore(RuntimeModule module, int methodToken, IntPtr[] typeInstantiationContext, int typeInstCount, IntPtr[] methodInstantiationContext, int methodInstCount) { ValidateModulePointer(module); if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(methodToken)) throw new ArgumentOutOfRangeException(nameof(methodToken), SR.Format(SR.Argument_InvalidToken, methodToken, new ModuleHandle(module))); fixed (IntPtr* typeInstArgs = typeInstantiationContext, methodInstArgs = methodInstantiationContext) { return ResolveMethod(module.GetNativeHandle(), methodToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount); } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static RuntimeMethodHandleInternal ResolveMethod(RuntimeModule module, int methodToken, IntPtr* typeInstArgs, int typeInstCount, IntPtr* methodInstArgs, int methodInstCount); // SQL-CLR LKG9 Compiler dependency public RuntimeFieldHandle GetRuntimeFieldHandleFromMetadataToken(int fieldToken) { return ResolveFieldHandle(fieldToken); } public RuntimeFieldHandle ResolveFieldHandle(int fieldToken) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, null, null)); } public RuntimeFieldHandle ResolveFieldHandle(int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) { return new RuntimeFieldHandle(ResolveFieldHandleInternal(GetRuntimeModule(), fieldToken, typeInstantiationContext, methodInstantiationContext)); } internal static IRuntimeFieldInfo ResolveFieldHandleInternal(RuntimeModule module, int fieldToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext) { ValidateModulePointer(module); if (!ModuleHandle.GetMetadataImport(module.GetNativeHandle()).IsValidToken(fieldToken)) throw new ArgumentOutOfRangeException(nameof(fieldToken), SR.Format(SR.Argument_InvalidToken, fieldToken, new ModuleHandle(module))); // defensive copy to be sure array is not mutated from the outside during processing int typeInstCount, methodInstCount; IntPtr[] typeInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(typeInstantiationContext, out typeInstCount); IntPtr[] methodInstantiationContextHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(methodInstantiationContext, out methodInstCount); fixed (IntPtr* typeInstArgs = typeInstantiationContextHandles, methodInstArgs = methodInstantiationContextHandles) { IRuntimeFieldInfo field = null; ResolveField(module.GetNativeHandle(), fieldToken, typeInstArgs, typeInstCount, methodInstArgs, methodInstCount, JitHelpers.GetObjectHandleOnStack(ref field)); GC.KeepAlive(typeInstantiationContext); GC.KeepAlive(methodInstantiationContext); return field; } } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void ResolveField(RuntimeModule module, int fieldToken, IntPtr* typeInstArgs, int typeInstCount, IntPtr* methodInstArgs, int methodInstCount, ObjectHandleOnStack retField); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static bool _ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash); internal static bool ContainsPropertyMatchingHash(RuntimeModule module, int propertyToken, uint hash) { return _ContainsPropertyMatchingHash(module.GetNativeHandle(), propertyToken, hash); } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] internal extern static void GetModuleType(RuntimeModule handle, ObjectHandleOnStack type); internal static RuntimeType GetModuleType(RuntimeModule module) { RuntimeType type = null; GetModuleType(module.GetNativeHandle(), JitHelpers.GetObjectHandleOnStack(ref type)); return type; } [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [SuppressUnmanagedCodeSecurity] private extern static void GetPEKind(RuntimeModule handle, out int peKind, out int machine); // making this internal, used by Module.GetPEKind internal static void GetPEKind(RuntimeModule module, out PortableExecutableKinds peKind, out ImageFileMachine machine) { int lKind, lMachine; GetPEKind(module.GetNativeHandle(), out lKind, out lMachine); peKind = (PortableExecutableKinds)lKind; machine = (ImageFileMachine)lMachine; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern static int GetMDStreamVersion(RuntimeModule module); public int MDStreamVersion { get { return GetMDStreamVersion(GetRuntimeModule().GetNativeHandle()); } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern static IntPtr _GetMetadataImport(RuntimeModule module); internal static MetadataImport GetMetadataImport(RuntimeModule module) { return new MetadataImport(_GetMetadataImport(module.GetNativeHandle()), module); } #endregion } internal unsafe class Signature { #region Definitions internal enum MdSigCallingConvention : byte { Generics = 0x10, HasThis = 0x20, ExplicitThis = 0x40, CallConvMask = 0x0F, Default = 0x00, C = 0x01, StdCall = 0x02, ThisCall = 0x03, FastCall = 0x04, Vararg = 0x05, Field = 0x06, LocalSig = 0x07, Property = 0x08, Unmgd = 0x09, GenericInst = 0x0A, Max = 0x0B, } #endregion #region FCalls [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern void GetSignature( void* pCorSig, int cCorSig, RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo methodHandle, RuntimeType declaringType); #endregion #region Private Data Members // // Keep the layout in sync with SignatureNative in the VM // internal RuntimeType[] m_arguments; internal RuntimeType m_declaringType; internal RuntimeType m_returnTypeORfieldType; internal object m_keepalive; internal void* m_sig; internal int m_managedCallingConventionAndArgIteratorFlags; // lowest byte is CallingConvention, upper 3 bytes are ArgIterator flags internal int m_nSizeOfArgStack; internal int m_csig; internal RuntimeMethodHandleInternal m_pMethod; #endregion #region Constructors public Signature( IRuntimeMethodInfo method, RuntimeType[] arguments, RuntimeType returnType, CallingConventions callingConvention) { m_pMethod = method.Value; m_arguments = arguments; m_returnTypeORfieldType = returnType; m_managedCallingConventionAndArgIteratorFlags = (byte)callingConvention; GetSignature(null, 0, new RuntimeFieldHandleInternal(), method, null); } public Signature(IRuntimeMethodInfo methodHandle, RuntimeType declaringType) { GetSignature(null, 0, new RuntimeFieldHandleInternal(), methodHandle, declaringType); } public Signature(IRuntimeFieldInfo fieldHandle, RuntimeType declaringType) { GetSignature(null, 0, fieldHandle.Value, null, declaringType); GC.KeepAlive(fieldHandle); } public Signature(void* pCorSig, int cCorSig, RuntimeType declaringType) { GetSignature(pCorSig, cCorSig, new RuntimeFieldHandleInternal(), null, declaringType); } #endregion #region Internal Members internal CallingConventions CallingConvention { get { return (CallingConventions)(byte)m_managedCallingConventionAndArgIteratorFlags; } } internal RuntimeType[] Arguments { get { return m_arguments; } } internal RuntimeType ReturnType { get { return m_returnTypeORfieldType; } } internal RuntimeType FieldType { get { return m_returnTypeORfieldType; } } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern bool CompareSig(Signature sig1, Signature sig2); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal extern Type[] GetCustomModifiers(int position, bool required); #endregion } internal abstract class Resolver { internal struct CORINFO_EH_CLAUSE { internal int Flags; internal int TryOffset; internal int TryLength; internal int HandlerOffset; internal int HandlerLength; internal int ClassTokenOrFilterOffset; } // ILHeader info internal abstract RuntimeType GetJitContext(ref int securityControlFlags); internal abstract byte[] GetCodeInfo(ref int stackSize, ref int initLocals, ref int EHCount); internal abstract byte[] GetLocalsSignature(); internal abstract unsafe void GetEHInfo(int EHNumber, void* exception); internal abstract unsafe byte[] GetRawEHInfo(); // token resolution internal abstract String GetStringLiteral(int token); internal abstract void ResolveToken(int token, out IntPtr typeHandle, out IntPtr methodHandle, out IntPtr fieldHandle); internal abstract byte[] ResolveSignature(int token, int fromMethod); // internal abstract MethodInfo GetDynamicMethod(); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.IO; using System.Net; using System.Net.Http; using System.Net.Sockets; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.HttpSys.Internal; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Logging; using Xunit; namespace Microsoft.AspNetCore.Server.HttpSys.Listener { public class ServerTests { [ConditionalFact] public async Task Server_TokenRegisteredAfterClientDisconnects_CallCanceled() { var interval = TimeSpan.FromSeconds(1); var canceled = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); string address; using (var server = Utilities.CreateHttpServer(out address)) { using (var client = new HttpClient()) { var responseTask = client.GetAsync(address); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); client.CancelPendingRequests(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => responseTask); var ct = context.DisconnectToken; Assert.True(ct.CanBeCanceled, "CanBeCanceled"); ct.Register(() => canceled.SetResult(0)); await canceled.Task.TimeoutAfter(interval); Assert.True(ct.IsCancellationRequested, "IsCancellationRequested"); context.Dispose(); } } } [ConditionalFact] public async Task Server_TokenRegisteredAfterResponseSent_Success() { var interval = TimeSpan.FromSeconds(1); var canceled = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); string address; using (var server = Utilities.CreateHttpServer(out address)) { using (var client = new HttpClient()) { var responseTask = client.GetAsync(address); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); context.Dispose(); var response = await responseTask; response.EnsureSuccessStatusCode(); Assert.Equal(string.Empty, await response.Content.ReadAsStringAsync()); var ct = context.DisconnectToken; Assert.False(ct.CanBeCanceled, "CanBeCanceled"); ct.Register(() => canceled.SetResult(0)); Assert.False(ct.IsCancellationRequested, "IsCancellationRequested"); Assert.False(canceled.Task.IsCompleted, "canceled"); } } } [ConditionalFact] public async Task Server_ConnectionCloseHeader_CancellationTokenFires() { var interval = TimeSpan.FromSeconds(1); var canceled = new TaskCompletionSource<int>(TaskCreationOptions.RunContinuationsAsynchronously); string address; using (var server = Utilities.CreateHttpServer(out address)) { var responseTask = SendRequestAsync(address); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); var ct = context.DisconnectToken; Assert.True(ct.CanBeCanceled, "CanBeCanceled"); Assert.False(ct.IsCancellationRequested, "IsCancellationRequested"); ct.Register(() => canceled.SetResult(0)); context.Response.Headers["Connection"] = "close"; context.Response.ContentLength = 11; var writer = new StreamWriter(context.Response.Body); await writer.WriteAsync("Hello World"); await writer.FlushAsync(); await canceled.Task.TimeoutAfter(interval); Assert.True(ct.IsCancellationRequested, "IsCancellationRequested"); var response = await responseTask; Assert.Equal("Hello World", response); } } [ConditionalFact] public async Task Server_SetRejectionVerbosityLevel_Success() { using (var server = Utilities.CreateHttpServer(out string address)) { server.Options.Http503Verbosity = Http503VerbosityLevel.Limited; var responseTask = SendRequestAsync(address); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); context.Dispose(); var response = await responseTask; Assert.Equal(string.Empty, response); } } [ConditionalFact] public void Server_RegisterUnavailablePrefix_ThrowsActionableHttpSysException() { using var server1 = Utilities.CreateHttpServer(out var address1); var options = new HttpSysOptions(); options.UrlPrefixes.Add(address1); using var listener = new HttpSysListener(options, new LoggerFactory()); var exception = Assert.Throws<HttpSysException>(() => listener.Start()); Assert.Equal((int)UnsafeNclNativeMethods.ErrorCodes.ERROR_ALREADY_EXISTS, exception.ErrorCode); Assert.Contains($"The prefix '{address1}' is already registered.", exception.Message); } [ConditionalFact] public async Task Server_HotAddPrefix_Success() { string address; using (var server = Utilities.CreateHttpServer(out address)) { var responseTask = SendRequestAsync(address); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal(string.Empty, context.Request.PathBase); Assert.Equal("/", context.Request.Path); context.Dispose(); var response = await responseTask; Assert.Equal(string.Empty, response); address += "pathbase/"; server.Options.UrlPrefixes.Add(address); responseTask = SendRequestAsync(address); context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal("/pathbase", context.Request.PathBase); Assert.Equal("/", context.Request.Path); context.Dispose(); response = await responseTask; Assert.Equal(string.Empty, response); } } [ConditionalFact] public async Task Server_HotRemovePrefix_Success() { string address; using (var server = Utilities.CreateHttpServer(out address)) { address += "pathbase/"; server.Options.UrlPrefixes.Add(address); var responseTask = SendRequestAsync(address); var context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal("/pathbase", context.Request.PathBase); Assert.Equal("/", context.Request.Path); context.Dispose(); var response = await responseTask; Assert.Equal(string.Empty, response); Assert.True(server.Options.UrlPrefixes.Remove(address)); responseTask = SendRequestAsync(address); context = await server.AcceptAsync(Utilities.DefaultTimeout).Before(responseTask); Assert.Equal(string.Empty, context.Request.PathBase); Assert.Equal("/pathbase/", context.Request.Path); context.Dispose(); response = await responseTask; Assert.Equal(string.Empty, response); } } private async Task<string> SendRequestAsync(string uri) { using (HttpClient client = new HttpClient()) { return await client.GetStringAsync(uri); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network { 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> /// PublicIPAddressesOperations operations. /// </summary> internal partial class PublicIPAddressesOperations : IServiceOperations<NetworkManagementClient>, IPublicIPAddressesOperations { /// <summary> /// Initializes a new instance of the PublicIPAddressesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal PublicIPAddressesOperations(NetworkManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// The delete publicIpAddress operation deletes the specified publicIpAddress. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginDeleteWithHttpMessagesAsync( resourceGroupName, publicIpAddressName, customHeaders, cancellationToken); return await this.Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// The delete publicIpAddress operation deletes the specified publicIpAddress. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </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> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginDelete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 204 && (int)_statusCode != 202 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// The Get publicIpAddress operation retreives information about the /// specified pubicIpAddress /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the subnet. /// </param> /// <param name='expand'> /// expand references resources. /// </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<PublicIPAddress>> GetWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", Uri.EscapeDataString(expand))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PublicIPAddress>(); _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<PublicIPAddress>(_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> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update PublicIPAddress operation /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<PublicIPAddress>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<PublicIPAddress> _response = await BeginCreateOrUpdateWithHttpMessagesAsync( resourceGroupName, publicIpAddressName, parameters, customHeaders, cancellationToken); return await this.Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken); } /// <summary> /// The Put PublicIPAddress operation creates/updates a stable/dynamic /// PublicIP address /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='publicIpAddressName'> /// The name of the publicIpAddress. /// </param> /// <param name='parameters'> /// Parameters supplied to the create/update PublicIPAddress operation /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<PublicIPAddress>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string publicIpAddressName, PublicIPAddress parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (publicIpAddressName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "publicIpAddressName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("publicIpAddressName", publicIpAddressName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses/{publicIpAddressName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{publicIpAddressName}", Uri.EscapeDataString(publicIpAddressName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("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(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, 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 != 201 && (int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<PublicIPAddress>(); _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 == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PublicIPAddress>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<PublicIPAddress>(_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> /// The List publicIpAddress opertion retrieves all the publicIpAddresses in a /// subscription. /// </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<IPage<PublicIPAddress>>> ListAllWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // 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, "ListAll", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Network/publicIPAddresses").ToString(); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_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> /// The List publicIpAddress opertion retrieves all the publicIpAddresses in a /// resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/publicIPAddresses").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_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> /// The List publicIpAddress opertion retrieves all the publicIpAddresses in a /// subscription. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListAllNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListAllNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_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> /// The List publicIpAddress opertion retrieves all the publicIpAddresses in a /// resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<PublicIPAddress>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<PublicIPAddress>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Page<PublicIPAddress>>(_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; } } }
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- datablock ParticleEmitterNodeData(DefaultEmitterNodeData) { timeMultiple = 1; }; // Smoke datablock ParticleData(Smoke) { textureName = "art/particles/smoke"; dragCoefficient = 0.3; gravityCoefficient = -0.2; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 3000; lifetimeVarianceMS = 250; useInvAlpha = true; spinRandomMin = -30.0; spinRandomMax = 30.0; sizes[0] = 1.5; sizes[1] = 2.75; sizes[2] = 6.5; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(SmokeEmitter) { ejectionPeriodMS = 400; periodVarianceMS = 5; ejectionVelocity = 0.0; velocityVariance = 0.0; thetaMin = 0.0; thetaMax = 90.0; particles = Smoke; }; datablock ParticleEmitterNodeData(SmokeEmitterNode) { timeMultiple = 1; }; // Ember datablock ParticleData(EmberParticle) { textureName = "art/particles/ember"; dragCoefficient = 0.0; windCoefficient = 0.0; gravityCoefficient = -0.05; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 5000; lifetimeVarianceMS = 0; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 90.0; spinSpeed = 1; colors[0] = "1.000000 0.800000 0.000000 0.800000"; colors[1] = "1.000000 0.700000 0.000000 0.800000"; colors[2] = "1.000000 0.000000 0.000000 0.200000"; sizes[0] = 0.05; sizes[1] = 0.1; sizes[2] = 0.05; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(EmberEmitter) { ejectionPeriodMS = 100; periodVarianceMS = 0; ejectionVelocity = 0.75; velocityVariance = 0.00; ejectionOffset = 2.0; thetaMin = 1.0; thetaMax = 100.0; particles = "EmberParticle"; }; datablock ParticleEmitterNodeData(EmberNode) { timeMultiple = 1; }; // Fire datablock ParticleData(FireParticle) { textureName = "art/particles/smoke"; dragCoefficient = 0.0; windCoefficient = 0.0; gravityCoefficient = -0.05; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 5000; lifetimeVarianceMS = 1000; useInvAlpha = false; spinRandomMin = -90.0; spinRandomMax = 90.0; spinSpeed = 1.0; colors[0] = "0.2 0.2 0.0 0.2"; colors[1] = "0.6 0.2 0.0 0.2"; colors[2] = "0.4 0.0 0.0 0.1"; colors[3] = "0.1 0.04 0.0 0.3"; sizes[0] = 0.5; sizes[1] = 4.0; sizes[2] = 5.0; sizes[3] = 6.0; times[0] = 0.0; times[1] = 0.1; times[2] = 0.2; times[3] = 0.3; }; datablock ParticleEmitterData(FireEmitter) { ejectionPeriodMS = 50; periodVarianceMS = 0; ejectionVelocity = 0.55; velocityVariance = 0.00; ejectionOffset = 1.0; thetaMin = 1.0; thetaMax = 100.0; particles = "FireParticle"; }; datablock ParticleEmitterNodeData(FireNode) { timeMultiple = 1; }; // Torch Fire datablock ParticleData(TorchFire1) { textureName = "art/particles/smoke"; dragCoefficient = 0.0; gravityCoefficient = -0.3; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 500; lifetimeVarianceMS = 250; useInvAlpha = false; spinRandomMin = -30.0; spinRandomMax = 30.0; spinSpeed = 1; colors[0] = "0.6 0.6 0.0 0.1"; colors[1] = "0.8 0.6 0.0 0.1"; colors[2] = "0.0 0.0 0.0 0.1"; sizes[0] = 0.5; sizes[1] = 0.5; sizes[2] = 2.4; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleData(TorchFire2) { textureName = "art/particles/smoke"; dragCoefficient = 0.0; gravityCoefficient = -0.5; // rises slowly inheritedVelFactor = 0.00; lifetimeMS = 800; lifetimeVarianceMS = 150; useInvAlpha = false; spinRandomMin = -30.0; spinRandomMax = 30.0; spinSpeed = 1; colors[0] = "0.8 0.6 0.0 0.1"; colors[1] = "0.6 0.6 0.0 0.1"; colors[2] = "0.0 0.0 0.0 0.1"; sizes[0] = 0.3; sizes[1] = 0.3; sizes[2] = 0.3; times[0] = 0.0; times[1] = 0.5; times[2] = 1.0; }; datablock ParticleEmitterData(TorchFireEmitter) { ejectionPeriodMS = 15; periodVarianceMS = 5; ejectionVelocity = 0.25; velocityVariance = 0.10; thetaMin = 0.0; thetaMax = 45.0; particles = "TorchFire1" TAB "TorchFire2"; }; datablock ParticleEmitterNodeData(TorchFireEmitterNode) { timeMultiple = 1; };
using UnityEngine; using UnityEditor; using System.Text; using System.IO; using UMA; using System.Collections.Generic; namespace UMAEditor { public class UmaSlotBuilderWindow : EditorWindow { public string slotName; public UnityEngine.Object slotFolder; public UnityEngine.Object relativeFolder; public SkinnedMeshRenderer normalReferenceMesh; public SkinnedMeshRenderer slotMesh; public UMAMaterial slotMaterial; string GetAssetFolder() { int index = slotName.LastIndexOf('/'); if( index > 0 ) { return slotName.Substring(0, index+1); } return ""; } string GetAssetName() { int index = slotName.LastIndexOf('/'); if (index > 0) { return slotName.Substring(index + 1); } return slotName; } public void EnforceFolder(ref UnityEngine.Object folderObject) { if (folderObject != null) { string destpath = AssetDatabase.GetAssetPath(folderObject); if (string.IsNullOrEmpty(destpath)) { folderObject = null; } else if (!System.IO.Directory.Exists(destpath)) { destpath = destpath.Substring(0, destpath.LastIndexOf('/')); folderObject = AssetDatabase.LoadMainAssetAtPath(destpath); } } } void OnGUI() { GUILayout.Label("UMA Slot Builder"); GUILayout.Space(20); normalReferenceMesh = EditorGUILayout.ObjectField("Seams Mesh (Optional)", normalReferenceMesh, typeof(SkinnedMeshRenderer), false) as SkinnedMeshRenderer; slotMesh = EditorGUILayout.ObjectField("Slot Mesh", slotMesh, typeof(SkinnedMeshRenderer), false) as SkinnedMeshRenderer; slotMaterial = EditorGUILayout.ObjectField("UMAMaterial", slotMaterial, typeof(UMAMaterial), false) as UMAMaterial; slotFolder = EditorGUILayout.ObjectField("Slot Destination Folder", slotFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object; EnforceFolder(ref slotFolder); slotName = EditorGUILayout.TextField("Element Name", slotName); if (GUILayout.Button("Create Slot")) { Debug.Log("Processing..."); if (CreateSlot() != null) { Debug.Log("Success."); } } GUILayout.Label("", EditorStyles.boldLabel); Rect dropArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true)); GUI.Box(dropArea, "Drag meshes here"); GUILayout.Label("Automatic Drag and Drop processing", EditorStyles.boldLabel); relativeFolder = EditorGUILayout.ObjectField("Relative Folder", relativeFolder, typeof(UnityEngine.Object), false) as UnityEngine.Object; EnforceFolder(ref relativeFolder); DropAreaGUI(dropArea); } private SlotDataAsset CreateSlot() { if(slotName == null || slotName == ""){ Debug.LogError("slotName must be specified."); return null; } return CreateSlot_Internal(); } private SlotDataAsset CreateSlot_Internal() { var material = slotMaterial; if (slotName == null || slotName == "") { Debug.LogError("slotName must be specified."); return null; } if (material == null) { Debug.LogWarning("No UMAMaterial specified, you need to specify that later."); return null; } if (slotFolder == null) { Debug.LogError("Slot folder not supplied"); return null; } if (slotMesh == null) { Debug.LogError("Slot Mesh not supplied."); return null; } Debug.Log("Slot Mesh: " + slotMesh.name, slotMesh.gameObject); SlotDataAsset slot = UMASlotProcessingUtil.CreateSlotData(AssetDatabase.GetAssetPath(slotFolder), GetAssetFolder(), GetAssetName(), slotMesh, material, normalReferenceMesh); return slot; } private void DropAreaGUI(Rect dropArea) { var evt = Event.current; if (evt.type == EventType.DragUpdated) { if (dropArea.Contains(evt.mousePosition)) { DragAndDrop.visualMode = DragAndDropVisualMode.Copy; } } if (evt.type == EventType.DragPerform) { if (dropArea.Contains(evt.mousePosition)) { DragAndDrop.AcceptDrag(); UnityEngine.Object[] draggedObjects = DragAndDrop.objectReferences as UnityEngine.Object[]; var meshes = new HashSet<SkinnedMeshRenderer>(); for (int i = 0; i < draggedObjects.Length; i++) { RecurseObject(draggedObjects[i], meshes); } foreach(var mesh in meshes) { slotMesh = mesh; GetMaterialName(mesh.name, mesh); if (CreateSlot() != null) { Debug.Log("Batch importer processed mesh: " + slotName); } } } } } private void RecurseObject(Object obj, HashSet<SkinnedMeshRenderer> meshes) { GameObject go = obj as GameObject; if (go != null) { foreach (var smr in go.GetComponentsInChildren<SkinnedMeshRenderer>(true)) { meshes.Add(smr); } return; } var path = AssetDatabase.GetAssetPath(obj); if (!string.IsNullOrEmpty(path) && System.IO.Directory.Exists(path)) { foreach (var guid in AssetDatabase.FindAssets("t:GameObject", new string[] {path})) { RecurseObject(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid), typeof(GameObject)), meshes); } } } private string ProcessTextureTypeAndName(Texture2D tex) { var suffixes = new string[] { "_dif", "_spec", "_nor" }; int index = 0; foreach( var suffix in suffixes ) { index = tex.name.IndexOf(suffix, System.StringComparison.InvariantCultureIgnoreCase); if( index > 0 ) { string name = tex.name.Substring(0,index); GetMaterialName(name, tex); return suffix; } } return ""; } private void GetMaterialName(string name, UnityEngine.Object obj) { if (relativeFolder != null) { var relativeLocation = AssetDatabase.GetAssetPath(relativeFolder); var assetLocation = AssetDatabase.GetAssetPath(obj); if (assetLocation.StartsWith(relativeLocation, System.StringComparison.InvariantCultureIgnoreCase)) { string temp = assetLocation.Substring(relativeLocation.Length + 1); // remove the prefix temp = temp.Substring(0, temp.LastIndexOf('/') + 1); // remove the asset name slotName = temp + name; // add the cleaned name } } else { slotName = name; } } [MenuItem("UMA/Slot Builder")] public static void OpenUmaTexturePrepareWindow() { UmaSlotBuilderWindow window = (UmaSlotBuilderWindow)EditorWindow.GetWindow(typeof(UmaSlotBuilderWindow)); #if !UNITY_4_6 && !UNITY_5_0 window.titleContent.text = "Slot Builder"; #else window.title = "Slot Builder"; #endif } [MenuItem("UMA/Optimize Slot Meshes")] public static void OptimizeSlotMeshes() { #if UMA2_LEAN_AND_CLEAN Debug.LogError("MenuItem - UMA/OptimizeSlotMeshes does not work with the define UMA2_LEAN_AND_CLEAN, we need all legacy fields available."); #else foreach (var obj in Selection.objects) { var SlotDataAsset = obj as SlotDataAsset; if (SlotDataAsset != null) { #pragma warning disable 618 if (SlotDataAsset.meshRenderer != null) { UMASlotProcessingUtil.OptimizeSlotDataMesh(SlotDataAsset.meshRenderer); SlotDataAsset.UpdateMeshData(SlotDataAsset.meshRenderer); SlotDataAsset.meshRenderer = null; EditorUtility.SetDirty(SlotDataAsset); } else { if (SlotDataAsset.meshData != null) { SlotDataAsset.UpdateMeshData(); } else { if (SlotDataAsset.meshData.vertices != null) { SlotDataAsset.UpdateMeshData(); } } } #pragma warning restore 618 } } AssetDatabase.SaveAssets(); #endif } } }
// Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. // // System.Drawing.Image.cs // // Authors: Christian Meyer (Christian.Meyer@cs.tum.edu) // Alexandre Pigolkine (pigolkine@gmx.de) // Jordi Mas i Hernandez (jordi@ximian.com) // Sanjay Gupta (gsanjay@novell.com) // Ravindra (rkumar@novell.com) // Sebastien Pouliot <sebastien@ximian.com> // // Copyright (C) 2002 Ximian, Inc. http://www.ximian.com // Copyright (C) 2004, 2007 Novell, Inc (http://www.novell.com) // Copyright (C) 2013 Kristof Ralovich, changes are available under the terms of the MIT X11 license // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.Serialization; using System.Runtime.InteropServices; using System.ComponentModel; using System.Drawing.Imaging; using System.IO; using System.Reflection; using Gdip = System.Drawing.SafeNativeMethods.Gdip; namespace System.Drawing { #if !NETCORE [Editor ("System.Drawing.Design.ImageEditor, " + Consts.AssemblySystem_Drawing_Design, typeof (System.Drawing.Design.UITypeEditor))] [TypeConverter (typeof(ImageConverter))] #endif public abstract partial class Image { // public methods // static public static Image FromFile(string filename, bool useEmbeddedColorManagement) { IntPtr imagePtr; int st; if (!File.Exists(filename)) throw new FileNotFoundException(filename); if (useEmbeddedColorManagement) st = Gdip.GdipLoadImageFromFileICM(filename, out imagePtr); else st = Gdip.GdipLoadImageFromFile(filename, out imagePtr); Gdip.CheckStatus(st); return CreateFromHandle(imagePtr); } // See http://support.microsoft.com/default.aspx?scid=kb;en-us;831419 for performance discussion public static Image FromStream(Stream stream, bool useEmbeddedColorManagement, bool validateImageData) { return LoadFromStream(stream, false); } internal static Image LoadFromStream(Stream stream, bool keepAlive) { if (stream == null) throw new ArgumentNullException(nameof(stream)); Image img = CreateFromHandle(InitializeFromStream(stream)); return img; } internal static Image CreateImageObject(IntPtr nativeImage) { return CreateFromHandle(nativeImage); } internal static Image CreateFromHandle(IntPtr handle) { ImageType type; Gdip.CheckStatus(Gdip.GdipGetImageType(handle, out type)); switch (type) { case ImageType.Bitmap: return new Bitmap(handle); case ImageType.Metafile: return new Metafile(handle); default: throw new NotSupportedException("Unknown image type."); } } public static int GetPixelFormatSize(PixelFormat pixfmt) { int result = 0; switch (pixfmt) { case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: result = 16; break; case PixelFormat.Format1bppIndexed: result = 1; break; case PixelFormat.Format24bppRgb: result = 24; break; case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppRgb: result = 32; break; case PixelFormat.Format48bppRgb: result = 48; break; case PixelFormat.Format4bppIndexed: result = 4; break; case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: result = 64; break; case PixelFormat.Format8bppIndexed: result = 8; break; } return result; } public static bool IsAlphaPixelFormat(PixelFormat pixfmt) { bool result = false; switch (pixfmt) { case PixelFormat.Format16bppArgb1555: case PixelFormat.Format32bppArgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format64bppArgb: case PixelFormat.Format64bppPArgb: result = true; break; case PixelFormat.Format16bppGrayScale: case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format1bppIndexed: case PixelFormat.Format24bppRgb: case PixelFormat.Format32bppRgb: case PixelFormat.Format48bppRgb: case PixelFormat.Format4bppIndexed: case PixelFormat.Format8bppIndexed: result = false; break; } return result; } private protected static IntPtr InitializeFromStream(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); // Unix, with libgdiplus // We use a custom API for this, because there's no easy way // to get the Stream down to libgdiplus. So, we wrap the stream // with a set of delegates. GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, true); int st = Gdip.GdipLoadImageFromDelegate_linux(sh.GetHeaderDelegate, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, out IntPtr imagePtr); // Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive // to avoid the object being collected and therefore the delegates would be collected as well. GC.KeepAlive(sh); Gdip.CheckStatus(st); return imagePtr; } // non-static public RectangleF GetBounds(ref GraphicsUnit pageUnit) { RectangleF source; int status = Gdip.GdipGetImageBounds(nativeImage, out source, ref pageUnit); Gdip.CheckStatus(status); return source; } public EncoderParameters GetEncoderParameterList(Guid encoder) { int status; uint sz; status = Gdip.GdipGetEncoderParameterListSize(nativeImage, ref encoder, out sz); Gdip.CheckStatus(status); IntPtr rawEPList = Marshal.AllocHGlobal((int)sz); EncoderParameters eps; try { status = Gdip.GdipGetEncoderParameterList(nativeImage, ref encoder, sz, rawEPList); eps = EncoderParameters.ConvertFromMemory(rawEPList); Gdip.CheckStatus(status); } finally { Marshal.FreeHGlobal(rawEPList); } return eps; } public PropertyItem GetPropertyItem(int propid) { int propSize; IntPtr property; PropertyItem item = new PropertyItem(); GdipPropertyItem gdipProperty = new GdipPropertyItem(); int status; status = Gdip.GdipGetPropertyItemSize(nativeImage, propid, out propSize); Gdip.CheckStatus(status); /* Get PropertyItem */ property = Marshal.AllocHGlobal(propSize); try { status = Gdip.GdipGetPropertyItem(nativeImage, propid, propSize, property); Gdip.CheckStatus(status); gdipProperty = (GdipPropertyItem)Marshal.PtrToStructure(property, typeof(GdipPropertyItem)); GdipPropertyItem.MarshalTo(gdipProperty, item); } finally { Marshal.FreeHGlobal(property); } return item; } public Image GetThumbnailImage(int thumbWidth, int thumbHeight, Image.GetThumbnailImageAbort callback, IntPtr callbackData) { if ((thumbWidth <= 0) || (thumbHeight <= 0)) throw new OutOfMemoryException("Invalid thumbnail size"); Image ThumbNail = new Bitmap(thumbWidth, thumbHeight); using (Graphics g = Graphics.FromImage(ThumbNail)) { int status = Gdip.GdipDrawImageRectRectI(g.NativeGraphics, nativeImage, 0, 0, thumbWidth, thumbHeight, 0, 0, this.Width, this.Height, GraphicsUnit.Pixel, IntPtr.Zero, null, IntPtr.Zero); Gdip.CheckStatus(status); } return ThumbNail; } internal ImageCodecInfo FindEncoderForFormat(ImageFormat format) { ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo encoder = null; if (format.Guid.Equals(ImageFormat.MemoryBmp.Guid)) format = ImageFormat.Png; /* Look for the right encoder for our format*/ for (int i = 0; i < encoders.Length; i++) { if (encoders[i].FormatID.Equals(format.Guid)) { encoder = encoders[i]; break; } } return encoder; } public void Save(string filename, ImageFormat format) { ImageCodecInfo encoder = FindEncoderForFormat(format); if (encoder == null) { // second chance encoder = FindEncoderForFormat(RawFormat); if (encoder == null) { string msg = string.Format("No codec available for saving format '{0}'.", format.Guid); throw new ArgumentException(msg, nameof(format)); } } Save(filename, encoder, null); } public void Save(string filename, ImageCodecInfo encoder, EncoderParameters encoderParams) { int st; Guid guid = encoder.Clsid; if (encoderParams == null) { st = Gdip.GdipSaveImageToFile(nativeImage, filename, ref guid, IntPtr.Zero); } else { IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = Gdip.GdipSaveImageToFile(nativeImage, filename, ref guid, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); } Gdip.CheckStatus(st); } private void Save(MemoryStream stream) { // Jpeg loses data, so we don't want to use it to serialize... ImageFormat dest = RawFormat; if (dest.Guid == ImageFormat.Jpeg.Guid) dest = ImageFormat.Png; // If we don't find an Encoder (for things like Icon), we just switch back to PNG... ImageCodecInfo codec = FindEncoderForFormat(dest) ?? FindEncoderForFormat(ImageFormat.Png); Save(stream, codec, null); } public void Save(Stream stream, ImageFormat format) { ImageCodecInfo encoder = FindEncoderForFormat(format); if (encoder == null) throw new ArgumentException("No codec available for format:" + format.Guid); Save(stream, encoder, null); } public void Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams) { int st; IntPtr nativeEncoderParams; Guid guid = encoder.Clsid; if (encoderParams == null) nativeEncoderParams = IntPtr.Zero; else nativeEncoderParams = encoderParams.ConvertToMemory(); try { GdiPlusStreamHelper sh = new GdiPlusStreamHelper(stream, false); st = Gdip.GdipSaveImageToDelegate_linux(nativeImage, sh.GetBytesDelegate, sh.PutBytesDelegate, sh.SeekDelegate, sh.CloseDelegate, sh.SizeDelegate, ref guid, nativeEncoderParams); // Since we're just passing to native code the delegates inside the wrapper, we need to keep sh alive // to avoid the object being collected and therefore the delegates would be collected as well. GC.KeepAlive(sh); } finally { if (nativeEncoderParams != IntPtr.Zero) Marshal.FreeHGlobal(nativeEncoderParams); } Gdip.CheckStatus(st); } public void SaveAdd(EncoderParameters encoderParams) { int st; IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = Gdip.GdipSaveAdd(nativeImage, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); Gdip.CheckStatus(st); } public void SaveAdd(Image image, EncoderParameters encoderParams) { int st; IntPtr nativeEncoderParams = encoderParams.ConvertToMemory(); st = Gdip.GdipSaveAddImage(nativeImage, image.nativeImage, nativeEncoderParams); Marshal.FreeHGlobal(nativeEncoderParams); Gdip.CheckStatus(st); } public void SetPropertyItem(PropertyItem propitem) { if (propitem == null) throw new ArgumentNullException(nameof(propitem)); int nItemSize = Marshal.SizeOf(propitem.Value[0]); int size = nItemSize * propitem.Value.Length; IntPtr dest = Marshal.AllocHGlobal(size); try { GdipPropertyItem pi = new GdipPropertyItem(); pi.id = propitem.Id; pi.len = propitem.Len; pi.type = propitem.Type; Marshal.Copy(propitem.Value, 0, dest, size); pi.value = dest; unsafe { int status = Gdip.GdipSetPropertyItem(nativeImage, &pi); Gdip.CheckStatus(status); } } finally { Marshal.FreeHGlobal(dest); } } [Browsable(false)] public ColorPalette Palette { get { return retrieveGDIPalette(); } set { storeGDIPalette(value); } } internal ColorPalette retrieveGDIPalette() { int bytes; ColorPalette ret = new ColorPalette(); int st = Gdip.GdipGetImagePaletteSize(nativeImage, out bytes); Gdip.CheckStatus(st); IntPtr palette_data = Marshal.AllocHGlobal(bytes); try { st = Gdip.GdipGetImagePalette(nativeImage, palette_data, bytes); Gdip.CheckStatus(st); ret.ConvertFromMemory(palette_data); return ret; } finally { Marshal.FreeHGlobal(palette_data); } } internal void storeGDIPalette(ColorPalette palette) { if (palette == null) { throw new ArgumentNullException(nameof(palette)); } IntPtr palette_data = palette.ConvertToMemory(); if (palette_data == IntPtr.Zero) { return; } try { int st = Gdip.GdipSetImagePalette(nativeImage, palette_data); Gdip.CheckStatus(st); } finally { Marshal.FreeHGlobal(palette_data); } } [Browsable(false)] public int[] PropertyIdList { get { uint propNumbers; int status = Gdip.GdipGetPropertyCount(nativeImage, out propNumbers); Gdip.CheckStatus(status); int[] idList = new int[propNumbers]; status = Gdip.GdipGetPropertyIdList(nativeImage, propNumbers, idList); Gdip.CheckStatus(status); return idList; } } [Browsable(false)] public PropertyItem[] PropertyItems { get { int propNums, propsSize, propSize; IntPtr properties, propPtr; PropertyItem[] items; GdipPropertyItem gdipProperty = new GdipPropertyItem(); int status; status = Gdip.GdipGetPropertySize(nativeImage, out propsSize, out propNums); Gdip.CheckStatus(status); items = new PropertyItem[propNums]; if (propNums == 0) return items; /* Get PropertyItem list*/ properties = Marshal.AllocHGlobal(propsSize * propNums); try { status = Gdip.GdipGetAllPropertyItems(nativeImage, propsSize, propNums, properties); Gdip.CheckStatus(status); propSize = Marshal.SizeOf(gdipProperty); propPtr = properties; for (int i = 0; i < propNums; i++, propPtr = new IntPtr(propPtr.ToInt64() + propSize)) { gdipProperty = (GdipPropertyItem)Marshal.PtrToStructure (propPtr, typeof(GdipPropertyItem)); items[i] = new PropertyItem(); GdipPropertyItem.MarshalTo(gdipProperty, items[i]); } } finally { Marshal.FreeHGlobal(properties); } return items; } } protected virtual void Dispose(bool disposing) { if (nativeImage != IntPtr.Zero) { int status = Gdip.GdipDisposeImage(nativeImage); // ... set nativeImage to null before (possibly) throwing an exception nativeImage = IntPtr.Zero; Gdip.CheckStatus(status); } } public object Clone() { IntPtr newimage = IntPtr.Zero; int status = Gdip.GdipCloneImage(nativeImage, out newimage); Gdip.CheckStatus(status); if (this is Bitmap) return new Bitmap(newimage); else return new Metafile(newimage); } internal static void ValidateImage(IntPtr bitmap) { // No validation is performed on Unix. } } }
// MIT License // // Copyright (c) 2009-2017 Luca Piccioni // // 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. // // This file is automatically generated #pragma warning disable 649, 1572, 1573 // ReSharper disable RedundantUsingDirective using System; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Text; using Khronos; // ReSharper disable CheckNamespace // ReSharper disable InconsistentNaming // ReSharper disable JoinDeclarationAndInitializer namespace OpenGL { public partial class Gl { /// <summary> /// [GL] Value of GL_MESH_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_SHADER_NV = 0x9559; /// <summary> /// [GL] Value of GL_TASK_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int TASK_SHADER_NV = 0x955A; /// <summary> /// [GL] Value of GL_MAX_MESH_UNIFORM_BLOCKS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_UNIFORM_BLOCKS_NV = 0x8E60; /// <summary> /// [GL] Value of GL_MAX_MESH_TEXTURE_IMAGE_UNITS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_TEXTURE_IMAGE_UNITS_NV = 0x8E61; /// <summary> /// [GL] Value of GL_MAX_MESH_IMAGE_UNIFORMS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_IMAGE_UNIFORMS_NV = 0x8E62; /// <summary> /// [GL] Value of GL_MAX_MESH_UNIFORM_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_UNIFORM_COMPONENTS_NV = 0x8E63; /// <summary> /// [GL] Value of GL_MAX_MESH_ATOMIC_COUNTER_BUFFERS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_ATOMIC_COUNTER_BUFFERS_NV = 0x8E64; /// <summary> /// [GL] Value of GL_MAX_MESH_ATOMIC_COUNTERS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_ATOMIC_COUNTERS_NV = 0x8E65; /// <summary> /// [GL] Value of GL_MAX_MESH_SHADER_STORAGE_BLOCKS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_SHADER_STORAGE_BLOCKS_NV = 0x8E66; /// <summary> /// [GL] Value of GL_MAX_COMBINED_MESH_UNIFORM_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_COMBINED_MESH_UNIFORM_COMPONENTS_NV = 0x8E67; /// <summary> /// [GL] Value of GL_MAX_TASK_UNIFORM_BLOCKS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_UNIFORM_BLOCKS_NV = 0x8E68; /// <summary> /// [GL] Value of GL_MAX_TASK_TEXTURE_IMAGE_UNITS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_TEXTURE_IMAGE_UNITS_NV = 0x8E69; /// <summary> /// [GL] Value of GL_MAX_TASK_IMAGE_UNIFORMS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_IMAGE_UNIFORMS_NV = 0x8E6A; /// <summary> /// [GL] Value of GL_MAX_TASK_UNIFORM_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_UNIFORM_COMPONENTS_NV = 0x8E6B; /// <summary> /// [GL] Value of GL_MAX_TASK_ATOMIC_COUNTER_BUFFERS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_ATOMIC_COUNTER_BUFFERS_NV = 0x8E6C; /// <summary> /// [GL] Value of GL_MAX_TASK_ATOMIC_COUNTERS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_ATOMIC_COUNTERS_NV = 0x8E6D; /// <summary> /// [GL] Value of GL_MAX_TASK_SHADER_STORAGE_BLOCKS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_SHADER_STORAGE_BLOCKS_NV = 0x8E6E; /// <summary> /// [GL] Value of GL_MAX_COMBINED_TASK_UNIFORM_COMPONENTS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_COMBINED_TASK_UNIFORM_COMPONENTS_NV = 0x8E6F; /// <summary> /// [GL] Value of GL_MAX_MESH_WORK_GROUP_INVOCATIONS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_WORK_GROUP_INVOCATIONS_NV = 0x95A2; /// <summary> /// [GL] Value of GL_MAX_TASK_WORK_GROUP_INVOCATIONS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_WORK_GROUP_INVOCATIONS_NV = 0x95A3; /// <summary> /// [GL] Value of GL_MAX_MESH_TOTAL_MEMORY_SIZE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_TOTAL_MEMORY_SIZE_NV = 0x9536; /// <summary> /// [GL] Value of GL_MAX_TASK_TOTAL_MEMORY_SIZE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_TOTAL_MEMORY_SIZE_NV = 0x9537; /// <summary> /// [GL] Value of GL_MAX_MESH_OUTPUT_VERTICES_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_OUTPUT_VERTICES_NV = 0x9538; /// <summary> /// [GL] Value of GL_MAX_MESH_OUTPUT_PRIMITIVES_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_OUTPUT_PRIMITIVES_NV = 0x9539; /// <summary> /// [GL] Value of GL_MAX_TASK_OUTPUT_COUNT_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_OUTPUT_COUNT_NV = 0x953A; /// <summary> /// [GL] Value of GL_MAX_DRAW_MESH_TASKS_COUNT_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_DRAW_MESH_TASKS_COUNT_NV = 0x953D; /// <summary> /// [GL] Value of GL_MAX_MESH_VIEWS_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_VIEWS_NV = 0x9557; /// <summary> /// [GL] Value of GL_MESH_OUTPUT_PER_VERTEX_GRANULARITY_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_OUTPUT_PER_VERTEX_GRANULARITY_NV = 0x92DF; /// <summary> /// [GL] Value of GL_MESH_OUTPUT_PER_PRIMITIVE_GRANULARITY_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_OUTPUT_PER_PRIMITIVE_GRANULARITY_NV = 0x9543; /// <summary> /// [GL] Value of GL_MAX_MESH_WORK_GROUP_SIZE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_MESH_WORK_GROUP_SIZE_NV = 0x953B; /// <summary> /// [GL] Value of GL_MAX_TASK_WORK_GROUP_SIZE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MAX_TASK_WORK_GROUP_SIZE_NV = 0x953C; /// <summary> /// [GL] Value of GL_MESH_WORK_GROUP_SIZE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_WORK_GROUP_SIZE_NV = 0x953E; /// <summary> /// [GL] Value of GL_TASK_WORK_GROUP_SIZE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int TASK_WORK_GROUP_SIZE_NV = 0x953F; /// <summary> /// [GL] Value of GL_MESH_VERTICES_OUT_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_VERTICES_OUT_NV = 0x9579; /// <summary> /// [GL] Value of GL_MESH_PRIMITIVES_OUT_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_PRIMITIVES_OUT_NV = 0x957A; /// <summary> /// [GL] Value of GL_MESH_OUTPUT_TYPE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_OUTPUT_TYPE_NV = 0x957B; /// <summary> /// [GL] Value of GL_UNIFORM_BLOCK_REFERENCED_BY_MESH_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int UNIFORM_BLOCK_REFERENCED_BY_MESH_SHADER_NV = 0x959C; /// <summary> /// [GL] Value of GL_UNIFORM_BLOCK_REFERENCED_BY_TASK_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int UNIFORM_BLOCK_REFERENCED_BY_TASK_SHADER_NV = 0x959D; /// <summary> /// [GL] Value of GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_MESH_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int ATOMIC_COUNTER_BUFFER_REFERENCED_BY_MESH_SHADER_NV = 0x959E; /// <summary> /// [GL] Value of GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TASK_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TASK_SHADER_NV = 0x959F; /// <summary> /// [GL] Value of GL_REFERENCED_BY_MESH_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int REFERENCED_BY_MESH_SHADER_NV = 0x95A0; /// <summary> /// [GL] Value of GL_REFERENCED_BY_TASK_SHADER_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int REFERENCED_BY_TASK_SHADER_NV = 0x95A1; /// <summary> /// [GL] Value of GL_MESH_SUBROUTINE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_SUBROUTINE_NV = 0x957C; /// <summary> /// [GL] Value of GL_TASK_SUBROUTINE_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int TASK_SUBROUTINE_NV = 0x957D; /// <summary> /// [GL] Value of GL_MESH_SUBROUTINE_UNIFORM_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int MESH_SUBROUTINE_UNIFORM_NV = 0x957E; /// <summary> /// [GL] Value of GL_TASK_SUBROUTINE_UNIFORM_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public const int TASK_SUBROUTINE_UNIFORM_NV = 0x957F; /// <summary> /// [GL] Value of GL_MESH_SHADER_BIT_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [Log(BitmaskName = "GL")] public const uint MESH_SHADER_BIT_NV = 0x00000040; /// <summary> /// [GL] Value of GL_TASK_SHADER_BIT_NV symbol. /// </summary> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [Log(BitmaskName = "GL")] public const uint TASK_SHADER_BIT_NV = 0x00000080; /// <summary> /// [GL] glDrawMeshTasksNV: Binding for glDrawMeshTasksNV. /// </summary> /// <param name="first"> /// A <see cref="T:uint"/>. /// </param> /// <param name="count"> /// A <see cref="T:uint"/>. /// </param> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public static void DrawMeshNV(uint first, uint count) { Debug.Assert(Delegates.pglDrawMeshTasksNV != null, "pglDrawMeshTasksNV not implemented"); Delegates.pglDrawMeshTasksNV(first, count); LogCommand("glDrawMeshTasksNV", null, first, count ); DebugCheckErrors(null); } /// <summary> /// [GL] glDrawMeshTasksIndirectNV: Binding for glDrawMeshTasksIndirectNV. /// </summary> /// <param name="indirect"> /// A <see cref="T:IntPtr"/>. /// </param> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public static void DrawMeshTasksIndirectNV(IntPtr indirect) { Debug.Assert(Delegates.pglDrawMeshTasksIndirectNV != null, "pglDrawMeshTasksIndirectNV not implemented"); Delegates.pglDrawMeshTasksIndirectNV(indirect); LogCommand("glDrawMeshTasksIndirectNV", null, indirect ); DebugCheckErrors(null); } /// <summary> /// [GL] glMultiDrawMeshTasksIndirectNV: Binding for glMultiDrawMeshTasksIndirectNV. /// </summary> /// <param name="indirect"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="drawcount"> /// A <see cref="T:int"/>. /// </param> /// <param name="stride"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public static void MultiDrawMeshTasksIndirectNV(IntPtr indirect, int drawcount, int stride) { Debug.Assert(Delegates.pglMultiDrawMeshTasksIndirectNV != null, "pglMultiDrawMeshTasksIndirectNV not implemented"); Delegates.pglMultiDrawMeshTasksIndirectNV(indirect, drawcount, stride); LogCommand("glMultiDrawMeshTasksIndirectNV", null, indirect, drawcount, stride ); DebugCheckErrors(null); } /// <summary> /// [GL] glMultiDrawMeshTasksIndirectCountNV: Binding for glMultiDrawMeshTasksIndirectCountNV. /// </summary> /// <param name="indirect"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="drawcount"> /// A <see cref="T:IntPtr"/>. /// </param> /// <param name="maxdrawcount"> /// A <see cref="T:int"/>. /// </param> /// <param name="stride"> /// A <see cref="T:int"/>. /// </param> [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] public static void MultiDrawMeshTasksIndirectCountNV(IntPtr indirect, IntPtr drawcount, int maxdrawcount, int stride) { Debug.Assert(Delegates.pglMultiDrawMeshTasksIndirectCountNV != null, "pglMultiDrawMeshTasksIndirectCountNV not implemented"); Delegates.pglMultiDrawMeshTasksIndirectCountNV(indirect, drawcount, maxdrawcount, stride); LogCommand("glMultiDrawMeshTasksIndirectCountNV", null, indirect, drawcount, maxdrawcount, stride ); DebugCheckErrors(null); } internal static unsafe partial class Delegates { [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glDrawMeshTasksNV(uint first, uint count); [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [ThreadStatic] internal static glDrawMeshTasksNV pglDrawMeshTasksNV; [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glDrawMeshTasksIndirectNV(IntPtr indirect); [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [ThreadStatic] internal static glDrawMeshTasksIndirectNV pglDrawMeshTasksIndirectNV; [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glMultiDrawMeshTasksIndirectNV(IntPtr indirect, int drawcount, int stride); [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [ThreadStatic] internal static glMultiDrawMeshTasksIndirectNV pglMultiDrawMeshTasksIndirectNV; [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [SuppressUnmanagedCodeSecurity] internal delegate void glMultiDrawMeshTasksIndirectCountNV(IntPtr indirect, IntPtr drawcount, int maxdrawcount, int stride); [RequiredByFeature("GL_NV_mesh_shader", Api = "gl|glcore")] [ThreadStatic] internal static glMultiDrawMeshTasksIndirectCountNV pglMultiDrawMeshTasksIndirectCountNV; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Xml; using SIL.Archiving.Generic; using SIL.Archiving.IMDI.Schema; using SIL.Extensions; using SIL.WritingSystems; namespace SIL.Archiving.IMDI.Lists { /// <summary>Generic class to handle items in the IMDI lists</summary> public class IMDIListItem : IComparable { /// <summary>Suitable for display to the user (potentially localized)</summary> public string Text { get; protected set; } /// <summary>Value suitable for storing in metadata files</summary> public string Value { get; private set; } /// <summary>Description to the user (often the same as the text)</summary> public string Definition { get; private set; } /// <summary>Constructor</summary> /// <param name="value">Value suitable for storing in metadata files</param> /// <param name="definition">Description to the user (often the same as the Text)</param> public IMDIListItem(string value, string definition) { Text = value; Value = value; // most of the time InnerText is empty - use the "Value" attribute for both if it is empty Definition = string.IsNullOrEmpty(definition) ? value : definition; } public override string ToString() { return Text; } /// <summary>Convert to VocabularyType</summary> public VocabularyType ToVocabularyType(VocabularyTypeValueType vocabularyType, string link) { return new VocabularyType { Type = vocabularyType, Value = Value, Link = link }; } /// <summary>Convert to BooleanType</summary> public BooleanType ToBooleanType() { BooleanEnum boolEnum; return Enum.TryParse(Value, true, out boolEnum) ? new BooleanType { Type = VocabularyTypeValueType.ClosedVocabulary, Value = boolEnum, Link = ListType.Link(ListType.Boolean) } : new BooleanType { Type = VocabularyTypeValueType.ClosedVocabulary, Value = BooleanEnum.Unknown, Link = ListType.Link(ListType.Boolean) }; } /// <summary> /// Localize the Text and Definition using the given localize function /// </summary> /// <param name="listName">The name of the list containing this item</param> /// <param name="localize">Delegate to use for getting localized versions of the Text and /// Definition of list items. The parameters are: 1) the list name; 2) list item value; /// 3) "Definition" or "Text"; 4) default (English) value.</param> internal void Localize(string listName, Func<string, string, string, string, string> localize) { if (localize != null && !string.IsNullOrEmpty(Value)) { if (Text == Definition) { Text = Definition = localize(listName, Value, "Text", Text); } else { Text = localize(listName, Value, "Text", Text); Definition = localize(listName, Value, "Definition", Definition); } } } /// <summary>Used for sorting. Compare 2 IMDIListItem objects. They are identical if the Text properties are the same</summary> public int CompareTo(object obj) { if (obj == null) return 1; IMDIListItem other = obj as IMDIListItem; if (other == null) throw new ArgumentException(); // handle special cases var thisValue = CheckSpecialCase(this); var thatValue = CheckSpecialCase(other); // compare the Text properties return String.Compare(thisValue, thatValue, StringComparison.InvariantCultureIgnoreCase); } /// <summary>Used for sorting. Compare 2 IMDIListItem objects. They are identical if the Text properties are the same</summary> public static int Compare(IMDIListItem itemA, IMDIListItem itemB) { return itemA.CompareTo(itemB); } /// <summary>This allows forcing specific entries to the top of the sort order</summary> private static string CheckSpecialCase(IMDIListItem inputValue) { switch (inputValue.Value) { case null: case "": return "A"; case "Unknown": return "B"; case "Undefined": return "C"; case "Unspecified": return "D"; } return "Z" + inputValue.Text; } } /// <summary> /// A list of IMDI list items, constructed using the imdi:Entry Nodes from the XML file. /// <example> /// Example 1: /// ---------- /// var lc = IMDI_Schema.ListConstructor.GetList(ListType.MPILanguages); /// comboBox1.Items.AddRange(lc.ToArray()); /// </example> /// <example> /// Example 2: /// ---------- /// var lc = IMDI_Schema.ListConstructor.GetList(ListType.MPILanguages); /// comboBox1.DataSource = lc; /// comboBox1.DisplayMember = "Text"; /// comboBox1.ValueMember = "Value"; /// </example> /// </summary> public class IMDIItemList : List<IMDIListItem> { private static string _listPath; private readonly string _listname; private bool _closed; /// --------------------------------------------------------------------------------------- public bool Closed { get { return _closed; } internal set { if (_closed && !value) throw new InvalidOperationException("Existing closed list cannot be made open!"); _closed = value; } } /// --------------------------------------------------------------------------------------- /// <summary>Constructs a list of IMDIListItems that can be used as the data source of a /// combo or list box</summary> /// <param name="listName">Name of the XML file that contains the desired list. It is suggested to /// use values from IMDI_Schema.ListTypes class. If not found on the local system, we will attempt /// to download from http://www.mpi.nl/IMDI/Schema. /// </param> /// <param name="uppercaseFirstCharacter">Make first character of each item uppercase</param> internal IMDIItemList(string listName, bool uppercaseFirstCharacter) : this(listName, uppercaseFirstCharacter, ListConstructor.RemoveUnknown.RemoveNone) { } /// --------------------------------------------------------------------------------------- /// <summary>Constructs a list of IMDIListItems that can be used as the data source of a /// combo or list box</summary> /// <param name="listName">Name of the XML file that contains the desired list. It is suggested to /// use values from IMDI_Schema.ListTypes class. If not found on the local system, we will attempt /// to download from http://www.mpi.nl/IMDI/Schema. /// </param> /// <param name="uppercaseFirstCharacter">Make first character of each item uppercase</param> /// <param name="removeUnknown">Specify which values of "unknown" to remove</param> internal IMDIItemList(string listName, bool uppercaseFirstCharacter, ListConstructor.RemoveUnknown removeUnknown) { Debug.Assert(listName.EndsWith(".xml")); _listname = listName.Substring(0, listName.Length - 4); if (listName == "MPI-Languages.xml") { // This file is woefully incomplete (only ~345 languages, less than 5% of the total). A comment inside it even says // "When a language name and identifier that you need is not in this list, please look it up under www.ethnologue.com/web.asp.". // So we use the information from SIL.WritingSystems, which is based on the complete Ethnologue data. AddLanguagesFromEthnologue(); } else { PopulateList(GetNodeList(listName), uppercaseFirstCharacter, removeUnknown); } InitializeThis(); } private void AddLanguagesFromEthnologue() { // We won't worry about how slow list lookup is with thousands of languages because we'll only // be looking up a few languages in all likelihood. Storing the names in a list that is searched // linearly does ensure matching on the major name of a language which happens to match an alias // for another language. It also ensures returning the major (English) name of the language when // looked up by ISO code. var langLookup = new LanguageLookup(); var languages = langLookup.SuggestLanguages("*").ToList(); foreach (var lang in languages) { if (lang.ThreeLetterTag == null || lang.ThreeLetterTag.Length != 3) continue; // Data includes codes like "pt-PT" and "zh-Hans": ignore those for now. AddItem(GetEnglishName(lang), "ISO639-3:" + lang.ThreeLetterTag); } foreach (var lang in languages) { if (lang.ThreeLetterTag == null || lang.ThreeLetterTag.Length != 3) continue; // Data includes codes like "pt-PT" and "zh-Hans": ignore those for now. foreach (var name in lang.Names) { if (name != GetEnglishName(lang)) AddItem(name, "ISO639-3:" + lang.ThreeLetterTag); } } } private static string GetEnglishName(LanguageInfo lang) { // For these languages, the data gives the language name in its own language and script first, // which is great for UI choosers. For IMDI, we prefer the English name as the default. switch (lang.ThreeLetterTag) { case "ara": return "Arabic"; case "ben": return "Bengali"; case "fra": return "French"; case "spa": return "Spanish"; case "tam": return "Tamil"; case "tel": return "Telugu"; case "tha": return "Thai"; case "urd": return "Urdu"; case "zho": return "Chinese"; // DesiredName is either the name the user prefers, or the first (and possibly only) name in the Names list. default: return lang.DesiredName; } } private void InitializeThis() { Initialize(); } /// --------------------------------------------------------------------------------------- protected virtual void Initialize() { // Add blank option Insert(0, new IMDIListItem(string.Empty, string.Empty)); } /// <summary>Gets a list of the Entry nodes from the selected XML file.</summary> /// <param name="listName">Name of the XML file that contains the desired list. It is suggested to /// use values from IMDI_Schema.ListTypes class. If not found on the local system, we will attempt /// to download from http://www.mpi.nl/IMDI/Schema. /// </param> /// <returns></returns> private XmlNodeList GetNodeList(string listName) { var listFileName = CheckFile(listName); // if the file was not found, throw an exception if (string.IsNullOrEmpty(listFileName)) throw new FileNotFoundException($"The list {listName} was not found."); XmlDocument doc = new XmlDocument(); doc.Load(listFileName); var nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("imdi", "http://www.mpi.nl/IMDI/Schema/IMDI"); // if not a valid XML file, throw an exception if (doc.DocumentElement == null) throw new XmlException($"The file {listFileName} was not a valid XML file."); var nodes = doc.DocumentElement.SelectNodes("//imdi:VocabularyDef/imdi:Entry", nsmgr); // if no entries were found, throw an exception if (nodes == null || nodes.Count == 0) throw new XmlException(string.Format($"The file {listFileName} does not contain any list entries. There might be a problem with the content at {ListType.Link(listName)}")); return nodes; } /// --------------------------------------------------------------------------------------- private static string CheckFile(string listName) { var listFileName = Path.Combine(ListPath, listName); // if file already exists locally, return it now if (File.Exists(listFileName)) return listFileName; // attempt to download if not already in list folder var url = ListType.Link(listName); Debug.WriteLine("Downloading from {0} to {1}", url, listFileName); var wc = new WebClient(); wc.DownloadFile(url, listFileName); // return full name, or null if not able to download return File.Exists(listFileName) ? listFileName : null; } /// --------------------------------------------------------------------------------------- private static string ListPath { get { if (!string.IsNullOrEmpty(_listPath)) return _listPath; var thisPath = ArchivingFileSystem.SilCommonIMDIDataFolder; // check if path exists if (!Directory.Exists(thisPath)) throw new DirectoryNotFoundException("Not able to find the IMDI lists directory."); _listPath = thisPath; return _listPath; } } /// --------------------------------------------------------------------------------------- public virtual void Localize(Func<string, string, string, string, string> localize) { if (localize != null) { foreach (var itm in this) itm.Localize(_listname, localize); } } /// --------------------------------------------------------------------------------------- protected void PopulateList(XmlNodeList nodes, bool uppercaseFirstCharacter, ListConstructor.RemoveUnknown removeUnknown) { foreach (XmlNode node in nodes) { if (node.Attributes == null) continue; var value = node.Attributes["Value"].Value; // the "Value" attribute contains the meta-data value to save switch (value.ToLower()) { case "unknown": if (removeUnknown == ListConstructor.RemoveUnknown.RemoveAll) continue; break; case "unspecified": case "undetermined": case "undefined": if (removeUnknown != ListConstructor.RemoveUnknown.RemoveNone) continue; break; } var definition = node.InnerText.Replace("Definition:", "").Replace("\t", " ").Replace("\r", "").Replace("\n", " ").Trim(); // if InnerText is set, it may contain the value for the meta-data file (some files do, some don't) if (uppercaseFirstCharacter && !string.IsNullOrEmpty(value) && (value.Substring(0, 1) != value.Substring(0, 1).ToUpper())) { value = value.ToUpperFirstLetter(); } AddItem(value, definition); } } /// --------------------------------------------------------------------------------------- public virtual void AddItem(string value, string definition) { Add(new IMDIListItem(value, definition)); } /// --------------------------------------------------------------------------------------- /// <summary>Returns the first item found with the given Value. If not found in a closed list, the /// "Unspecified" item will be returned; otherwise returns null.</summary> /// <param name="value">The meta-data value of the item to find</param> public IMDIListItem FindByValue(string value) { try { return this.First(i => String.Equals(i.Value, value, StringComparison.CurrentCultureIgnoreCase)); } catch { return Closed ? this.FirstOrDefault(i => String.Equals(i.Value, "Unspecified", StringComparison.CurrentCultureIgnoreCase)) : null; } } /// <summary>Returns the first item found with the given Text, or null if not found</summary> /// <param name="text">The (potentially localized) UI text of the item to find</param> public IMDIListItem FindByText(string text) { var itm = this.FirstOrDefault(i => String.Equals(i.Text, text, StringComparison.CurrentCultureIgnoreCase)); return itm; } } }
/* * Attribute.cs - Implementation of the "System.Attribute" class. * * Copyright (C) 2001 Southern Storm Software, Pty Ltd. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System { using System.Reflection; [AttributeUsage(AttributeTargets.All, Inherited=true, AllowMultiple=false)] public abstract class Attribute { // Constructor. protected Attribute() { // Nothing to do here. } #if CONFIG_REFLECTION // Determine if two attributes are equal. [ClrReflection] public override bool Equals(Object value) { Type type1; Type type2; // The value must not be null. if(value == null) { return false; } // The types must be equal. type1 = GetType(); type2 = value.GetType(); if(type1 != type2) { return false; } // All fields must be identical. Because of // the "ClrReflection" attribute on this method, // the runtime engine will allow us to access // every field, including private fields. FieldInfo[] fields = type1.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // Check each of the fields for equality in turn. int posn; Object value1; Object value2; for(posn = 0; posn < fields.Length; ++posn) { value1 = fields[posn].GetValue(this); value2 = fields[posn].GetValue(value); if(value1 == null) { if(value2 != null) { return false; } } else if(value2 == null) { return false; } else if(!value1.Equals(value2)) { return false; } } return true; } // Get the hash value for this instance. [ClrReflection] public override int GetHashCode() { // Use the hash value for the first non-null field. // The "ClrReflection" attribute will allow us to // access the private internals of the value. FieldInfo[] fields = GetType().GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); int posn; Object value; for(posn = 0; posn < fields.Length; ++posn) { value = fields[posn].GetValue(this); if(value != null) { return value.GetHashCode(); } } // There are no non-null fields, so hash the type instead. return GetType().GetHashCode(); } // Get a single attribute associated with a particular program item. private static Attribute GetAttr(ICustomAttributeProvider element, Type attributeType, bool inherit) { Object[] attrs; if(element == null) { throw new ArgumentNullException("element"); } if(attributeType == null) { throw new ArgumentNullException("attributeType"); } attrs = element.GetCustomAttributes(attributeType, inherit); if(attrs == null || attrs.Length < 1) { return null; } else if(attrs.Length == 1) { return (Attribute)(attrs[0]); } else { throw new AmbiguousMatchException (_("Reflection_AmbiguousAttr")); } } // Get all attributes associated with a particular program item. private static Attribute[] GetAllAttrs(ICustomAttributeProvider element, bool inherit) { Object[] attrs; Attribute[] newAttrs; if(element == null) { throw new ArgumentNullException("element"); } attrs = element.GetCustomAttributes(inherit); if(attrs == null) { return null; } else { newAttrs = new Attribute [attrs.Length]; int posn; for(posn = 0; posn < attrs.Length; ++posn) { newAttrs[posn] = (Attribute)(attrs[posn]); } return newAttrs; } } // Get all attributes associated with a particular program item, // that are defined to be of a particular type. private static Attribute[] GetAttrs(ICustomAttributeProvider element, Type attributeType, bool inherit) { Object[] attrs; Attribute[] newAttrs; if(element == null) { throw new ArgumentNullException("element"); } if(attributeType == null) { throw new ArgumentNullException("attributeType"); } attrs = element.GetCustomAttributes(attributeType, inherit); if(attrs == null) { return null; } else { newAttrs = new Attribute [attrs.Length]; int posn; for(posn = 0; posn < attrs.Length; ++posn) { newAttrs[posn] = (Attribute)(attrs[posn]); } return newAttrs; } } // Determine if an attribute is defined on a particular program item. private static bool IsAttrDefined(ICustomAttributeProvider element, Type attributeType, bool inherit) { if(element == null) { throw new ArgumentNullException("element"); } if(attributeType == null) { throw new ArgumentNullException("attributeType"); } return element.IsDefined(attributeType, inherit); } // Get an attribute that is associated with a particular program item. public static Attribute GetCustomAttribute(Module element, Type attributeType) { return GetAttr(element, attributeType, true); } public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType) { return GetAttr(element, attributeType, true); } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType) { return GetAttr(element, attributeType, true); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType) { return GetAttr(element, attributeType, true); } #if !ECMA_COMPAT // Get an attribute that is associated with a particular program item. public static Attribute GetCustomAttribute(Module element, Type attributeType, bool inherit) { return GetAttr(element, attributeType, inherit); } public static Attribute GetCustomAttribute(ParameterInfo element, Type attributeType, bool inherit) { return GetAttr(element, attributeType, inherit); } public static Attribute GetCustomAttribute(MemberInfo element, Type attributeType, bool inherit) { return GetAttr(element, attributeType, inherit); } public static Attribute GetCustomAttribute(Assembly element, Type attributeType, bool inherit) { return GetAttr(element, attributeType, inherit); } #endif // !ECMA_COMPAT // Get all attributes that are associated with a particular program item. public static Attribute[] GetCustomAttributes(Assembly element) { return GetAllAttrs(element, true); } public static Attribute[] GetCustomAttributes(Module element) { return GetAllAttrs(element, true); } public static Attribute[] GetCustomAttributes(ParameterInfo element) { return GetAllAttrs(element, true); } public static Attribute[] GetCustomAttributes(MemberInfo element) { return GetAllAttrs(element, true); } #if !ECMA_COMPAT // Get all attributes that are associated with a particular program item. public static Attribute[] GetCustomAttributes(Assembly element, bool inherit) { return GetAllAttrs(element, inherit); } public static Attribute[] GetCustomAttributes(Module element, bool inherit) { return GetAllAttrs(element, inherit); } public static Attribute[] GetCustomAttributes(ParameterInfo element, bool inherit) { return GetAllAttrs(element, inherit); } public static Attribute[] GetCustomAttributes(MemberInfo element, bool inherit) { return GetAllAttrs(element, inherit); } #endif // !ECMA_COMPAT // Get all attributes that are associated with a particular program item, // and which have a specific type. public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType) { return GetAttrs(element, attributeType, true); } public static Attribute[] GetCustomAttributes (MemberInfo element, Type attributeType) { return GetAttrs(element, attributeType, true); } public static Attribute[] GetCustomAttributes (Module element, Type attributeType) { return GetAttrs(element, attributeType, true); } public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType) { return GetAttrs(element, attributeType, true); } #if !ECMA_COMPAT // Get all attributes that are associated with a particular program item, // and which have a specific type. public static Attribute[] GetCustomAttributes (ParameterInfo element, Type attributeType, bool inherit) { return GetAttrs(element, attributeType, inherit); } public static Attribute[] GetCustomAttributes (MemberInfo element, Type attributeType, bool inherit) { return GetAttrs(element, attributeType, inherit); } public static Attribute[] GetCustomAttributes (Module element, Type attributeType, bool inherit) { return GetAttrs(element, attributeType, inherit); } public static Attribute[] GetCustomAttributes (Assembly element, Type attributeType, bool inherit) { return GetAttrs(element, attributeType, inherit); } #endif // !ECMA_COMPAT // Determine if an attribute is defined on a particular program item. public static bool IsDefined(MemberInfo element, Type attributeType) { return IsAttrDefined(element, attributeType, true); } public static bool IsDefined(Module element, Type attributeType) { return IsAttrDefined(element, attributeType, true); } public static bool IsDefined(Assembly element, Type attributeType) { return IsAttrDefined(element, attributeType, true); } public static bool IsDefined(ParameterInfo element, Type attributeType) { return IsAttrDefined(element, attributeType, true); } #if !ECMA_COMPAT // Determine if an attribute is defined on a particular program item. public static bool IsDefined(MemberInfo element, Type attributeType, bool inherit) { return IsAttrDefined(element, attributeType, inherit); } public static bool IsDefined(Module element, Type attributeType, bool inherit) { return IsAttrDefined(element, attributeType, inherit); } public static bool IsDefined(Assembly element, Type attributeType, bool inherit) { return IsAttrDefined(element, attributeType, inherit); } public static bool IsDefined(ParameterInfo element, Type attributeType, bool inherit) { return IsAttrDefined(element, attributeType, inherit); } #endif // !ECMA_COMPAT #endif // CONFIG_REFLECTION #if !ECMA_COMPAT // Get a type identifier for this attribute's type. public virtual Object TypeId { get { return GetType(); } } // Determine if this attribute is a default value. public virtual bool IsDefaultAttribute() { return false; } // Match this attribute against another. public virtual bool Match(Object obj) { return Equals(obj); } #endif // !ECMA_COMPAT }; // class Attribute }; // namespace System
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel.Design; using System.Linq; using System.Reflection; #if NETFRAMEWORK using System.Runtime.Remoting.Messaging; #endif using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json.Linq; namespace StackifyLib.Utils { public class HelperFunctions { static List<string> _BadTypes = new List<string>() { "log4net.Util.SystemStringFormat", "System.Object[]" }; static JsonSerializerSettings serializerSettings = new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, Converters = new List<JsonConverter>() { new ToStringConverter("Module", typeof(Module)), new ToStringConverter("Method", typeof(MemberInfo)), new ToStringConverter("Assembly", typeof(Assembly)), } }; static JsonSerializer serializer = JsonSerializer.Create(serializerSettings); /// <summary> /// Trying to serialize something that the user passed in. Sometimes this is used to serialize what we know is additional debug and sometimes it is the primary logged item. This is why the serializeSimpleTypes exists. For additional debug stuff we always serialize it. For the primary logged object we won't because it doesn't make any sense to put a string in the json as well as the main message. It's meant for objects. /// </summary> /// <param name="logObject"></param> /// <param name="serializeSimpleTypes"></param> /// <param name="properties"></param> /// <returns></returns> public static string SerializeDebugData(object logObject, bool serializeSimpleTypes, Dictionary<string, object> properties = null) { Type t = null; JObject jObject = null; try { if (logObject == null) { } else { t = logObject.GetType(); #if NET40 var typeInfo = t; #else var typeInfo = t.GetTypeInfo(); #endif if (logObject is string || t.FullName == "log4net.Util.SystemStringFormat") { if (serializeSimpleTypes) { jObject = new JObject(); jObject.Add("logArg", new JValue(logObject.ToString())); } } else if (typeInfo.IsPrimitive || typeInfo.BaseType == typeof(ValueType)) { if (serializeSimpleTypes) { jObject = new JObject(); try { jObject.Add("logArg", new JValue(logObject)); } catch (ArgumentException) { jObject.Add("logArg", new JValue(logObject.ToString())); } } } //look for some things we don't want to touch else if (logObject is IDisposable)// || logObject is MarshalByRefObject) { } else if (!_BadTypes.Contains(t.ToString())) { var token = JToken.FromObject(logObject, serializer); if (token is JObject) { jObject = (JObject)token; var type = logObject.GetType(); //do we log the objectType? Not logging it for simple things if (typeInfo.IsPrimitive == false && type.Name != "String" && typeInfo.BaseType != typeof(ValueType) && type.Name.Contains("AnonymousType") == false && (type.FullName == null || type.FullName.Contains("System.Collections.Generic.Dictionary") == false)) { jObject.Add("objectType", type.FullName); } } else if (token is JArray) { jObject = new JObject(); jObject.Add("logArg", token); var type = logObject.GetType(); if (type.IsArray) { var array = (Array) logObject; if (array.Length > 0) { var child = array.GetValue(0); var childtype = child.GetType(); #if NET40 var childtypeinfo = childtype; #else var childtypeinfo = childtype.GetTypeInfo(); #endif if (childtypeinfo.IsPrimitive == false && childtype.Name != "String" && childtypeinfo.BaseType != typeof(ValueType)) { jObject.Add("objectType", childtype.FullName); } } } else { if (!typeInfo.ContainsGenericParameters) { jObject.Add("objectType", type.FullName); } else { #if NETFULL var genericArgs = typeInfo.GetGenericArguments(); #else var genericArgs = typeInfo.IsGenericTypeDefinition ? type.GetTypeInfo().GenericTypeParameters : type.GetTypeInfo().GenericTypeArguments; #endif if (genericArgs != null && genericArgs.Length > 0) { var childtype = genericArgs.First(); #if NET40 var childtypeinfo = childtype; #else var childtypeinfo = childtype.GetTypeInfo(); #endif if (childtypeinfo.IsPrimitive == false && childtype.Name != "String" && childtypeinfo.BaseType != typeof(ValueType)) { jObject.Add("objectType", childtype.FullName); } } else { jObject.Add("objectType", type.FullName); } } } } else if (token is JValue) { if (serializeSimpleTypes) { jObject = new JObject(); jObject.Add("logArg", token); } } } } } catch (Exception ex) { lock (_BadTypes) { _BadTypes.Add(t.ToString()); } Utils.StackifyAPILogger.Log(ex.ToString()); } string data = null; if (properties != null && properties.Count > 0) { if (jObject == null) { jObject = new JObject(); } JObject props = new JObject(); foreach (var prop in properties) { try { if (IsValueType(prop.Value)) { props.Add(prop.Key, new JValue(prop.Value)); } else { props.Add(prop.Key, JObject.FromObject(prop.Value, serializer)); } } catch (Exception ex) { StackifyAPILogger.Log(ex.ToString()); } } jObject.Add("context", props); } if (jObject != null) { jObject = GetPrunedObject(jObject, Config.LoggingJsonMaxFields); return JsonConvert.SerializeObject(jObject, serializerSettings); } return null; } /// <summary> /// If the <see cref="JObject"/> provided has move fields than maxFields /// will return a simplified <see cref="JObject"/> with original as an unparsed string message, /// otherwise will return original <see cref="JObject"/> /// </summary> private static JObject GetPrunedObject(JObject obj, int maxFields) { var fieldCount = GetFieldCount(obj); if (fieldCount > maxFields) { return new JObject { { "invalid", true }, { "message", obj.ToString() } }; } return obj; } private static int GetFieldCount(JToken obj) { switch (obj.Type) { case JTokenType.Array: case JTokenType.Object: return obj.Children().Sum(i => GetFieldCount(i)); case JTokenType.Property: return GetFieldCount(obj.Value<JProperty>().Value); default: return 1; } } public static bool IsValueType(object obj) { if (obj == null) return false; var t = obj.GetType(); #if NET40 return t.IsPrimitive || t.Equals(typeof(string)); #else return t.GetTypeInfo().IsPrimitive || t.Equals(typeof(string)); #endif } public static string CleanPartialUrl(string url) { if (string.IsNullOrEmpty(url) || !url.Contains("/")) return url; string[] urlPieces = url.Split(new char[] { '/' }); var sbNewUrl = new StringBuilder(url.Length); int index = 0; foreach (string piece in urlPieces) { if (string.IsNullOrEmpty(piece)) { continue; } long val; Guid guidval; if (long.TryParse(piece, out val)) { sbNewUrl.Append("/{id}"); } else if (Guid.TryParse(piece, out guidval)) { sbNewUrl.Append("/{guid}"); } else { sbNewUrl.AppendFormat("/{0}", piece); } index++; } if (url.EndsWith("/")) { sbNewUrl.Append("/"); } return sbNewUrl.ToString(); } public static string GetRequestId() { string reqId = null; #if NETFULL try { if (string.IsNullOrEmpty(reqId)) { var stackifyRequestID = CallContext.LogicalGetData("Stackify-RequestID"); if (stackifyRequestID != null) { reqId = stackifyRequestID.ToString(); } } if (string.IsNullOrEmpty(reqId)) { //gets from Trace.CorrelationManager.ActivityId but doesnt assume it is guid since it technically doesn't have to be //not calling the CorrelationManager method because it blows up if it isn't a guid var correltionManagerId = CallContext.LogicalGetData("E2ETrace.ActivityID"); if (correltionManagerId != null && correltionManagerId is Guid && ((Guid) correltionManagerId) != Guid.Empty) { reqId = correltionManagerId.ToString(); } } } catch (System.Web.HttpException ex) { StackifyAPILogger.Log("Request not available \r\n" + ex.ToString()); } catch (Exception ex) { StackifyAPILogger.Log("Error figuring out TransID \r\n" + ex.ToString()); } #endif try { if (string.IsNullOrEmpty(reqId)) { reqId = getContextProperty("RequestId") as string; } } catch (Exception ex) { StackifyAPILogger.Log("Error figuring out TransID \r\n" + ex.ToString()); } return reqId; } public static string GetReportingUrl() { return GetStackifyProperty("REPORTING_URL"); } public static string GetAppName() { if (!IsBeingProfiled) { return Config.AppName; } // Getting profiler app name and environment are a side effect of checking the profiler wrapper GetWrapperAssembly(); return _profilerAppName ?? Config.AppName; } public static string GetAppEnvironment() { if (!IsBeingProfiled) { return Config.AppName; } // Getting profiler app name and environment are a side effect of checking the profiler wrapper GetWrapperAssembly(); return _profilerEnvironment ?? Config.Environment; } private static Assembly _wrapperAssembly = null; private static Type _stackifyCallContextType = null; protected static Assembly GetWrapperAssembly() { if (!IsBeingProfiled) { return null; } if (_wrapperAssembly != null) { return _wrapperAssembly; } try { var assemblies = AppDomain.CurrentDomain.GetAssemblies(); var agentAssemblyQry = assemblies.Where(assembly => assembly.FullName.StartsWith("Stackify.Agent,")); foreach (var middleware in agentAssemblyQry) { var stackifyCallContextType = middleware?.GetType("Stackify.Agent.Threading.StackifyCallContext"); if (stackifyCallContextType != null) { GetProfilerAppNameAndEnvironment(middleware); _stackifyCallContextType = stackifyCallContextType; _wrapperAssembly = middleware; } } } catch { // Ignore errors } return _wrapperAssembly; } private static string _profilerAppName = null; private static string _profilerEnvironment = null; private static void GetProfilerAppNameAndEnvironment(Assembly middleware) { try { // Get AppName and Environment and cache them, so we won't query over and over. var agentConfigType = middleware?.GetType("Stackify.Agent.Configuration.AgentConfig"); if (agentConfigType != null) { var profilerSettings = agentConfigType.GetProperty("Settings")?.GetValue(null, null); if (profilerSettings != null) { var settingsType = profilerSettings.GetType(); _profilerAppName = settingsType?.GetProperty("AppName")?.GetValue(profilerSettings, null) as string; _profilerEnvironment = settingsType?.GetProperty("Environment")?.GetValue(profilerSettings, null) as string; } } } catch { // Ignore errors here } } private static object getContextProperty(string propName) { if (!IsBeingProfiled || string.IsNullOrWhiteSpace(propName)) { return null; } if (_wrapperAssembly == null) { GetWrapperAssembly(); } try { if (_stackifyCallContextType != null) { var traceContextProp = _stackifyCallContextType.GetProperty("TraceContext")?.GetValue(null, null); if (traceContextProp != null) { var traceContextType = traceContextProp.GetType(); var contextProp = traceContextType.GetProperty(propName); var propValue = contextProp?.GetValue(traceContextProp, null); return propValue; } } } catch { // Ignore errors } return null; } private static string GetStackifyProperty(string propName) { if (!IsBeingProfiled || string.IsNullOrWhiteSpace(propName)) { return null; } try { var stackifyProps = getContextProperty("props"); if (stackifyProps != null) { var propsType = stackifyProps.GetType(); var getItemMethod = propsType.GetMethod("get_Item", new[] {typeof(string)}); if (getItemMethod != null) { return getItemMethod.Invoke(stackifyProps, new[] {propName}) as string; } } } catch { // Ignore Errors } return null; } private static Boolean? _isBeingProfiled = null; protected static bool IsBeingProfiled { get { if (_isBeingProfiled.HasValue) { return _isBeingProfiled.Value; } #if NETFRAMEWORK var profilerEnv = "COR_ENABLE_PROFILING"; var profilerUuidEnv = "COR_PROFILER"; #else string profilerEnv = null; string profilerUuidEnv = null; // .Net Standard could be .Net Core or .Net Framework, so check var framework = System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription; if (string.IsNullOrEmpty(framework)) { return false; } if (framework.StartsWith(".NET Native", StringComparison.OrdinalIgnoreCase)) { // Native code can't be profiled return false; } else if (framework.StartsWith(".NET Framework", StringComparison.OrdinalIgnoreCase)) { profilerEnv = "COR_ENABLE_PROFILING"; profilerUuidEnv = "COR_PROFILER"; } else // Assume everything else is .Net Core current values would be .Net Core, .Net 5.x and .Net 6.x { profilerEnv = "CORECLR_ENABLE_PROFILING"; profilerUuidEnv = "CORECLR_PROFILER"; } if (profilerEnv == null || profilerUuidEnv == null) { // This code should be unreachable, but just in case the above checks are changed we handle it return false; } #endif var enableString = Environment.GetEnvironmentVariable(profilerEnv); var uuidString = Environment.GetEnvironmentVariable(profilerUuidEnv); if (!string.IsNullOrWhiteSpace(enableString) && !string.IsNullOrWhiteSpace(uuidString)) { _isBeingProfiled = string.Equals("1", enableString?.Trim()) && string.Equals("{cf0d821e-299b-5307-a3d8-b283c03916da}", uuidString.Trim(), StringComparison.OrdinalIgnoreCase); } else { _isBeingProfiled = false; } return _isBeingProfiled.Value; } } public static String MaskReportingUrl(String url) { String maskedUrl = ""; try { String[] pathFields = url.Split('/'); List<String> stripFields = new List<String>(pathFields.Length); foreach (String field in pathFields) { stripFields.Add(Mask(field)); } maskedUrl = string.Join("/", stripFields); if (maskedUrl.EndsWith("/")) { maskedUrl = maskedUrl.Substring(0, maskedUrl.Length - 1); } } catch { // If we had errors, just return what we got. return url; } return maskedUrl; } private static readonly Regex ID_REGEX = new Regex("^(\\d+)$", RegexOptions.Compiled); private static readonly Regex GUID_REGEX = new Regex("^(?i)(\\b[A-F0-9]{8}(?:-[A-F0-9]{4}){3}-[A-F0-9]{12}\\b)$", RegexOptions.Compiled); private static readonly Regex EMAIL_REGEX = new Regex( "^((([!#$%&'*+\\-/=?^_`{|}~\\w])|([!#$%&'*+\\-/=?^_`{|}~\\w][!#$%&'*+\\-/=?^_`{|}~\\.\\w]{0,}[!#$%&'*+\\-/=?^_`{|}~\\w]))[@]\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*)$", RegexOptions.Compiled); private static readonly Regex IP_REGEX = new Regex( "^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$", RegexOptions.Compiled); private static String Mask(String field) { if (ID_REGEX.IsMatch(field)) { return "{id}"; } if (GUID_REGEX.IsMatch(field)) { return "{guid}"; } if (EMAIL_REGEX.IsMatch(field)) { return "{email}"; } if (IP_REGEX.IsMatch(field)) { return "{ip}"; } if (field.Contains(';')) { return field.Substring(0, field.IndexOf(';')); } return field; } } public class ToStringConverter : JsonConverter { private string _propName = ""; private Type _type; public ToStringConverter(string propName, Type t) { _propName = propName; _type = t; } public override bool CanConvert(Type objectType) { return _type.IsAssignableFrom(objectType); } public override bool CanRead => false; public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value != null) { var o = new JObject(); o.Add(new JProperty(_propName, value.ToString())); o.WriteTo(writer); } } } }
// Copyright 2016 Mark Raasveldt // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; namespace Tibialyzer { class MapForm : NotificationForm { private System.Windows.Forms.PictureBox mapUpLevel; private System.Windows.Forms.PictureBox mapDownLevel; private EnterTextBox mapperBox; private Label usedItemsLabel; private Label label1; private EnterTextBox coordinateBox; private Label routeButton; private static Font text_font = new Font(FontFamily.GenericSansSerif, 11, FontStyle.Bold); private Coordinate startCoordinate; public MapForm(Coordinate startCoordinate) { this.startCoordinate = startCoordinate; InitializeComponent(); } private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MapForm)); this.mapBox = new Tibialyzer.MapPictureBox(); this.mapUpLevel = new System.Windows.Forms.PictureBox(); this.mapDownLevel = new System.Windows.Forms.PictureBox(); this.mapperBox = new Tibialyzer.EnterTextBox(); this.usedItemsLabel = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.coordinateBox = new Tibialyzer.EnterTextBox(); this.routeButton = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.mapBox)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.mapUpLevel)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.mapDownLevel)).BeginInit(); this.SuspendLayout(); // // mapBox // this.mapBox.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.mapBox.Location = new System.Drawing.Point(121, 12); this.mapBox.Name = "mapBox"; this.mapBox.Size = new System.Drawing.Size(195, 190); this.mapBox.TabIndex = 0; this.mapBox.TabStop = false; // // mapUpLevel // this.mapUpLevel.Location = new System.Drawing.Point(121, 13); this.mapUpLevel.Name = "mapUpLevel"; this.mapUpLevel.Size = new System.Drawing.Size(21, 21); this.mapUpLevel.TabIndex = 3; this.mapUpLevel.TabStop = false; // // mapDownLevel // this.mapDownLevel.Location = new System.Drawing.Point(121, 34); this.mapDownLevel.Name = "mapDownLevel"; this.mapDownLevel.Size = new System.Drawing.Size(21, 21); this.mapDownLevel.TabIndex = 4; this.mapDownLevel.TabStop = false; // // mapperBox // this.mapperBox.Location = new System.Drawing.Point(6, 47); this.mapperBox.Name = "mapperBox"; this.mapperBox.Size = new System.Drawing.Size(108, 20); this.mapperBox.TabIndex = 5; this.mapperBox.Text = "127.128,124.128,7"; this.mapperBox.TextChanged += new System.EventHandler(this.mapperBox_TextChanged); // // usedItemsLabel // this.usedItemsLabel.AutoSize = true; this.usedItemsLabel.BackColor = System.Drawing.Color.Transparent; this.usedItemsLabel.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.usedItemsLabel.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.usedItemsLabel.Location = new System.Drawing.Point(7, 29); this.usedItemsLabel.Name = "usedItemsLabel"; this.usedItemsLabel.Size = new System.Drawing.Size(107, 16); this.usedItemsLabel.TabIndex = 42; this.usedItemsLabel.Text = "Mapper Coord"; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.label1.Location = new System.Drawing.Point(19, 75); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(84, 16); this.label1.TabIndex = 44; this.label1.Text = "Coordinate"; // // coordinateBox // this.coordinateBox.Location = new System.Drawing.Point(6, 93); this.coordinateBox.Name = "coordinateBox"; this.coordinateBox.Size = new System.Drawing.Size(108, 20); this.coordinateBox.TabIndex = 43; this.coordinateBox.Text = "1024,1024,7"; this.coordinateBox.TextChanged += new System.EventHandler(this.coordinateBox_TextChanged); // // routeButton // this.routeButton.BackColor = System.Drawing.Color.Transparent; this.routeButton.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.routeButton.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.routeButton.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(191)))), ((int)(((byte)(191)))), ((int)(((byte)(191))))); this.routeButton.Location = new System.Drawing.Point(6, 181); this.routeButton.Name = "routeButton"; this.routeButton.Padding = new System.Windows.Forms.Padding(2); this.routeButton.Size = new System.Drawing.Size(103, 21); this.routeButton.TabIndex = 45; this.routeButton.Text = "Route"; this.routeButton.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.routeButton.Click += new System.EventHandler(this.routeButton_Click); // // MapForm // this.ClientSize = new System.Drawing.Size(328, 221); this.Controls.Add(this.routeButton); this.Controls.Add(this.label1); this.Controls.Add(this.coordinateBox); this.Controls.Add(this.usedItemsLabel); this.Controls.Add(this.mapperBox); this.Controls.Add(this.mapDownLevel); this.Controls.Add(this.mapUpLevel); this.Controls.Add(this.mapBox); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "MapForm"; this.Text = "NPC Form"; ((System.ComponentModel.ISupportInitialize)(this.mapBox)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.mapUpLevel)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.mapDownLevel)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } private MapPictureBox mapBox; protected override bool ShowWithoutActivation { get { return true; } } public override void LoadForm() { this.SuspendForm(); NotificationInitialize(); Coordinate coord = startCoordinate; if (coord == null) { try { MemoryReader.UpdateBattleList(); coord = new Coordinate(MemoryReader.X, MemoryReader.Y, MemoryReader.Z); } catch { coord = new Coordinate(); } } Map m = StorageManager.getMap(coord.z); mapBox.map = m; mapBox.mapImage = null; mapBox.sourceWidth = mapBox.Width; mapBox.beginCoordinate = new Coordinate(coord); mapBox.mapCoordinate = new Coordinate(coord); mapBox.zCoordinate = coord.z; mapBox.MapUpdated += MapBox_MapUpdated; mapBox.UpdateMap(); coordinateBox.Text = String.Format("{0},{1},{2}", coord.x, coord.y, coord.z); UnregisterControl(mapBox); this.mapUpLevel.Image = StyleManager.GetImage("mapup.png"); this.UnregisterControl(mapUpLevel); this.mapUpLevel.Click += mapUpLevel_Click; this.mapDownLevel.Image = StyleManager.GetImage("mapdown.png"); this.UnregisterControl(mapDownLevel); this.mapDownLevel.Click += mapDownLevel_Click; base.NotificationFinalize(); this.ResumeForm(); } private void MapBox_MapUpdated() { updating = true; SetCoordinate(mapBox.mapCoordinate); updating = false; } private void SetCoordinate(Coordinate coordinate) { int x = coordinate.x, y = coordinate.y, z = coordinate.z; coordinateBox.Text = String.Format("{0},{1},{2}", x, y, z); mapperBox.Text = ((x / 256 + 124).ToString() + "." + (x % 256).ToString()) + "," + ((y / 256 + 121).ToString() + "." + (y % 256).ToString()) + "," + z.ToString(); } void mapUpLevel_Click(object sender, EventArgs e) { mapBox.mapCoordinate.z--; mapBox.UpdateMap(); base.ResetTimer(); } void mapDownLevel_Click(object sender, EventArgs e) { mapBox.mapCoordinate.z++; mapBox.UpdateMap(); base.ResetTimer(); } public override string FormName() { return "MapForm"; } bool updating = false; private void mapperBox_TextChanged(object sender, EventArgs e) { if (updating) return; string[] split = mapperBox.Text.Split(','); if (split.Length == 3) { int x_big, x_small, y_big, y_small, z; string[] xsplit = split[0].Split('.'); string[] ysplit = split[1].Split('.'); if (xsplit.Length == 2 && ysplit.Length == 2 && int.TryParse(xsplit[0], out x_big) && int.TryParse(xsplit[1], out x_small) && int.TryParse(ysplit[0], out y_big) && int.TryParse(ysplit[1], out y_small) && int.TryParse(split[2], out z)) { int x = 256 * (x_big - 124) + x_small; int y = 256 * (y_big - 121) + y_small; if (mapBox.mapCoordinate.x != x || mapBox.mapCoordinate.y != y || mapBox.mapCoordinate.z != z) { updating = true; mapBox.mapCoordinate = new Coordinate(x, y, z); SetCoordinate(mapBox.mapCoordinate); mapBox.UpdateMap(); updating = false; } } } } private void coordinateBox_TextChanged(object sender, EventArgs e) { if (updating) return; string[] split = coordinateBox.Text.Split(','); int x, y, z; if (split.Length == 3 && int.TryParse(split[0], out x) && int.TryParse(split[1], out y) && int.TryParse(split[2], out z)) { if (mapBox.mapCoordinate.x != x || mapBox.mapCoordinate.y != y || mapBox.mapCoordinate.z != z) { updating = true; mapBox.mapCoordinate = new Coordinate(x, y, z); SetCoordinate(mapBox.mapCoordinate); mapBox.UpdateMap(); updating = false; } } } private void routeButton_Click(object sender, EventArgs e) { Coordinate c = mapBox.mapCoordinate; CommandManager.ExecuteCommand(String.Format("route@{0},{1},{2}", c.x, c.y, c.z)); } } }
using System; using Mindscape.LightSpeed; using Mindscape.LightSpeed.Validation; using Mindscape.LightSpeed.Linq; namespace Foosinator.Models { [Serializable] [System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")] [System.ComponentModel.DataObject] [Table("Players")] public partial class Player : Entity<System.Guid> { #region Fields [ValidatePresence] [ValidateLength(0, 50)] private string _name; private System.DateTime _created; [ValidateLength(0, 50)] private string _slackUserId; [ValidateLength(0, 500)] private string _profilePicture; #endregion #region Field attribute and view names /// <summary>Identifies the Name entity attribute.</summary> public const string NameField = "Name"; /// <summary>Identifies the Created entity attribute.</summary> public const string CreatedField = "Created"; /// <summary>Identifies the SlackUserId entity attribute.</summary> public const string SlackUserIdField = "SlackUserId"; /// <summary>Identifies the ProfilePicture entity attribute.</summary> public const string ProfilePictureField = "ProfilePicture"; #endregion #region Relationships [ReverseAssociation("Player1")] private readonly EntityCollection<Game> _gamesByPlayer1 = new EntityCollection<Game>(); [ReverseAssociation("Player2")] private readonly EntityCollection<Game> _gamesByPlayer2 = new EntityCollection<Game>(); [ReverseAssociation("Player3")] private readonly EntityCollection<Game> _gamesByPlayer3 = new EntityCollection<Game>(); [ReverseAssociation("Player4")] private readonly EntityCollection<Game> _gamesByPlayer4 = new EntityCollection<Game>(); [ReverseAssociation("Player")] private readonly EntityCollection<Result> _results = new EntityCollection<Result>(); #endregion #region Properties [System.Diagnostics.DebuggerNonUserCode] public EntityCollection<Game> GamesByPlayer1 { get { return Get(_gamesByPlayer1); } } [System.Diagnostics.DebuggerNonUserCode] public EntityCollection<Game> GamesByPlayer2 { get { return Get(_gamesByPlayer2); } } [System.Diagnostics.DebuggerNonUserCode] public EntityCollection<Game> GamesByPlayer3 { get { return Get(_gamesByPlayer3); } } [System.Diagnostics.DebuggerNonUserCode] public EntityCollection<Game> GamesByPlayer4 { get { return Get(_gamesByPlayer4); } } [System.Diagnostics.DebuggerNonUserCode] public EntityCollection<Result> Results { get { return Get(_results); } } [System.Diagnostics.DebuggerNonUserCode] public string Name { get { return Get(ref _name, "Name"); } set { Set(ref _name, value, "Name"); } } [System.Diagnostics.DebuggerNonUserCode] public System.DateTime Created { get { return Get(ref _created, "Created"); } set { Set(ref _created, value, "Created"); } } [System.Diagnostics.DebuggerNonUserCode] public string SlackUserId { get { return Get(ref _slackUserId, "SlackUserId"); } set { Set(ref _slackUserId, value, "SlackUserId"); } } [System.Diagnostics.DebuggerNonUserCode] public string ProfilePicture { get { return Get(ref _profilePicture, "ProfilePicture"); } set { Set(ref _profilePicture, value, "ProfilePicture"); } } #endregion } [Serializable] [System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")] [System.ComponentModel.DataObject] [Table("Games")] public partial class Game : Entity<System.Guid> { #region Fields private System.DateTime _created; [ValidateLength(0, 50)] private string _pin; [ValidateLength(0, 50)] private string _status; [Column("Player1")] private System.Guid _player1Id; [Column("Player2")] private System.Guid _player2Id; [Column("Player3")] private System.Nullable<System.Guid> _player3Id; [Column("Player4")] private System.Nullable<System.Guid> _player4Id; #endregion #region Field attribute and view names /// <summary>Identifies the Created entity attribute.</summary> public const string CreatedField = "Created"; /// <summary>Identifies the Pin entity attribute.</summary> public const string PinField = "Pin"; /// <summary>Identifies the Status entity attribute.</summary> public const string StatusField = "Status"; /// <summary>Identifies the Player1Id entity attribute.</summary> public const string Player1IdField = "Player1Id"; /// <summary>Identifies the Player2Id entity attribute.</summary> public const string Player2IdField = "Player2Id"; /// <summary>Identifies the Player3Id entity attribute.</summary> public const string Player3IdField = "Player3Id"; /// <summary>Identifies the Player4Id entity attribute.</summary> public const string Player4IdField = "Player4Id"; #endregion #region Relationships [ReverseAssociation("Game")] private readonly EntityCollection<Result> _results = new EntityCollection<Result>(); [ReverseAssociation("GamesByPlayer1")] private readonly EntityHolder<Player> _player1 = new EntityHolder<Player>(); [ReverseAssociation("GamesByPlayer2")] private readonly EntityHolder<Player> _player2 = new EntityHolder<Player>(); [ReverseAssociation("GamesByPlayer3")] private readonly EntityHolder<Player> _player3 = new EntityHolder<Player>(); [ReverseAssociation("GamesByPlayer4")] private readonly EntityHolder<Player> _player4 = new EntityHolder<Player>(); #endregion #region Properties [System.Diagnostics.DebuggerNonUserCode] public EntityCollection<Result> Results { get { return Get(_results); } } [System.Diagnostics.DebuggerNonUserCode] public Player Player1 { get { return Get(_player1); } set { Set(_player1, value); } } [System.Diagnostics.DebuggerNonUserCode] public Player Player2 { get { return Get(_player2); } set { Set(_player2, value); } } [System.Diagnostics.DebuggerNonUserCode] public Player Player3 { get { return Get(_player3); } set { Set(_player3, value); } } [System.Diagnostics.DebuggerNonUserCode] public Player Player4 { get { return Get(_player4); } set { Set(_player4, value); } } [System.Diagnostics.DebuggerNonUserCode] public System.DateTime Created { get { return Get(ref _created, "Created"); } set { Set(ref _created, value, "Created"); } } [System.Diagnostics.DebuggerNonUserCode] public string Pin { get { return Get(ref _pin, "Pin"); } set { Set(ref _pin, value, "Pin"); } } [System.Diagnostics.DebuggerNonUserCode] public string Status { get { return Get(ref _status, "Status"); } set { Set(ref _status, value, "Status"); } } /// <summary>Gets or sets the ID for the <see cref="Player1" /> property.</summary> [System.Diagnostics.DebuggerNonUserCode] public System.Guid Player1Id { get { return Get(ref _player1Id, "Player1Id"); } set { Set(ref _player1Id, value, "Player1Id"); } } /// <summary>Gets or sets the ID for the <see cref="Player2" /> property.</summary> [System.Diagnostics.DebuggerNonUserCode] public System.Guid Player2Id { get { return Get(ref _player2Id, "Player2Id"); } set { Set(ref _player2Id, value, "Player2Id"); } } /// <summary>Gets or sets the ID for the <see cref="Player3" /> property.</summary> [System.Diagnostics.DebuggerNonUserCode] public System.Nullable<System.Guid> Player3Id { get { return Get(ref _player3Id, "Player3Id"); } set { Set(ref _player3Id, value, "Player3Id"); } } /// <summary>Gets or sets the ID for the <see cref="Player4" /> property.</summary> [System.Diagnostics.DebuggerNonUserCode] public System.Nullable<System.Guid> Player4Id { get { return Get(ref _player4Id, "Player4Id"); } set { Set(ref _player4Id, value, "Player4Id"); } } #endregion } [Serializable] [System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")] [System.ComponentModel.DataObject] [Table("Results")] public partial class Result : Entity<System.Guid> { #region Fields private System.DateTime _created; [ValidatePresence] [ValidateLength(0, 50)] private string _status; private System.Nullable<System.Guid> _playerId; private System.Guid _gameId; #endregion #region Field attribute and view names /// <summary>Identifies the Created entity attribute.</summary> public const string CreatedField = "Created"; /// <summary>Identifies the Status entity attribute.</summary> public const string StatusField = "Status"; /// <summary>Identifies the PlayerId entity attribute.</summary> public const string PlayerIdField = "PlayerId"; /// <summary>Identifies the GameId entity attribute.</summary> public const string GameIdField = "GameId"; #endregion #region Relationships [ReverseAssociation("Results")] private readonly EntityHolder<Player> _player = new EntityHolder<Player>(); [ReverseAssociation("Results")] private readonly EntityHolder<Game> _game = new EntityHolder<Game>(); #endregion #region Properties [System.Diagnostics.DebuggerNonUserCode] public Player Player { get { return Get(_player); } set { Set(_player, value); } } [System.Diagnostics.DebuggerNonUserCode] public Game Game { get { return Get(_game); } set { Set(_game, value); } } [System.Diagnostics.DebuggerNonUserCode] public System.DateTime Created { get { return Get(ref _created, "Created"); } set { Set(ref _created, value, "Created"); } } [System.Diagnostics.DebuggerNonUserCode] public string Status { get { return Get(ref _status, "Status"); } set { Set(ref _status, value, "Status"); } } /// <summary>Gets or sets the ID for the <see cref="Player" /> property.</summary> [System.Diagnostics.DebuggerNonUserCode] public System.Nullable<System.Guid> PlayerId { get { return Get(ref _playerId, "PlayerId"); } set { Set(ref _playerId, value, "PlayerId"); } } /// <summary>Gets or sets the ID for the <see cref="Game" /> property.</summary> [System.Diagnostics.DebuggerNonUserCode] public System.Guid GameId { get { return Get(ref _gameId, "GameId"); } set { Set(ref _gameId, value, "GameId"); } } #endregion } /// <summary> /// Provides a strong-typed unit of work for working with the FoosinatorModel model. /// </summary> [System.CodeDom.Compiler.GeneratedCode("LightSpeedModelGenerator", "1.0.0.0")] public partial class FoosinatorModelUnitOfWork : Mindscape.LightSpeed.UnitOfWork { public System.Linq.IQueryable<Player> Players { get { return this.Query<Player>(); } } public System.Linq.IQueryable<Game> Games { get { return this.Query<Game>(); } } public System.Linq.IQueryable<Result> Results { get { return this.Query<Result>(); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Msi.Fluent { using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Management.Graph.RBAC.Fluent.Models; using Microsoft.Azure.Management.Graph.RBAC.Fluent; using Microsoft.Azure.Management.Msi.Fluent.Identity.Definition; using Microsoft.Azure.Management.Msi.Fluent.Identity.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core; using Microsoft.Azure.Management.ResourceManager.Fluent; internal sealed partial class IdentityImpl { /// <summary> /// Specifies that the identity should have the given access (described by the role) /// on an ARM resource. An applications running on an Azure service with this identity /// can use this permission to access the resource. /// </summary> /// <param name="resource">The resource to access.</param> /// <param name="role">Access role to assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithAccessTo(IResource resource, BuiltInRole role) { return this.WithAccessTo(resource, role); } /// <summary> /// Specifies that the identity should have the given access (described by the role) /// on an ARM resource identified by the given resource id. An applications running /// on an Azure service with this identity can use this permission to access the resource. /// </summary> /// <param name="resourceId">Id of the resource to access.</param> /// <param name="role">Access role to assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithAccessTo(string resourceId, BuiltInRole role) { return this.WithAccessTo(resourceId, role); } /// <summary> /// Specifies that the identity should have the given access (described by the role /// definition) on an ARM resource. An applications running on an Azure service with /// this identity can use this permission to access the resource. /// </summary> /// <param name="resource">Scope of the access represented as ARM resource.</param> /// <param name="roleDefinitionId">Access role definition to assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithAccessTo(IResource resource, string roleDefinitionId) { return this.WithAccessTo(resource, roleDefinitionId); } /// <summary> /// Specifies that the identity should have the given access (described by the role /// definition) on an ARM resource identified by the given resource id. An applications /// running on an Azure service with this identity can use this permission to access /// the resource. /// </summary> /// <param name="resourceId">Id of the resource to access.</param> /// <param name="roleDefinitionId">Access role definition to assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithAccessTo(string resourceId, string roleDefinitionId) { return this.WithAccessTo(resourceId, roleDefinitionId); } /// <summary> /// Specifies that an access role assigned to the identity should be removed. /// </summary> /// <param name="roleAssignment">Describes an existing role assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithoutAccess(IRoleAssignment roleAssignment) { return this.WithoutAccess(roleAssignment); } /// <summary> /// Specifies that the identity should have the given access (described by the role) /// on the resource group that identity resides. An applications running on an Azure /// service with this identity can use this permission to access the resource group. /// </summary> /// <param name="role">Access role to assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithAccessToCurrentResourceGroup(BuiltInRole role) { return this.WithAccessToCurrentResourceGroup(role); } /// <summary> /// Specifies that the identity should have the given access (described by the role /// definition) on the resource group that identity resides. An applications running /// on an Azure service with this identity can use this permission to access the /// resource group. /// </summary> /// <param name="roleDefinitionId">Access role definition to assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithAccessToCurrentResourceGroup(string roleDefinitionId) { return this.WithAccessToCurrentResourceGroup(roleDefinitionId); } /// <summary> /// Specifies that an access role assigned to the identity should be removed. /// </summary> /// <param name="resourceId">Id of the resource that identity has access.</param> /// <param name="role">The access role assigned to the identity.</param> /// <return>The next stage of the update.</return> Identity.Update.IUpdate Identity.Update.IWithAccess.WithoutAccessTo(string resourceId, BuiltInRole role) { return this.WithoutAccessTo(resourceId, role); } /// <summary> /// Specifies that the identity should have the given access (described by the role) /// on an ARM resource. An applications running on an Azure service with this identity /// can use this permission to access the resource. /// </summary> /// <param name="resource">The resource to access.</param> /// <param name="role">Access role to assigned to the identity.</param> /// <return>The next stage of the definition.</return> Identity.Definition.IWithCreate Identity.Definition.IWithAccess.WithAccessTo(IResource resource, BuiltInRole role) { return this.WithAccessTo(resource, role); } /// <summary> /// Specifies that the identity should have the given access (described by the role) /// on an ARM resource identified by the given resource id. An applications running /// on an Azure service with this identity can use this permission to access the resource. /// </summary> /// <param name="resourceId">Id of the resource to access.</param> /// <param name="role">Access role to assigned to the identity.</param> /// <return>The next stage of the definition.</return> Identity.Definition.IWithCreate Identity.Definition.IWithAccess.WithAccessTo(string resourceId, BuiltInRole role) { return this.WithAccessTo(resourceId, role); } /// <summary> /// Specifies that the identity should have the given access (described by the role /// definition) on an ARM resource. An applications running on an Azure service with /// this identity can use this permission to access the resource. /// </summary> /// <param name="resource">Scope of the access represented as ARM resource.</param> /// <param name="roleDefinitionId">Access role definition to assigned to the identity.</param> /// <return>The next stage of the definition.</return> Identity.Definition.IWithCreate Identity.Definition.IWithAccess.WithAccessTo(IResource resource, string roleDefinitionId) { return this.WithAccessTo(resource, roleDefinitionId); } /// <summary> /// Specifies that the identity should have the given access (described by the role /// definition) on an ARM resource identified by the given resource id. An applications /// running on an Azure service with this identity can use this permission to access /// the resource. /// </summary> /// <param name="resourceId">Id of the resource to access.</param> /// <param name="roleDefinitionId">Access role definition to assigned to the identity.</param> /// <return>The next stage of the definition.</return> Identity.Definition.IWithCreate Identity.Definition.IWithAccess.WithAccessTo(string resourceId, string roleDefinitionId) { return this.WithAccessTo(resourceId, roleDefinitionId); } /// <summary> /// Specifies that the identity should have the given access (described by the role) /// on the resource group that identity resides. An applications running on an Azure /// service with this identity can use this permission to access the resource group. /// </summary> /// <param name="role">Access role to assigned to the identity.</param> /// <return>The next stage of the definition.</return> Identity.Definition.IWithCreate Identity.Definition.IWithAccess.WithAccessToCurrentResourceGroup(BuiltInRole role) { return this.WithAccessToCurrentResourceGroup(role); } /// <summary> /// Specifies that the identity should have the given access (described by the role /// definition) on the resource group that identity resides. An applications running /// on an Azure service with this identity can use this permission to access the /// resource group. /// </summary> /// <param name="roleDefinitionId">Access role definition to assigned to the identity.</param> /// <return>The next stage of the definition.</return> Identity.Definition.IWithCreate Identity.Definition.IWithAccess.WithAccessToCurrentResourceGroup(string roleDefinitionId) { return this.WithAccessToCurrentResourceGroup(roleDefinitionId); } /// <summary> /// Gets id of the Azure Active Directory application associated with the identity. /// </summary> string Microsoft.Azure.Management.Msi.Fluent.IIdentity.ClientId { get { return this.ClientId(); } } /// <summary> /// Gets id of the Azure Active Directory tenant to which the identity belongs to. /// </summary> string Microsoft.Azure.Management.Msi.Fluent.IIdentity.TenantId { get { return this.TenantId(); } } /// <summary> /// Gets the url that can be queried to obtain the identity credentials. /// </summary> string Microsoft.Azure.Management.Msi.Fluent.IIdentity.ClientSecretUrl { get { return this.ClientSecretUrl(); } } /// <summary> /// Gets id of the Azure Active Directory service principal object associated with the identity. /// </summary> string Microsoft.Azure.Management.Msi.Fluent.IIdentity.PrincipalId { get { return this.PrincipalId(); } } } }
using System; using System.Collections; // 14/6/03 namespace NBM.Plugin { #region Protocol listener collection and enumerator /// <summary> /// /// </summary> internal class ProtocolListenerEnumerator : IEnumerator, IDisposable { private int index = -1; private IList collection; /// <summary> /// /// </summary> /// <param name="collection"></param> public ProtocolListenerEnumerator(ProtocolListenerCollection collection) { this.collection = ArrayList.Synchronized(collection.Clone()); } /// <summary> /// /// </summary> object IEnumerator.Current { get { return Current; } } /// <summary> /// /// </summary> public IProtocolListener Current { get { return (IProtocolListener)collection[index]; } } /// <summary> /// /// </summary> public void Reset() { index = -1; } /// <summary> /// /// </summary> /// <returns></returns> public bool MoveNext() { if (index == -1) System.Threading.Monitor.Enter(collection.SyncRoot); return ++index < collection.Count; } /// <summary> /// /// </summary> public void Dispose() { System.Threading.Monitor.Exit(collection.SyncRoot); } } /// <summary> /// /// </summary> internal class ProtocolListenerCollection : IList, ICollection, IEnumerable, ICloneable { private ArrayList arrayList = new ArrayList(); /// <summary> /// /// </summary> /// <returns></returns> object ICloneable.Clone() { return this.Clone(); } /// <summary> /// /// </summary> /// <returns></returns> public ProtocolListenerCollection Clone() { ProtocolListenerCollection c = new ProtocolListenerCollection(); c.arrayList.AddRange(this.arrayList); return c; } /// <summary> /// /// </summary> public ProtocolListenerCollection() { } /// <summary> /// /// </summary> /// <returns></returns> public IEnumerator GetEnumerator() { return new ProtocolListenerEnumerator(this); } /// <summary> /// /// </summary> public int Count { get { return this.arrayList.Count; } } /// <summary> /// /// </summary> /// <param name="array"></param> /// <param name="count"></param> public void CopyTo(Array array, int count) { this.arrayList.CopyTo(array, count); } /// <summary> /// /// </summary> public bool IsSynchronized { get { return this.arrayList.IsSynchronized; } } /// <summary> /// /// </summary> public object SyncRoot { get { return this.arrayList.SyncRoot; } } /// <summary> /// /// </summary> public bool IsFixedSize { get { return arrayList.IsFixedSize; } } /// <summary> /// /// </summary> public bool IsReadOnly { get { return arrayList.IsReadOnly; } } /// <summary> /// /// </summary> object IList.this[int index] { get { return this[index]; } set { this[index] = (IProtocolListener)value; } } /// <summary> /// /// </summary> public IProtocolListener this[int index] { get { return (IProtocolListener)this.arrayList[index]; } set { this.arrayList[index] = value; } } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> int IList.Add(object o) { return Add((IProtocolListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> public int Add(IProtocolListener o) { return this.arrayList.Add(o); } /// <summary> /// /// </summary> public void Clear() { arrayList.Clear(); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> bool IList.Contains(object o) { return Contains((IProtocolListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> public bool Contains(IProtocolListener o) { return this.arrayList.Contains(o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> int IList.IndexOf(object o) { return IndexOf((IProtocolListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> /// <returns></returns> public int IndexOf(IProtocolListener o) { return this.arrayList.IndexOf(o); } /// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="o"></param> void IList.Insert(int index, object o) { Insert(index, (IProtocolListener)o); } /// <summary> /// /// </summary> /// <param name="index"></param> /// <param name="o"></param> public void Insert(int index, IProtocolListener o) { this.arrayList.Insert(index, o); } /// <summary> /// /// </summary> /// <param name="o"></param> void IList.Remove(object o) { Remove((IProtocolListener)o); } /// <summary> /// /// </summary> /// <param name="o"></param> public void Remove(IProtocolListener o) { this.arrayList.Remove(o); } /// <summary> /// /// </summary> /// <param name="index"></param> public void RemoveAt(int index) { arrayList.RemoveAt(index); } } #endregion /// <summary> /// Server class for ProtocolControl. /// <seealso cref="ProtocolControl"/> /// </summary> public class ProtocolServer { private ProtocolListenerCollection listenerList = new ProtocolListenerCollection(); private ArrayList friendsList = new ArrayList(); /// <summary> /// /// </summary> public ProtocolServer() { } /// <summary> /// /// </summary> /// <param name="listener"></param> public void AddListener(IProtocolListener listener) { if (!this.listenerList.Contains(listener)) listenerList.Add(listener); } /// <summary> /// /// </summary> /// <param name="listener"></param> public void RemoveListener(IProtocolListener listener) { listenerList.Remove(listener); } /// <summary> /// /// </summary> /// <returns></returns> public Proxy.IConnection CreateConnection() { switch (Settings.GlobalSettings.Instance().InternetConnection) { default: case Settings.InternetConnection.Direct: return new Proxy.DirectConnection(); case Settings.InternetConnection.Socks4: return new Proxy.Socks4Connection(); case Settings.InternetConnection.Socks5: return new Proxy.Socks5Connection(); case Settings.InternetConnection.Http: return new Proxy.HttpConnection(); } } /// <summary> /// /// </summary> public void OnBeginConnect() { foreach (IProtocolListener listener in this.listenerList) { listener.OnBeginConnect(); } } /// <summary> /// /// </summary> public void OnConnect() { foreach (IProtocolListener listener in this.listenerList) { listener.OnConnect(); } } /// <summary> /// /// </summary> public void OnConnectCanceled() { foreach (IProtocolListener listener in this.listenerList) { listener.OnConnectCanceled(); } } /// <summary> /// /// </summary> public void OnNormalDisconnect() { this.friendsList.Clear(); foreach (IProtocolListener listener in this.listenerList) { listener.OnDisconnect(false); } } /// <summary> /// /// </summary> public void ForcedDisconnect() { this.friendsList.Clear(); foreach (IProtocolListener listener in this.listenerList) { listener.OnDisconnect(true); } } /// <summary> /// /// </summary> /// <param name="newStatus"></param> public void OnChangeStatus(OnlineStatus newStatus) { foreach (IProtocolListener listener in this.listenerList) { listener.OnChangeStatus(newStatus); } } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="opCompleteEvent"></param> /// <param name="tag"></param> public void StartInvitedConversation(Friend friend, OperationCompleteEvent opCompleteEvent, object tag) { foreach (IProtocolListener listener in this.listenerList) { listener.OnInvitedToConversation(friend, opCompleteEvent, tag); } } /// <summary> /// /// </summary> /// <param name="friend"></param> public void AddFriend(Friend friend) { foreach (IProtocolListener listener in this.listenerList) { friend.AddListener(listener); listener.OnFriendAdd(friend); } this.friendsList.Add(friend); } /// <summary> /// /// </summary> /// <param name="friend"></param> public void RemoveFriend(Friend friend) { foreach (IProtocolListener listener in this.listenerList) { friend.RemoveListener(listener); listener.OnFriendRemove(friend); } this.friendsList.Remove(friend); } /// <summary> /// /// </summary> /// <param name="username"></param> public void RemoveFriend(string username) { Friend friend = GetFriend(username); if (friend != null) RemoveFriend(friend); } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <returns></returns> public bool ContainsFriend(Friend friend) { return this.friendsList.Contains(friend); } /// <summary> /// /// </summary> /// <param name="username"></param> /// <returns></returns> public bool ContainsFriend(string username) { return GetFriend(username) != null; } /// <summary> /// /// </summary> /// <param name="username"></param> /// <returns></returns> public Friend GetFriend(string username) { lock (this.friendsList.SyncRoot) { foreach (Friend friend in this.friendsList) { if (friend.Username == username) return friend; } } return null; } /// <summary> /// /// </summary> /// <param name="username"></param> public void AddFriendToList(string username) { foreach (IProtocolListener listener in this.listenerList) { listener.OnAddFriendToList(username); } } /// <summary> /// /// </summary> /// <param name="friend"></param> public void RemoveFriendFromList(Friend friend) { foreach (IProtocolListener listener in this.listenerList) { listener.OnRemoveFriendFromList(friend); } } /// <summary> /// /// </summary> /// <param name="friend"></param> public void BlockFriend(Friend friend) { foreach (IProtocolListener listener in this.listenerList) { listener.OnBlockFriend(friend); } } /// <summary> /// /// </summary> /// <param name="friend"></param> public void UnblockFriend(Friend friend) { foreach (IProtocolListener listener in this.listenerList) { listener.OnUnblockFriend(friend); } } /// <summary> /// /// </summary> /// <param name="text"></param> public void WriteDebug(string text) { foreach (IProtocolListener listener in this.listenerList) { listener.OnWriteDebug(text); } } /// <summary> /// /// </summary> /// <param name="format"></param> /// <param name="args"></param> public void WriteDebug(string format, params object[] args) { foreach (IProtocolListener listener in this.listenerList) { listener.OnWriteDebug(string.Format(format, args)); } } /// <summary> /// /// </summary> /// <param name="friend"></param> /// <param name="reason"></param> /// <param name="enableAddCheckbox"></param> public void PromptForStrangerHasAddedMe(Friend friend, string reason, bool enableAddCheckbox) { foreach (IProtocolListener listener in this.listenerList) { listener.OnPromptForStrangerHasAddedMe(friend, reason, enableAddCheckbox); } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Data.SqlTypes; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; using System.Xml; using System.IO; using System.Web.Hosting; using System.Diagnostics; using System.Text; using System.Text.RegularExpressions; using System.Globalization; using DotNetNuke; using DotNetNuke.Security; using DotNetNuke.Entities.Portals; using DotNetNuke.Services.Scheduling; using DotNetNuke.Entities.Modules; using System.Reflection; using System.Security; using System.Security.Permissions; using Brafton; using Brafton.Modules.Globals; using System.Net; using Brafton.Modules.VideoImporter; using Brafton.Modules.BraftonImporter7_02_02.dbDataLayer; using System.Web.Script.Serialization; namespace BraftonView.Brafton_Importer_Clean { [SecurityCritical] public partial class DesktopModules_Brafton_View2 : DotNetNuke.Entities.Modules.PortalModuleBase { //Connection properties public SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SiteSqlServer"].ToString()); public SqlConnection connection2; public SqlCommand cmd = new SqlCommand(); public SqlCommand cmd2 = new SqlCommand(); public Boolean isEditable; public Boolean braftonViewable() { /* * This is going to determine if user is logged in and if so * will go and retrieve the admin user control * */ isEditable = HttpContext.Current.User.Identity.IsAuthenticated; if (isEditable) { return true; } return false; } protected void Page_Load(object sender, EventArgs e) { /* * TO DO: * Need to create a check if video article somehow, and determine if we should add the atlantis scripts to the head. * */ ModuleConfiguration.ModuleTitle = ""; if (braftonViewable()) { CheckUpdate(); CheckStatus(); BraftonAdminPanel.Visible = true; } HtmlLink css = new HtmlLink(); css.Href = "https://atlantisjs.brafton.com/v1/atlantisjsv1.4.css"; css.Attributes.Add("rel", "stylesheet"); css.Attributes.Add("type", "text/css"); this.Page.Header.Controls.Add(css); string jquery = "<script>!window.jQuery && document.write(unescape('%3Cscript src=\"//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js\"%3E%3C/script%3E'))</script>"; string atlantis = "<script src='https://atlantisjs.brafton.com/v1/atlantis.min.v1.3.js' type='text/javascript'></script>"; //do a check if jquery is turned on if (Settings.Contains("IncludejQuery") && Settings["IncludeAtlantis"].ToString() == "1") { this.Page.Header.Controls.Add(new LiteralControl(jquery)); } if (Settings.Contains("IncludeAtlantis") && Settings["IncludeAtlantis"].ToString() == "1") { this.Page.Header.Controls.Add(new LiteralControl(atlantis)); } /* * This will be added when using without the blog module in the version 7.1.0 HtmlMeta meta = new HtmlMeta(); meta.Name = "brafton"; meta.Content = "my brafton"; this.Page.Header.Controls.Add(meta); * */ MessageImageVisible(); } protected void MessageImageVisible() { if (!string.IsNullOrWhiteSpace(globalErrorMessage.Text)) { MessageImage.Visible = true; } else { MessageImage.Visible = false; } } protected void Import_Click(object sender, EventArgs e) { Brafton.DotNetNuke.BraftonSchedule newSched = new Brafton.DotNetNuke.BraftonSchedule(); MyGlobals.BraftonViewModuleId.Add(ModuleId); newSched.DoWork(); globalErrorMessage.Text = MyGlobals.MyGlobalError; MessageImageVisible(); MyGlobals.MyGlobalError = ""; } protected void show_globals(object sender, EventArgs e) { CheckStatus(); globalErrorMessage.Text = MyGlobals.MyGlobalError; MessageImageVisible(); MyGlobals.MyGlobalError = ""; } protected void CheckStatus() { using (DataClasses1DataContext dnncontext = new DataClasses1DataContext()) { Schedule sc = dnncontext.Schedules.FirstOrDefault(x => x.FriendlyName == "BraftonImporter"); if (sc == null){} else { if (Convert.ToBoolean(sc.Enabled)) { EnableAuto.Text = "Disable Automatic Import"; } else { EnableAuto.Text = "Enable Automatic Import"; } } } string msg = "<ul>"; bool status = true; if (Settings.Contains("RadioButtonList1")) { string type = Settings["RadioButtonList1"].ToString(); if (Settings.Contains("APIKey") && (type == "articles" || type == "both") ) { string key = Settings["APIKey"].ToString(); Guid key_result; bool valid = Guid.TryParse(key, out key_result); status = status ? valid : status; if (!status) { msg = msg + "<li>APIKey is either not set or is invalid</li>"; } } else if(type == "articles" || type == "both") { msg = msg + "<li>You have not set your API Key</li>"; status = false; } if ((Settings.Contains("VideoPublic") || Settings.Contains("VideoPrivate")) && (type == "video" || type == "both")) { string publicKey = Settings["VideoPublic"].ToString(); string privateKey = Settings["VideoPrivate"].ToString(); Guid private_result; bool private_valid = Guid.TryParse(privateKey, out private_result); status = status ? private_valid : status; bool public_valid = !string.IsNullOrWhiteSpace(publicKey); status = status ? public_valid : status; if (!public_valid || !private_valid) { msg = msg + "<li>Check your Public and Private Keys to ensure they are valid</li>"; } } else if (type == "video" || type == "both") { msg = msg + "<li>You have not set your Video Public and/or Private Keys</li>"; status = false; } if (!Settings.Contains("blogIdDrpDwn")) { msg = msg + "<li>You have not selected a Blog to import your content into</li>"; status = false; } connection.Open(); cmd.Connection = connection; cmd.CommandText = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Blog_Posts' AND column_name='BraftonID') BEGIN ALTER TABLE Blog_Posts ADD BraftonID nvarchar(255) END"; cmd.ExecuteNonQuery(); cmd.CommandText = "IF NOT EXISTS (SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME='Blog_Posts' AND column_name='LastUpdatedOn') BEGIN ALTER TABLE Blog_Posts ADD LastUpdatedOn DATETIME NULL END"; cmd.ExecuteNonQuery(); connection.Close(); cmd.Dispose(); msg = msg + "</ul>"; if (status) { msg = string.Empty; } else { StatusImage.ImageUrl = "~/desktopmodules/Braftonimporter7_02_02/Images/error.png"; } } else { status = false; msg = "<li>No options have been saved for this module</li>"; StatusImage.ImageUrl = "~/desktopmodules/Braftonimporter7_02_02/Images/error.png"; } checkedStatusLabel.Text = msg; Import.Enabled = status; EnableAuto.Enabled = status; } protected void EnableAutomaticImport(object sender, EventArgs e) { /* * this will add the importer to the dnn scheduler * */ using (DataClasses1DataContext dnncontext = new DataClasses1DataContext()) { Schedule sc = dnncontext.Schedules.FirstOrDefault(x => x.FriendlyName == "BraftonImporter"); if (sc == null) { Schedule newSchedule = new Schedule(); newSchedule.TypeFullName = "Brafton.DotNetNuke.BraftonSchedule,BraftonImporter7_02_02"; newSchedule.TimeLapse = 1; newSchedule.TimeLapseMeasurement = "h"; newSchedule.RetryTimeLapse = 15; newSchedule.RetryTimeLapseMeasurement = "m"; newSchedule.RetainHistoryNum = 0; newSchedule.CatchUpEnabled = false; newSchedule.Enabled = true; newSchedule.FriendlyName = "BraftonImporter"; newSchedule.CreatedOnDate = DateTime.Now; newSchedule.ScheduleStartDate = DateTime.Now; newSchedule.AttachToEvent = ""; newSchedule.ObjectDependencies = ""; dnncontext.Schedules.InsertOnSubmit(newSchedule); dnncontext.SubmitChanges(); MyGlobals.LogMessage("Created scheduler Entry for Brafton Importer", 1); EnableAuto.Text = "Turn Off Automatic Import"; } else { if (Convert.ToBoolean(sc.Enabled)) { sc.Enabled = false; MyGlobals.LogMessage("The Schedule has been disabled", 1); EnableAuto.Text = "Turn On Automatic Import"; } else { sc.Enabled = true; MyGlobals.LogMessage("The Schedule has been enabled", 1); EnableAuto.Text = "Turn Off Automatic Import"; } dnncontext.SubmitChanges(); } globalErrorMessage.Text = MyGlobals.MyGlobalError; MessageImageVisible(); MyGlobals.MyGlobalError = ""; } } protected void CheckUpdate() { string msg = string.Empty; DesktopModuleInfo braftonModule = DesktopModuleController.GetDesktopModuleByFriendlyName("Brafton Content Importer"); string SystemVersion = braftonModule.Version.ToString(); Version currentVersion = new Version(SystemVersion); string url = "http://updater.brafton.com/u/dotnetnuke/update"; HttpWebRequest report = (HttpWebRequest)WebRequest.Create(url); HttpWebResponse response = (HttpWebResponse)report.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader reader = new StreamReader(stream); var result = reader.ReadToEnd(); var json = new JavaScriptSerializer(); //Dictionary<string, string> updaterResponse = new Dictionary<string, string>(); var jsonData = json.Deserialize<Dictionary<string, string>>(result.ToString()); string updatedVersion = jsonData["new_version"].ToString(); Version remoteVerion = new Version(updatedVersion); int compare_result = currentVersion.CompareTo(remoteVerion); if (compare_result < 0) { UpdateAvailable.Visible = true; msg = "There is an update available for your Importer.<br/> You are currently running V" + SystemVersion + ", However V" + updatedVersion + " is available.<br/>You can Download the updated version <a href='" + jsonData["download_link"].ToString() + "'>HERE</a>"; } UpdateMessage.Text = msg; } } }
#region License /* * Copyright 2002-2010 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion #region Imports using System; using System.Collections; using System.Collections.Generic; using System.Web.UI; using Spring.Collections; using Spring.Validation; using IValidator = Spring.Validation.IValidator; using Spring.Context; using Spring.Context.Support; using Spring.Globalization; using System.ComponentModel; using System.Globalization; using System.Resources; using Spring.Web.Support; #endregion Imports namespace Spring.Web.UI { #region ASP.NET 2.0 Spring Master Page Implementation /// <summary> /// Spring.NET Master Page implementation for ASP.NET 2.0 /// </summary> /// <author>Aleksandar Seovic</author> public class MasterPage : System.Web.UI.MasterPage, IApplicationContextAware, ISupportsWebDependencyInjection, IWebNavigable { #region Instance Fields private ILocalizer localizer; private IValidationErrors validationErrors = new ValidationErrors(); private IMessageSource messageSource; private IApplicationContext applicationContext; private IApplicationContext defaultApplicationContext; private IWebNavigator webNavigator; private IDictionary args; #endregion #region Lifecycle methods /// <summary> /// Initialize a new MasterPage instance. /// </summary> public MasterPage() { InitializeNavigationSupport(); } /// <summary> /// Initializes user control. /// </summary> protected override void OnInit(EventArgs e) { InitializeMessageSource(); base.OnInit(e); // initialize controls OnInitializeControls(EventArgs.Empty); } /// <summary> /// Binds data from the data model into controls and raises /// PreRender event afterwards. /// </summary> /// <param name="e">Event arguments.</param> protected override void OnPreRender(EventArgs e) { if (localizer != null) { localizer.ApplyResources(this, messageSource, UserCulture); } else if (Page.Localizer != null) { Page.Localizer.ApplyResources(this, messageSource, UserCulture); } base.OnPreRender(e); } /// <summary> /// This event is raised before Load event and should be used to initialize /// controls as necessary. /// </summary> public event EventHandler InitializeControls; /// <summary> /// Raises InitializeControls event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnInitializeControls(EventArgs e) { if (InitializeControls != null) { InitializeControls(this, e); } } /// <summary> /// Obtains a <see cref="T:System.Web.UI.UserControl"/> object from a user control file /// and injects dependencies according to Spring config file. /// </summary> /// <param name="virtualPath">The virtual path to a user control file.</param> /// <returns> /// Returns the specified <see langword="UserControl"/> object, with dependencies injected. /// </returns> protected virtual new Control LoadControl(string virtualPath) { Control control = base.LoadControl(virtualPath); control = WebDependencyInjectionUtils.InjectDependenciesRecursive(defaultApplicationContext,control); return control; } /// <summary> /// Obtains a <see cref="T:System.Web.UI.UserControl"/> object by type /// and injects dependencies according to Spring config file. /// </summary> /// <param name="t">The type of a user control.</param> /// <param name="parameters">parameters to pass to the control</param> /// <returns> /// Returns the specified <see langword="UserControl"/> object, with dependencies injected. /// </returns> protected virtual new Control LoadControl( Type t, params object[] parameters) { Control control = base.LoadControl( t, parameters ); control = WebDependencyInjectionUtils.InjectDependenciesRecursive(defaultApplicationContext,control); return control; } #endregion Control lifecycle methods #region Data binding events /// <summary> /// This event is raised after all controls have been populated with values /// from the data model. /// </summary> public event EventHandler DataBound; /// <summary> /// Raises DataBound event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnDataBound(EventArgs e) { if (DataBound != null) { DataBound(this, e); } } /// <summary> /// This event is raised after data model has been populated with values from /// web controls. /// </summary> public event EventHandler DataUnbound; /// <summary> /// Raises DataBound event. /// </summary> /// <param name="e">Event arguments.</param> protected virtual void OnDataUnbound(EventArgs e) { if (DataUnbound != null) { DataUnbound(this, e); } } #endregion #region Application context support /// <summary> /// Gets or sets the <see cref="Spring.Context.IApplicationContext"/> that this /// object runs in. /// </summary> /// <value></value> /// <remarks> /// <p> /// Normally this call will be used to initialize the object. /// </p> /// <p> /// Invoked after population of normal object properties but before an /// init callback such as /// <see cref="Spring.Objects.Factory.IInitializingObject"/>'s /// <see cref="Spring.Objects.Factory.IInitializingObject.AfterPropertiesSet"/> /// or a custom init-method. Invoked after the setting of any /// <see cref="Spring.Context.IResourceLoaderAware"/>'s /// <see cref="Spring.Context.IResourceLoaderAware.ResourceLoader"/> /// property. /// </p> /// </remarks> /// <exception cref="Spring.Context.ApplicationContextException"> /// In the case of application context initialization errors. /// </exception> /// <exception cref="Spring.Objects.ObjectsException"> /// If thrown by any application context methods. /// </exception> /// <exception cref="Spring.Objects.Factory.ObjectInitializationException"/> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual IApplicationContext ApplicationContext { get { return applicationContext; } set { applicationContext = value; } } #endregion #region Message source and localization support /// <summary> /// Gets or sets the localizer. /// </summary> /// <value>The localizer.</value> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ILocalizer Localizer { get { return localizer; } set { localizer = value; if (localizer.ResourceCache is NullResourceCache) { localizer.ResourceCache = new AspNetResourceCache(); } } } /// <summary> /// Gets or sets the local message source. /// </summary> /// <value>The local message source.</value> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public IMessageSource MessageSource { get { return messageSource; } set { messageSource = value; if (messageSource != null && messageSource is AbstractMessageSource) { ((AbstractMessageSource) messageSource).ParentMessageSource = applicationContext; } } } /// <summary> /// Initializes local message source /// </summary> protected void InitializeMessageSource() { if (MessageSource == null) { string key = GetType().FullName + ".MessageSource"; MessageSource = (IMessageSource) Context.Cache.Get(key); if (MessageSource == null) { ResourceSetMessageSource defaultMessageSource = new ResourceSetMessageSource(); ResourceManager rm = GetLocalResourceManager(); if (rm != null) { defaultMessageSource.ResourceManagers.Add(rm); } Context.Cache.Insert(key, defaultMessageSource); MessageSource = defaultMessageSource; } } } /// <summary> /// Creates and returns local ResourceManager for this page. /// </summary> /// <remarks> /// <para> /// In ASP.NET 1.1, this method loads local resources from the web application assembly. /// </para> /// <para> /// However, in ASP.NET 2.0, local resources are compiled into the dynamic assembly, /// so we need to find that assembly instead and load the resources from it. /// </para> /// </remarks> /// <returns>Local ResourceManager instance.</returns> private ResourceManager GetLocalResourceManager() { return LocalResourceManager.GetLocalResourceManager(this); } /// <summary> /// Returns message for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <returns>Message text.</returns> public string GetMessage(string name) { return messageSource.GetMessage(name, UserCulture); } /// <summary> /// Returns message for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <param name="args">Message arguments that will be used to format return value.</param> /// <returns>Formatted message text.</returns> public string GetMessage(string name, params object[] args) { return messageSource.GetMessage(name, UserCulture, args); } /// <summary> /// Returns resource object for the specified resource name. /// </summary> /// <param name="name">Resource name.</param> /// <returns>Resource object.</returns> public object GetResourceObject(string name) { return messageSource.GetResourceObject(name, UserCulture); } /// <summary> /// Gets or sets user's culture /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public virtual CultureInfo UserCulture { get { return Page.UserCulture; } set { Page.UserCulture = value; } } #endregion #region Result support /// <summary> /// Ensure, that <see cref="WebNavigator"/> is set to a valid instance. /// </summary> /// <remarks> /// If <see cref="WebNavigator"/> is not already set, creates and sets a new <see cref="WebFormsResultWebNavigator"/> instance.<br/> /// Override this method if you don't want to inject a navigator, but need a different default. /// </remarks> protected virtual void InitializeNavigationSupport() { webNavigator = new WebFormsResultWebNavigator(this, null, null, true); } /// <summary> /// Gets/Sets the navigator to be used for handling <see cref="SetResult(string, object)"/> calls. /// </summary> public IWebNavigator WebNavigator { get { return webNavigator; } set { webNavigator = value; } } /// <summary> /// Gets or sets map of result names to target URLs /// </summary> /// <remarks> /// Using <see cref="Results"/> requires <see cref="WebNavigator"/> to implement <see cref="IResultWebNavigator"/>. /// </remarks> [Browsable( false )] [DesignerSerializationVisibility( DesignerSerializationVisibility.Hidden )] public virtual IDictionary Results { get { if (WebNavigator is IResultWebNavigator) { return ((IResultWebNavigator)WebNavigator).Results; } return null; } set { if (WebNavigator is IResultWebNavigator) { ((IResultWebNavigator)WebNavigator).Results = value; return; } throw new NotSupportedException("WebNavigator must be of type IResultWebNavigator to support Results"); } } /// <summary> /// A convenience, case-insensitive table that may be used to e.g. pass data into SpEL expressions"/>. /// </summary> /// <remarks> /// By default, e.g. <see cref="SetResult(string)"/> passes the control instance into an expression. Using /// <see cref="Args"/> is an easy way to pass additional parameters into the expression /// <example> /// // config: /// /// &lt;property Name=&quot;Results&quot;&gt; /// &lt;dictionary&gt; /// &lt;entry key=&quot;ok_clicked&quot; value=&quot;redirect:~/ShowResult.aspx?result=%{Args['result']}&quot; /&gt; /// &lt;/dictionary&gt; /// &lt;/property&gt; /// /// // code: /// /// void OnOkClicked(object sender, EventArgs e) /// { /// Args[&quot;result&quot;] = txtUserInput.Text; /// SetResult(&quot;ok_clicked&quot;); /// } /// </example> /// </remarks> public IDictionary Args { get { if (args == null) { args = new CaseInsensitiveHashtable(); } return args; } } /// <summary> /// Redirects user to a URL mapped to specified result name. /// </summary> /// <param name="resultName">Result name.</param> protected void SetResult( string resultName ) { WebNavigator.NavigateTo( resultName, this, null ); } /// <summary> /// Redirects user to a URL mapped to specified result name. /// </summary> /// <param name="resultName">Name of the result.</param> /// <param name="context">The context to use for evaluating the SpEL expression in the Result.</param> protected void SetResult( string resultName, object context ) { WebNavigator.NavigateTo( resultName, this, context ); } /// <summary> /// Returns a redirect url string that points to the /// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this /// result evaluated using this Page for expression /// </summary> /// <param name="resultName">Name of the result.</param> /// <returns>A redirect url string.</returns> protected string GetResultUrl( string resultName ) { return ResolveUrl( WebNavigator.GetResultUri( resultName, this, null ) ); } /// <summary> /// Returns a redirect url string that points to the /// <see cref="Spring.Web.Support.Result.TargetPage"/> defined by this /// result evaluated using this Page for expression /// </summary> /// <param name="resultName">Name of the result.</param> /// <param name="context">The context to use for evaluating the SpEL expression in the Result</param> /// <returns>A redirect url string.</returns> protected string GetResultUrl( string resultName, object context ) { return ResolveUrl( WebNavigator.GetResultUri( resultName, this, context ) ); } #endregion #region Validation support /// <summary> /// Evaluates specified validators and returns <c>True</c> if all of them are valid. /// </summary> /// <remarks> /// <p> /// Each validator can itself represent a collection of other validators if it is /// an instance of <see cref="ValidatorGroup"/> or one of its derived types. /// </p> /// <p> /// Please see the Validation Framework section in the documentation for more info. /// </p> /// </remarks> /// <param name="validationContext">Object to validate.</param> /// <param name="validators">Validators to evaluate.</param> /// <returns> /// <c>True</c> if all of the specified validators are valid, <c>False</c> otherwise. /// </returns> public virtual bool Validate(object validationContext, params IValidator[] validators) { IDictionary<string, object> contextParams = CreateValidatorParameters(); bool result = true; foreach (IValidator validator in validators) { if (validator == null) { throw new ArgumentException("Validator is not defined."); } result = validator.Validate(validationContext, contextParams, this.validationErrors) && result; } return result; } /// <summary> /// Gets the validation errors container. /// </summary> /// <value>The validation errors container.</value> public virtual IValidationErrors ValidationErrors { get { return validationErrors; } } /// <summary> /// Creates the validator parameters. /// </summary> /// <remarks> /// <para> /// This method can be overriden if you want to pass additional parameters /// to the validation framework, but you should make sure that you call /// this base implementation in order to add page, session, application, /// request, response and context to the variables collection. /// </para> /// </remarks> /// <returns> /// Dictionary containing parameters that should be passed to /// the data validation framework. /// </returns> protected virtual IDictionary<string, object> CreateValidatorParameters() { IDictionary<string, object> parameters = new Dictionary<string, object>(8); parameters["page"] = this.Page; parameters["usercontrol"] = this; parameters["session"] = this.Session; parameters["application"] = this.Application; parameters["request"] = this.Request; parameters["response"] = this.Response; parameters["context"] = this.Context; return parameters; } #endregion #region Spring Page support /// <summary> /// Overrides Page property to return <see cref="Spring.Web.UI.Page"/> /// instead of <see cref="System.Web.UI.Page"/>. /// </summary> [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Page Page { get { return (Page) base.Page; } } #endregion #region Dependency Injection Support /// <summary> /// Holds the default ApplicationContext to be used during DI. /// </summary> IApplicationContext ISupportsWebDependencyInjection.DefaultApplicationContext { get { return defaultApplicationContext; } set { defaultApplicationContext = value; } } /// <summary> /// Injects dependencies before adding the control. /// </summary> protected override void AddedControl(Control control,int index) { control = WebDependencyInjectionUtils.InjectDependenciesRecursive(defaultApplicationContext,control); base.AddedControl(control,index); } #endregion Dependency Injection Support } #endregion }
using System; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; using System.Collections; namespace fyiReporting.RdlDesign { public partial class RdlDesigner : System.Windows.Forms.Form { #region Windows Form Designer generated code Timer _IpcTimer = null; private MDIChild printChild=null; private DialogValidateRdl _ValidateRdl=null; private DockStyle _PropertiesLocation = DockStyle.Right; private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(RdlDesigner)); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.newReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.closeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.saveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.saveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.printToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pDFToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pDFOldStyleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tIFFToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cSVToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.excelToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dOCToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.rTFDOCToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.xMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.webPageHTMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.webArchiveSingleFileMHTToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.recentFilesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.cutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.copyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pasteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.deleteToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.selectAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator(); this.findToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.findNextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.replaceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.goToToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator7 = new System.Windows.Forms.ToolStripSeparator(); this.formatXMLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.viewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.designerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.rDLTextToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.previewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.showReportInBrowserToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.propertiesWindowsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.insertToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.chartToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.gridToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.imageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.lineToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.listToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.matrixToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.rectangleToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.subReportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tableToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.textboxToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.barCodeEAN13ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.barCodeBooklandToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataSetsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dataSourcesToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator8 = new System.Windows.Forms.ToolStripSeparator(); this.embeddedImagesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator9 = new System.Windows.Forms.ToolStripSeparator(); this.createSharedDataSourceToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.formatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.alignToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.leftsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.centersToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.rightsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator10 = new System.Windows.Forms.ToolStripSeparator(); this.topsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.middlesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.bottomsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sizeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.widthToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.heightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.bothToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.horizontalSpacingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.makeEqualToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.increaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.decreaseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.zeroToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.verticalSpacingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.makeEqualToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.increaseToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.decreaseToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.zeroToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator11 = new System.Windows.Forms.ToolStripSeparator(); this.paddingLeftToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.increaseToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.decreaseToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.zeroToolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem(); this.paddingRightToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.increaseToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.decreaseToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.zeroToolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem(); this.paddintTopToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.increaseToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.decreaseToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.zeroToolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem(); this.paddingBottomToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.increaseToolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.decreaseToolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.zeroToolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem(); this.toolsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.validateRDLToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator12 = new System.Windows.Forms.ToolStripSeparator(); this.startDesktopServerToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator13 = new System.Windows.Forms.ToolStripSeparator(); this.optionsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.windowToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.cascadeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.tileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.horizontalToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.verticallyToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.closeAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem1 = new System.Windows.Forms.ToolStripMenuItem(); this.supportToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.mainTB = new System.Windows.Forms.ToolStrip(); this.newToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.openToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.saveToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.cutToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.copyToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.pasteToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.undoToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.textboxToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.chartToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.tableToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.listToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.imageToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.matrixToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.subreportToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.rectangleToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.lineToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.fxToolStripLabel1 = new System.Windows.Forms.ToolStripLabel(); this.ctlEditTextbox = new System.Windows.Forms.ToolStripTextBox(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.boldToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.italiacToolStripButton1 = new System.Windows.Forms.ToolStripButton(); this.underlineToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.leftAlignToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.centerAlignToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.rightAlignToolStripButton3 = new System.Windows.Forms.ToolStripButton(); this.fontToolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.fontSizeToolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.printToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.zoomToolStripComboBox1 = new System.Windows.Forms.ToolStripComboBox(); this.selectToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.pdfToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.htmlToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.excelToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.XmlToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.MhtToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.CsvToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.RtfToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.TifToolStripButton2 = new System.Windows.Forms.ToolStripButton(); this.mainTC = new System.Windows.Forms.TabControl(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.foreColorPicker1 = new fyiReporting.RdlDesign.ColorPicker(); this.backColorPicker1 = new fyiReporting.RdlDesign.ColorPicker(); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.statusSelected = new System.Windows.Forms.ToolStripStatusLabel(); this.toolStripStatusLabel2 = new System.Windows.Forms.ToolStripStatusLabel(); this.statusPosition = new System.Windows.Forms.ToolStripStatusLabel(); this.mainSP = new System.Windows.Forms.Splitter(); this.mainProperties = new fyiReporting.RdlDesign.PropertyCtl(); this.ContextMenuTB = new System.Windows.Forms.ContextMenuStrip(this.components); this.MenuTBClose = new System.Windows.Forms.ToolStripMenuItem(); this.MenuTBSave = new System.Windows.Forms.ToolStripMenuItem(); this.MenuTBCloseAllButThis = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.mainTB.SuspendLayout(); this.toolStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.statusStrip1.SuspendLayout(); this.ContextMenuTB.SuspendLayout(); this.SuspendLayout(); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.viewToolStripMenuItem, this.insertToolStripMenuItem, this.dataToolStripMenuItem, this.formatToolStripMenuItem, this.toolsToolStripMenuItem, this.windowToolStripMenuItem, this.helpToolStripMenuItem}); resources.ApplyResources(this.menuStrip1, "menuStrip1"); this.menuStrip1.Name = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newReportToolStripMenuItem, this.openToolStripMenuItem, this.closeToolStripMenuItem, this.toolStripSeparator1, this.saveToolStripMenuItem, this.saveAsToolStripMenuItem, this.printToolStripMenuItem, this.exportToolStripMenuItem, this.toolStripSeparator2, this.recentFilesToolStripMenuItem, this.toolStripSeparator3, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; resources.ApplyResources(this.fileToolStripMenuItem, "fileToolStripMenuItem"); this.fileToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuFile_Popup); // // newReportToolStripMenuItem // this.newReportToolStripMenuItem.Name = "newReportToolStripMenuItem"; resources.ApplyResources(this.newReportToolStripMenuItem, "newReportToolStripMenuItem"); this.newReportToolStripMenuItem.Click += new System.EventHandler(this.menuFileNewReport_Click); // // openToolStripMenuItem // this.openToolStripMenuItem.Name = "openToolStripMenuItem"; resources.ApplyResources(this.openToolStripMenuItem, "openToolStripMenuItem"); this.openToolStripMenuItem.Click += new System.EventHandler(this.menuFileOpen_Click); // // closeToolStripMenuItem // this.closeToolStripMenuItem.Name = "closeToolStripMenuItem"; resources.ApplyResources(this.closeToolStripMenuItem, "closeToolStripMenuItem"); this.closeToolStripMenuItem.Click += new System.EventHandler(this.menuFileClose_Click); // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1"); // // saveToolStripMenuItem // resources.ApplyResources(this.saveToolStripMenuItem, "saveToolStripMenuItem"); this.saveToolStripMenuItem.Name = "saveToolStripMenuItem"; this.saveToolStripMenuItem.Click += new System.EventHandler(this.menuFileSave_Click); // // saveAsToolStripMenuItem // resources.ApplyResources(this.saveAsToolStripMenuItem, "saveAsToolStripMenuItem"); this.saveAsToolStripMenuItem.Name = "saveAsToolStripMenuItem"; this.saveAsToolStripMenuItem.Click += new System.EventHandler(this.menuFileSaveAs_Click); // // printToolStripMenuItem // resources.ApplyResources(this.printToolStripMenuItem, "printToolStripMenuItem"); this.printToolStripMenuItem.Name = "printToolStripMenuItem"; this.printToolStripMenuItem.Click += new System.EventHandler(this.menuFilePrint_Click); // // exportToolStripMenuItem // this.exportToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.pDFToolStripMenuItem, this.pDFOldStyleToolStripMenuItem, this.tIFFToolStripMenuItem, this.cSVToolStripMenuItem, this.excelToolStripMenuItem, this.dOCToolStripMenuItem, this.rTFDOCToolStripMenuItem, this.xMLToolStripMenuItem, this.webPageHTMLToolStripMenuItem, this.webArchiveSingleFileMHTToolStripMenuItem}); resources.ApplyResources(this.exportToolStripMenuItem, "exportToolStripMenuItem"); this.exportToolStripMenuItem.Name = "exportToolStripMenuItem"; // // pDFToolStripMenuItem // this.pDFToolStripMenuItem.Name = "pDFToolStripMenuItem"; resources.ApplyResources(this.pDFToolStripMenuItem, "pDFToolStripMenuItem"); this.pDFToolStripMenuItem.Click += new System.EventHandler(this.pDFToolStripMenuItem_Click); // // pDFOldStyleToolStripMenuItem // this.pDFOldStyleToolStripMenuItem.Name = "pDFOldStyleToolStripMenuItem"; resources.ApplyResources(this.pDFOldStyleToolStripMenuItem, "pDFOldStyleToolStripMenuItem"); this.pDFOldStyleToolStripMenuItem.Click += new System.EventHandler(this.pDFOldStyleToolStripMenuItem_Click); // // tIFFToolStripMenuItem // this.tIFFToolStripMenuItem.Name = "tIFFToolStripMenuItem"; resources.ApplyResources(this.tIFFToolStripMenuItem, "tIFFToolStripMenuItem"); this.tIFFToolStripMenuItem.Click += new System.EventHandler(this.tIFFToolStripMenuItem_Click); // // cSVToolStripMenuItem // this.cSVToolStripMenuItem.Name = "cSVToolStripMenuItem"; resources.ApplyResources(this.cSVToolStripMenuItem, "cSVToolStripMenuItem"); this.cSVToolStripMenuItem.Click += new System.EventHandler(this.cSVToolStripMenuItem_Click); // // excelToolStripMenuItem // this.excelToolStripMenuItem.Name = "excelToolStripMenuItem"; resources.ApplyResources(this.excelToolStripMenuItem, "excelToolStripMenuItem"); this.excelToolStripMenuItem.Click += new System.EventHandler(this.excelToolStripMenuItem_Click); // // dOCToolStripMenuItem // this.dOCToolStripMenuItem.Name = "dOCToolStripMenuItem"; resources.ApplyResources(this.dOCToolStripMenuItem, "dOCToolStripMenuItem"); this.dOCToolStripMenuItem.Click += new System.EventHandler(this.dOCToolStripMenuItem_Click); // // rTFDOCToolStripMenuItem // this.rTFDOCToolStripMenuItem.Name = "rTFDOCToolStripMenuItem"; resources.ApplyResources(this.rTFDOCToolStripMenuItem, "rTFDOCToolStripMenuItem"); this.rTFDOCToolStripMenuItem.Click += new System.EventHandler(this.rTFDOCToolStripMenuItem_Click); // // xMLToolStripMenuItem // this.xMLToolStripMenuItem.Name = "xMLToolStripMenuItem"; resources.ApplyResources(this.xMLToolStripMenuItem, "xMLToolStripMenuItem"); this.xMLToolStripMenuItem.Click += new System.EventHandler(this.xMLToolStripMenuItem_Click); // // webPageHTMLToolStripMenuItem // this.webPageHTMLToolStripMenuItem.Name = "webPageHTMLToolStripMenuItem"; resources.ApplyResources(this.webPageHTMLToolStripMenuItem, "webPageHTMLToolStripMenuItem"); this.webPageHTMLToolStripMenuItem.Click += new System.EventHandler(this.webPageHTMLToolStripMenuItem_Click); // // webArchiveSingleFileMHTToolStripMenuItem // this.webArchiveSingleFileMHTToolStripMenuItem.Name = "webArchiveSingleFileMHTToolStripMenuItem"; resources.ApplyResources(this.webArchiveSingleFileMHTToolStripMenuItem, "webArchiveSingleFileMHTToolStripMenuItem"); this.webArchiveSingleFileMHTToolStripMenuItem.Click += new System.EventHandler(this.webArchiveSingleFileMHTToolStripMenuItem_Click); // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2"); // // recentFilesToolStripMenuItem // resources.ApplyResources(this.recentFilesToolStripMenuItem, "recentFilesToolStripMenuItem"); this.recentFilesToolStripMenuItem.Name = "recentFilesToolStripMenuItem"; // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3"); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; resources.ApplyResources(this.exitToolStripMenuItem, "exitToolStripMenuItem"); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.undoToolStripMenuItem, this.redoToolStripMenuItem, this.toolStripSeparator4, this.cutToolStripMenuItem, this.copyToolStripMenuItem, this.pasteToolStripMenuItem, this.deleteToolStripMenuItem, this.toolStripSeparator5, this.selectAllToolStripMenuItem, this.toolStripSeparator6, this.findToolStripMenuItem, this.findNextToolStripMenuItem, this.replaceToolStripMenuItem, this.goToToolStripMenuItem, this.toolStripSeparator7, this.formatXMLToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; resources.ApplyResources(this.editToolStripMenuItem, "editToolStripMenuItem"); this.editToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuEdit_Popup); // // undoToolStripMenuItem // this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; resources.ApplyResources(this.undoToolStripMenuItem, "undoToolStripMenuItem"); this.undoToolStripMenuItem.Click += new System.EventHandler(this.menuEditUndo_Click); // // redoToolStripMenuItem // this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; resources.ApplyResources(this.redoToolStripMenuItem, "redoToolStripMenuItem"); this.redoToolStripMenuItem.Click += new System.EventHandler(this.menuEditRedo_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4"); // // cutToolStripMenuItem // this.cutToolStripMenuItem.Name = "cutToolStripMenuItem"; resources.ApplyResources(this.cutToolStripMenuItem, "cutToolStripMenuItem"); this.cutToolStripMenuItem.Click += new System.EventHandler(this.menuEditCut_Click); // // copyToolStripMenuItem // this.copyToolStripMenuItem.Name = "copyToolStripMenuItem"; resources.ApplyResources(this.copyToolStripMenuItem, "copyToolStripMenuItem"); this.copyToolStripMenuItem.Click += new System.EventHandler(this.menuEditCopy_Click); // // pasteToolStripMenuItem // this.pasteToolStripMenuItem.Name = "pasteToolStripMenuItem"; resources.ApplyResources(this.pasteToolStripMenuItem, "pasteToolStripMenuItem"); this.pasteToolStripMenuItem.Click += new System.EventHandler(this.menuEditPaste_Click); // // deleteToolStripMenuItem // this.deleteToolStripMenuItem.Name = "deleteToolStripMenuItem"; resources.ApplyResources(this.deleteToolStripMenuItem, "deleteToolStripMenuItem"); this.deleteToolStripMenuItem.Click += new System.EventHandler(this.menuEditDelete_Click); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5"); // // selectAllToolStripMenuItem // this.selectAllToolStripMenuItem.Name = "selectAllToolStripMenuItem"; resources.ApplyResources(this.selectAllToolStripMenuItem, "selectAllToolStripMenuItem"); this.selectAllToolStripMenuItem.Click += new System.EventHandler(this.menuEditSelectAll_Click); // // toolStripSeparator6 // this.toolStripSeparator6.Name = "toolStripSeparator6"; resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6"); // // findToolStripMenuItem // this.findToolStripMenuItem.Name = "findToolStripMenuItem"; resources.ApplyResources(this.findToolStripMenuItem, "findToolStripMenuItem"); this.findToolStripMenuItem.Click += new System.EventHandler(this.menuEditFind_Click); // // findNextToolStripMenuItem // this.findNextToolStripMenuItem.Name = "findNextToolStripMenuItem"; resources.ApplyResources(this.findNextToolStripMenuItem, "findNextToolStripMenuItem"); this.findNextToolStripMenuItem.Click += new System.EventHandler(this.menuEditFindNext_Click); // // replaceToolStripMenuItem // this.replaceToolStripMenuItem.Name = "replaceToolStripMenuItem"; resources.ApplyResources(this.replaceToolStripMenuItem, "replaceToolStripMenuItem"); this.replaceToolStripMenuItem.Click += new System.EventHandler(this.menuEditReplace_Click); // // goToToolStripMenuItem // this.goToToolStripMenuItem.Name = "goToToolStripMenuItem"; resources.ApplyResources(this.goToToolStripMenuItem, "goToToolStripMenuItem"); this.goToToolStripMenuItem.Click += new System.EventHandler(this.menuEditGoto_Click); // // toolStripSeparator7 // this.toolStripSeparator7.Name = "toolStripSeparator7"; resources.ApplyResources(this.toolStripSeparator7, "toolStripSeparator7"); // // formatXMLToolStripMenuItem // this.formatXMLToolStripMenuItem.Name = "formatXMLToolStripMenuItem"; resources.ApplyResources(this.formatXMLToolStripMenuItem, "formatXMLToolStripMenuItem"); this.formatXMLToolStripMenuItem.Click += new System.EventHandler(this.menuEdit_FormatXml); // // viewToolStripMenuItem // this.viewToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.designerToolStripMenuItem, this.rDLTextToolStripMenuItem, this.previewToolStripMenuItem, this.showReportInBrowserToolStripMenuItem, this.propertiesWindowsToolStripMenuItem}); this.viewToolStripMenuItem.Name = "viewToolStripMenuItem"; resources.ApplyResources(this.viewToolStripMenuItem, "viewToolStripMenuItem"); this.viewToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuView_Popup); // // designerToolStripMenuItem // this.designerToolStripMenuItem.Name = "designerToolStripMenuItem"; resources.ApplyResources(this.designerToolStripMenuItem, "designerToolStripMenuItem"); this.designerToolStripMenuItem.Click += new System.EventHandler(this.menuViewDesigner_Click); // // rDLTextToolStripMenuItem // this.rDLTextToolStripMenuItem.Name = "rDLTextToolStripMenuItem"; resources.ApplyResources(this.rDLTextToolStripMenuItem, "rDLTextToolStripMenuItem"); this.rDLTextToolStripMenuItem.Click += new System.EventHandler(this.menuViewRDL_Click); // // previewToolStripMenuItem // this.previewToolStripMenuItem.Name = "previewToolStripMenuItem"; resources.ApplyResources(this.previewToolStripMenuItem, "previewToolStripMenuItem"); this.previewToolStripMenuItem.Click += new System.EventHandler(this.menuViewPreview_Click); // // showReportInBrowserToolStripMenuItem // this.showReportInBrowserToolStripMenuItem.Name = "showReportInBrowserToolStripMenuItem"; resources.ApplyResources(this.showReportInBrowserToolStripMenuItem, "showReportInBrowserToolStripMenuItem"); this.showReportInBrowserToolStripMenuItem.Click += new System.EventHandler(this.menuViewBrowser_Click); // // propertiesWindowsToolStripMenuItem // this.propertiesWindowsToolStripMenuItem.Name = "propertiesWindowsToolStripMenuItem"; resources.ApplyResources(this.propertiesWindowsToolStripMenuItem, "propertiesWindowsToolStripMenuItem"); this.propertiesWindowsToolStripMenuItem.Click += new System.EventHandler(this.menuEditProperties_Click); // // insertToolStripMenuItem // this.insertToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.chartToolStripMenuItem, this.gridToolStripMenuItem, this.imageToolStripMenuItem, this.lineToolStripMenuItem, this.listToolStripMenuItem, this.matrixToolStripMenuItem, this.rectangleToolStripMenuItem, this.subReportToolStripMenuItem, this.tableToolStripMenuItem, this.textboxToolStripMenuItem, this.barCodeEAN13ToolStripMenuItem, this.barCodeBooklandToolStripMenuItem}); this.insertToolStripMenuItem.Name = "insertToolStripMenuItem"; resources.ApplyResources(this.insertToolStripMenuItem, "insertToolStripMenuItem"); // // chartToolStripMenuItem // this.chartToolStripMenuItem.Name = "chartToolStripMenuItem"; resources.ApplyResources(this.chartToolStripMenuItem, "chartToolStripMenuItem"); this.chartToolStripMenuItem.Tag = "Chart"; this.chartToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // gridToolStripMenuItem // this.gridToolStripMenuItem.Name = "gridToolStripMenuItem"; resources.ApplyResources(this.gridToolStripMenuItem, "gridToolStripMenuItem"); this.gridToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // imageToolStripMenuItem // this.imageToolStripMenuItem.Name = "imageToolStripMenuItem"; resources.ApplyResources(this.imageToolStripMenuItem, "imageToolStripMenuItem"); this.imageToolStripMenuItem.Tag = "Image"; this.imageToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // lineToolStripMenuItem // this.lineToolStripMenuItem.Name = "lineToolStripMenuItem"; resources.ApplyResources(this.lineToolStripMenuItem, "lineToolStripMenuItem"); this.lineToolStripMenuItem.Tag = "Line"; this.lineToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // listToolStripMenuItem // this.listToolStripMenuItem.Name = "listToolStripMenuItem"; resources.ApplyResources(this.listToolStripMenuItem, "listToolStripMenuItem"); this.listToolStripMenuItem.Tag = "List"; this.listToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // matrixToolStripMenuItem // this.matrixToolStripMenuItem.Name = "matrixToolStripMenuItem"; resources.ApplyResources(this.matrixToolStripMenuItem, "matrixToolStripMenuItem"); this.matrixToolStripMenuItem.Tag = "Matrix"; this.matrixToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // rectangleToolStripMenuItem // this.rectangleToolStripMenuItem.Name = "rectangleToolStripMenuItem"; resources.ApplyResources(this.rectangleToolStripMenuItem, "rectangleToolStripMenuItem"); this.rectangleToolStripMenuItem.Tag = "Rectangle"; this.rectangleToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // subReportToolStripMenuItem // this.subReportToolStripMenuItem.Name = "subReportToolStripMenuItem"; resources.ApplyResources(this.subReportToolStripMenuItem, "subReportToolStripMenuItem"); this.subReportToolStripMenuItem.Tag = "Subreport"; this.subReportToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // tableToolStripMenuItem // this.tableToolStripMenuItem.Name = "tableToolStripMenuItem"; resources.ApplyResources(this.tableToolStripMenuItem, "tableToolStripMenuItem"); this.tableToolStripMenuItem.Tag = "Table"; this.tableToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // textboxToolStripMenuItem // this.textboxToolStripMenuItem.Name = "textboxToolStripMenuItem"; resources.ApplyResources(this.textboxToolStripMenuItem, "textboxToolStripMenuItem"); this.textboxToolStripMenuItem.Tag = "Textbox"; this.textboxToolStripMenuItem.Click += new System.EventHandler(this.InsertToolStripMenuItem_Click); // // barCodeEAN13ToolStripMenuItem // this.barCodeEAN13ToolStripMenuItem.Name = "barCodeEAN13ToolStripMenuItem"; resources.ApplyResources(this.barCodeEAN13ToolStripMenuItem, "barCodeEAN13ToolStripMenuItem"); // // barCodeBooklandToolStripMenuItem // this.barCodeBooklandToolStripMenuItem.Name = "barCodeBooklandToolStripMenuItem"; resources.ApplyResources(this.barCodeBooklandToolStripMenuItem, "barCodeBooklandToolStripMenuItem"); // // dataToolStripMenuItem // this.dataToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.dataSetsToolStripMenuItem, this.dataSourcesToolStripMenuItem1, this.toolStripSeparator8, this.embeddedImagesToolStripMenuItem, this.toolStripSeparator9, this.createSharedDataSourceToolStripMenuItem}); this.dataToolStripMenuItem.Name = "dataToolStripMenuItem"; resources.ApplyResources(this.dataToolStripMenuItem, "dataToolStripMenuItem"); this.dataToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuData_Popup); // // dataSetsToolStripMenuItem // this.dataSetsToolStripMenuItem.Name = "dataSetsToolStripMenuItem"; resources.ApplyResources(this.dataSetsToolStripMenuItem, "dataSetsToolStripMenuItem"); // // dataSourcesToolStripMenuItem1 // this.dataSourcesToolStripMenuItem1.Name = "dataSourcesToolStripMenuItem1"; resources.ApplyResources(this.dataSourcesToolStripMenuItem1, "dataSourcesToolStripMenuItem1"); this.dataSourcesToolStripMenuItem1.Click += new System.EventHandler(this.dataSourcesToolStripMenuItem1_Click); // // toolStripSeparator8 // this.toolStripSeparator8.Name = "toolStripSeparator8"; resources.ApplyResources(this.toolStripSeparator8, "toolStripSeparator8"); // // embeddedImagesToolStripMenuItem // this.embeddedImagesToolStripMenuItem.Name = "embeddedImagesToolStripMenuItem"; resources.ApplyResources(this.embeddedImagesToolStripMenuItem, "embeddedImagesToolStripMenuItem"); this.embeddedImagesToolStripMenuItem.Click += new System.EventHandler(this.embeddedImagesToolStripMenuItem_Click); // // toolStripSeparator9 // this.toolStripSeparator9.Name = "toolStripSeparator9"; resources.ApplyResources(this.toolStripSeparator9, "toolStripSeparator9"); // // createSharedDataSourceToolStripMenuItem // this.createSharedDataSourceToolStripMenuItem.Name = "createSharedDataSourceToolStripMenuItem"; resources.ApplyResources(this.createSharedDataSourceToolStripMenuItem, "createSharedDataSourceToolStripMenuItem"); this.createSharedDataSourceToolStripMenuItem.Click += new System.EventHandler(this.menuFileNewDataSourceRef_Click); // // formatToolStripMenuItem // this.formatToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.alignToolStripMenuItem, this.sizeToolStripMenuItem, this.horizontalSpacingToolStripMenuItem, this.verticalSpacingToolStripMenuItem, this.toolStripSeparator11, this.paddingLeftToolStripMenuItem, this.paddingRightToolStripMenuItem, this.paddintTopToolStripMenuItem, this.paddingBottomToolStripMenuItem}); this.formatToolStripMenuItem.Name = "formatToolStripMenuItem"; resources.ApplyResources(this.formatToolStripMenuItem, "formatToolStripMenuItem"); this.formatToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuFormat_Popup); // // alignToolStripMenuItem // this.alignToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.leftsToolStripMenuItem, this.centersToolStripMenuItem, this.rightsToolStripMenuItem, this.toolStripSeparator10, this.topsToolStripMenuItem, this.middlesToolStripMenuItem, this.bottomsToolStripMenuItem}); this.alignToolStripMenuItem.Name = "alignToolStripMenuItem"; resources.ApplyResources(this.alignToolStripMenuItem, "alignToolStripMenuItem"); // // leftsToolStripMenuItem // this.leftsToolStripMenuItem.Name = "leftsToolStripMenuItem"; resources.ApplyResources(this.leftsToolStripMenuItem, "leftsToolStripMenuItem"); this.leftsToolStripMenuItem.Click += new System.EventHandler(this.menuFormatAlignL_Click); // // centersToolStripMenuItem // this.centersToolStripMenuItem.Name = "centersToolStripMenuItem"; resources.ApplyResources(this.centersToolStripMenuItem, "centersToolStripMenuItem"); this.centersToolStripMenuItem.Click += new System.EventHandler(this.menuFormatAlignC_Click); // // rightsToolStripMenuItem // this.rightsToolStripMenuItem.Name = "rightsToolStripMenuItem"; resources.ApplyResources(this.rightsToolStripMenuItem, "rightsToolStripMenuItem"); this.rightsToolStripMenuItem.Click += new System.EventHandler(this.menuFormatAlignR_Click); // // toolStripSeparator10 // this.toolStripSeparator10.Name = "toolStripSeparator10"; resources.ApplyResources(this.toolStripSeparator10, "toolStripSeparator10"); // // topsToolStripMenuItem // this.topsToolStripMenuItem.Name = "topsToolStripMenuItem"; resources.ApplyResources(this.topsToolStripMenuItem, "topsToolStripMenuItem"); this.topsToolStripMenuItem.Click += new System.EventHandler(this.menuFormatAlignT_Click); // // middlesToolStripMenuItem // this.middlesToolStripMenuItem.Name = "middlesToolStripMenuItem"; resources.ApplyResources(this.middlesToolStripMenuItem, "middlesToolStripMenuItem"); this.middlesToolStripMenuItem.Click += new System.EventHandler(this.menuFormatAlignM_Click); // // bottomsToolStripMenuItem // this.bottomsToolStripMenuItem.Name = "bottomsToolStripMenuItem"; resources.ApplyResources(this.bottomsToolStripMenuItem, "bottomsToolStripMenuItem"); this.bottomsToolStripMenuItem.Click += new System.EventHandler(this.menuFormatAlignB_Click); // // sizeToolStripMenuItem // this.sizeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.widthToolStripMenuItem, this.heightToolStripMenuItem, this.bothToolStripMenuItem}); this.sizeToolStripMenuItem.Name = "sizeToolStripMenuItem"; resources.ApplyResources(this.sizeToolStripMenuItem, "sizeToolStripMenuItem"); // // widthToolStripMenuItem // this.widthToolStripMenuItem.Name = "widthToolStripMenuItem"; resources.ApplyResources(this.widthToolStripMenuItem, "widthToolStripMenuItem"); this.widthToolStripMenuItem.Click += new System.EventHandler(this.menuFormatSizeW_Click); // // heightToolStripMenuItem // this.heightToolStripMenuItem.Name = "heightToolStripMenuItem"; resources.ApplyResources(this.heightToolStripMenuItem, "heightToolStripMenuItem"); this.heightToolStripMenuItem.Click += new System.EventHandler(this.menuFormatSizeH_Click); // // bothToolStripMenuItem // this.bothToolStripMenuItem.Name = "bothToolStripMenuItem"; resources.ApplyResources(this.bothToolStripMenuItem, "bothToolStripMenuItem"); this.bothToolStripMenuItem.Click += new System.EventHandler(this.menuFormatSizeB_Click); // // horizontalSpacingToolStripMenuItem // this.horizontalSpacingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.makeEqualToolStripMenuItem, this.increaseToolStripMenuItem, this.decreaseToolStripMenuItem, this.zeroToolStripMenuItem}); this.horizontalSpacingToolStripMenuItem.Name = "horizontalSpacingToolStripMenuItem"; resources.ApplyResources(this.horizontalSpacingToolStripMenuItem, "horizontalSpacingToolStripMenuItem"); // // makeEqualToolStripMenuItem // this.makeEqualToolStripMenuItem.Name = "makeEqualToolStripMenuItem"; resources.ApplyResources(this.makeEqualToolStripMenuItem, "makeEqualToolStripMenuItem"); this.makeEqualToolStripMenuItem.Click += new System.EventHandler(this.menuFormatHorzE_Click); // // increaseToolStripMenuItem // this.increaseToolStripMenuItem.Name = "increaseToolStripMenuItem"; resources.ApplyResources(this.increaseToolStripMenuItem, "increaseToolStripMenuItem"); this.increaseToolStripMenuItem.Click += new System.EventHandler(this.menuFormatHorzI_Click); // // decreaseToolStripMenuItem // this.decreaseToolStripMenuItem.Name = "decreaseToolStripMenuItem"; resources.ApplyResources(this.decreaseToolStripMenuItem, "decreaseToolStripMenuItem"); this.decreaseToolStripMenuItem.Click += new System.EventHandler(this.menuFormatHorzD_Click); // // zeroToolStripMenuItem // this.zeroToolStripMenuItem.Name = "zeroToolStripMenuItem"; resources.ApplyResources(this.zeroToolStripMenuItem, "zeroToolStripMenuItem"); this.zeroToolStripMenuItem.Click += new System.EventHandler(this.menuFormatHorzZ_Click); // // verticalSpacingToolStripMenuItem // this.verticalSpacingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.makeEqualToolStripMenuItem1, this.increaseToolStripMenuItem1, this.decreaseToolStripMenuItem1, this.zeroToolStripMenuItem1}); this.verticalSpacingToolStripMenuItem.Name = "verticalSpacingToolStripMenuItem"; resources.ApplyResources(this.verticalSpacingToolStripMenuItem, "verticalSpacingToolStripMenuItem"); // // makeEqualToolStripMenuItem1 // this.makeEqualToolStripMenuItem1.Name = "makeEqualToolStripMenuItem1"; resources.ApplyResources(this.makeEqualToolStripMenuItem1, "makeEqualToolStripMenuItem1"); this.makeEqualToolStripMenuItem1.Click += new System.EventHandler(this.menuFormatVertE_Click); // // increaseToolStripMenuItem1 // this.increaseToolStripMenuItem1.Name = "increaseToolStripMenuItem1"; resources.ApplyResources(this.increaseToolStripMenuItem1, "increaseToolStripMenuItem1"); this.increaseToolStripMenuItem1.Click += new System.EventHandler(this.menuFormatVertI_Click); // // decreaseToolStripMenuItem1 // this.decreaseToolStripMenuItem1.Name = "decreaseToolStripMenuItem1"; resources.ApplyResources(this.decreaseToolStripMenuItem1, "decreaseToolStripMenuItem1"); this.decreaseToolStripMenuItem1.Click += new System.EventHandler(this.menuFormatVertD_Click); // // zeroToolStripMenuItem1 // this.zeroToolStripMenuItem1.Name = "zeroToolStripMenuItem1"; resources.ApplyResources(this.zeroToolStripMenuItem1, "zeroToolStripMenuItem1"); this.zeroToolStripMenuItem1.Click += new System.EventHandler(this.menuFormatVertZ_Click); // // toolStripSeparator11 // this.toolStripSeparator11.Name = "toolStripSeparator11"; resources.ApplyResources(this.toolStripSeparator11, "toolStripSeparator11"); // // paddingLeftToolStripMenuItem // this.paddingLeftToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.increaseToolStripMenuItem2, this.decreaseToolStripMenuItem2, this.zeroToolStripMenuItem2}); this.paddingLeftToolStripMenuItem.Name = "paddingLeftToolStripMenuItem"; resources.ApplyResources(this.paddingLeftToolStripMenuItem, "paddingLeftToolStripMenuItem"); // // increaseToolStripMenuItem2 // this.increaseToolStripMenuItem2.Name = "increaseToolStripMenuItem2"; resources.ApplyResources(this.increaseToolStripMenuItem2, "increaseToolStripMenuItem2"); this.increaseToolStripMenuItem2.Click += new System.EventHandler(this.menuFormatPadding_Click); // // decreaseToolStripMenuItem2 // this.decreaseToolStripMenuItem2.Name = "decreaseToolStripMenuItem2"; resources.ApplyResources(this.decreaseToolStripMenuItem2, "decreaseToolStripMenuItem2"); this.decreaseToolStripMenuItem2.Click += new System.EventHandler(this.menuFormatPadding_Click); // // zeroToolStripMenuItem2 // this.zeroToolStripMenuItem2.Name = "zeroToolStripMenuItem2"; resources.ApplyResources(this.zeroToolStripMenuItem2, "zeroToolStripMenuItem2"); this.zeroToolStripMenuItem2.Click += new System.EventHandler(this.menuFormatPadding_Click); // // paddingRightToolStripMenuItem // this.paddingRightToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.increaseToolStripMenuItem3, this.decreaseToolStripMenuItem3, this.zeroToolStripMenuItem3}); this.paddingRightToolStripMenuItem.Name = "paddingRightToolStripMenuItem"; resources.ApplyResources(this.paddingRightToolStripMenuItem, "paddingRightToolStripMenuItem"); // // increaseToolStripMenuItem3 // this.increaseToolStripMenuItem3.Name = "increaseToolStripMenuItem3"; resources.ApplyResources(this.increaseToolStripMenuItem3, "increaseToolStripMenuItem3"); this.increaseToolStripMenuItem3.Click += new System.EventHandler(this.menuFormatPadding_Click); // // decreaseToolStripMenuItem3 // this.decreaseToolStripMenuItem3.Name = "decreaseToolStripMenuItem3"; resources.ApplyResources(this.decreaseToolStripMenuItem3, "decreaseToolStripMenuItem3"); this.decreaseToolStripMenuItem3.Click += new System.EventHandler(this.menuFormatPadding_Click); // // zeroToolStripMenuItem3 // this.zeroToolStripMenuItem3.Name = "zeroToolStripMenuItem3"; resources.ApplyResources(this.zeroToolStripMenuItem3, "zeroToolStripMenuItem3"); this.zeroToolStripMenuItem3.Click += new System.EventHandler(this.menuFormatPadding_Click); // // paddintTopToolStripMenuItem // this.paddintTopToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.increaseToolStripMenuItem4, this.decreaseToolStripMenuItem4, this.zeroToolStripMenuItem4}); this.paddintTopToolStripMenuItem.Name = "paddintTopToolStripMenuItem"; resources.ApplyResources(this.paddintTopToolStripMenuItem, "paddintTopToolStripMenuItem"); // // increaseToolStripMenuItem4 // this.increaseToolStripMenuItem4.Name = "increaseToolStripMenuItem4"; resources.ApplyResources(this.increaseToolStripMenuItem4, "increaseToolStripMenuItem4"); this.increaseToolStripMenuItem4.Click += new System.EventHandler(this.menuFormatPadding_Click); // // decreaseToolStripMenuItem4 // this.decreaseToolStripMenuItem4.Name = "decreaseToolStripMenuItem4"; resources.ApplyResources(this.decreaseToolStripMenuItem4, "decreaseToolStripMenuItem4"); this.decreaseToolStripMenuItem4.Click += new System.EventHandler(this.menuFormatPadding_Click); // // zeroToolStripMenuItem4 // this.zeroToolStripMenuItem4.Name = "zeroToolStripMenuItem4"; resources.ApplyResources(this.zeroToolStripMenuItem4, "zeroToolStripMenuItem4"); this.zeroToolStripMenuItem4.Click += new System.EventHandler(this.menuFormatPadding_Click); // // paddingBottomToolStripMenuItem // this.paddingBottomToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.increaseToolStripMenuItem5, this.decreaseToolStripMenuItem5, this.zeroToolStripMenuItem5}); this.paddingBottomToolStripMenuItem.Name = "paddingBottomToolStripMenuItem"; resources.ApplyResources(this.paddingBottomToolStripMenuItem, "paddingBottomToolStripMenuItem"); // // increaseToolStripMenuItem5 // this.increaseToolStripMenuItem5.Name = "increaseToolStripMenuItem5"; resources.ApplyResources(this.increaseToolStripMenuItem5, "increaseToolStripMenuItem5"); this.increaseToolStripMenuItem5.Click += new System.EventHandler(this.menuFormatPadding_Click); // // decreaseToolStripMenuItem5 // this.decreaseToolStripMenuItem5.Name = "decreaseToolStripMenuItem5"; resources.ApplyResources(this.decreaseToolStripMenuItem5, "decreaseToolStripMenuItem5"); this.decreaseToolStripMenuItem5.Click += new System.EventHandler(this.menuFormatPadding_Click); // // zeroToolStripMenuItem5 // this.zeroToolStripMenuItem5.Name = "zeroToolStripMenuItem5"; resources.ApplyResources(this.zeroToolStripMenuItem5, "zeroToolStripMenuItem5"); this.zeroToolStripMenuItem5.Click += new System.EventHandler(this.menuFormatPadding_Click); // // toolsToolStripMenuItem // this.toolsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.validateRDLToolStripMenuItem, this.toolStripSeparator12, this.startDesktopServerToolStripMenuItem, this.toolStripSeparator13, this.optionsToolStripMenuItem}); this.toolsToolStripMenuItem.Name = "toolsToolStripMenuItem"; resources.ApplyResources(this.toolsToolStripMenuItem, "toolsToolStripMenuItem"); this.toolsToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuTools_Popup); // // validateRDLToolStripMenuItem // this.validateRDLToolStripMenuItem.Name = "validateRDLToolStripMenuItem"; resources.ApplyResources(this.validateRDLToolStripMenuItem, "validateRDLToolStripMenuItem"); this.validateRDLToolStripMenuItem.Click += new System.EventHandler(this.menuToolsValidateSchema_Click); // // toolStripSeparator12 // this.toolStripSeparator12.Name = "toolStripSeparator12"; resources.ApplyResources(this.toolStripSeparator12, "toolStripSeparator12"); // // startDesktopServerToolStripMenuItem // this.startDesktopServerToolStripMenuItem.Name = "startDesktopServerToolStripMenuItem"; resources.ApplyResources(this.startDesktopServerToolStripMenuItem, "startDesktopServerToolStripMenuItem"); this.startDesktopServerToolStripMenuItem.Click += new System.EventHandler(this.menuToolsProcess_Click); // // toolStripSeparator13 // this.toolStripSeparator13.Name = "toolStripSeparator13"; resources.ApplyResources(this.toolStripSeparator13, "toolStripSeparator13"); // // optionsToolStripMenuItem // this.optionsToolStripMenuItem.Name = "optionsToolStripMenuItem"; resources.ApplyResources(this.optionsToolStripMenuItem, "optionsToolStripMenuItem"); this.optionsToolStripMenuItem.Click += new System.EventHandler(this.menuToolsOptions_Click); // // windowToolStripMenuItem // this.windowToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.cascadeToolStripMenuItem, this.tileToolStripMenuItem, this.closeAllToolStripMenuItem}); this.windowToolStripMenuItem.Name = "windowToolStripMenuItem"; resources.ApplyResources(this.windowToolStripMenuItem, "windowToolStripMenuItem"); this.windowToolStripMenuItem.DropDownOpening += new System.EventHandler(this.menuWnd_Popup); // // cascadeToolStripMenuItem // this.cascadeToolStripMenuItem.Name = "cascadeToolStripMenuItem"; resources.ApplyResources(this.cascadeToolStripMenuItem, "cascadeToolStripMenuItem"); this.cascadeToolStripMenuItem.Click += new System.EventHandler(this.menuWndCascade_Click); // // tileToolStripMenuItem // this.tileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.horizontalToolStripMenuItem, this.verticallyToolStripMenuItem}); this.tileToolStripMenuItem.Name = "tileToolStripMenuItem"; resources.ApplyResources(this.tileToolStripMenuItem, "tileToolStripMenuItem"); // // horizontalToolStripMenuItem // this.horizontalToolStripMenuItem.Name = "horizontalToolStripMenuItem"; resources.ApplyResources(this.horizontalToolStripMenuItem, "horizontalToolStripMenuItem"); this.horizontalToolStripMenuItem.Click += new System.EventHandler(this.menuWndTileH_Click); // // verticallyToolStripMenuItem // this.verticallyToolStripMenuItem.Name = "verticallyToolStripMenuItem"; resources.ApplyResources(this.verticallyToolStripMenuItem, "verticallyToolStripMenuItem"); this.verticallyToolStripMenuItem.Click += new System.EventHandler(this.menuWndTileV_Click); // // closeAllToolStripMenuItem // this.closeAllToolStripMenuItem.Name = "closeAllToolStripMenuItem"; resources.ApplyResources(this.closeAllToolStripMenuItem, "closeAllToolStripMenuItem"); this.closeAllToolStripMenuItem.Click += new System.EventHandler(this.menuWndCloseAll_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.helpToolStripMenuItem1, this.supportToolStripMenuItem, this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; resources.ApplyResources(this.helpToolStripMenuItem, "helpToolStripMenuItem"); // // helpToolStripMenuItem1 // this.helpToolStripMenuItem1.Name = "helpToolStripMenuItem1"; resources.ApplyResources(this.helpToolStripMenuItem1, "helpToolStripMenuItem1"); this.helpToolStripMenuItem1.Click += new System.EventHandler(this.menuHelpHelp_Click); // // supportToolStripMenuItem // this.supportToolStripMenuItem.Name = "supportToolStripMenuItem"; resources.ApplyResources(this.supportToolStripMenuItem, "supportToolStripMenuItem"); this.supportToolStripMenuItem.Click += new System.EventHandler(this.menuHelpSupport_Click); // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; resources.ApplyResources(this.aboutToolStripMenuItem, "aboutToolStripMenuItem"); this.aboutToolStripMenuItem.Click += new System.EventHandler(this.menuHelpAbout_Click); // // mainTB // this.mainTB.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.newToolStripButton1, this.openToolStripButton1, this.saveToolStripButton1, this.cutToolStripButton1, this.copyToolStripButton1, this.pasteToolStripButton1, this.undoToolStripButton1, this.textboxToolStripButton1, this.chartToolStripButton1, this.tableToolStripButton1, this.listToolStripButton1, this.imageToolStripButton1, this.matrixToolStripButton1, this.subreportToolStripButton1, this.rectangleToolStripButton1, this.lineToolStripButton1, this.fxToolStripLabel1, this.ctlEditTextbox}); resources.ApplyResources(this.mainTB, "mainTB"); this.mainTB.Name = "mainTB"; // // newToolStripButton1 // this.newToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.newToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.document_new; resources.ApplyResources(this.newToolStripButton1, "newToolStripButton1"); this.newToolStripButton1.Name = "newToolStripButton1"; this.newToolStripButton1.Tag = "New"; this.newToolStripButton1.Click += new System.EventHandler(this.menuFileNewReport_Click); // // openToolStripButton1 // this.openToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.openToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.document_open; resources.ApplyResources(this.openToolStripButton1, "openToolStripButton1"); this.openToolStripButton1.Name = "openToolStripButton1"; this.openToolStripButton1.Tag = "Open"; this.openToolStripButton1.Click += new System.EventHandler(this.menuFileOpen_Click); // // saveToolStripButton1 // this.saveToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.saveToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.document_save; resources.ApplyResources(this.saveToolStripButton1, "saveToolStripButton1"); this.saveToolStripButton1.Name = "saveToolStripButton1"; this.saveToolStripButton1.Tag = "Save"; this.saveToolStripButton1.Click += new System.EventHandler(this.menuFileSave_Click); // // cutToolStripButton1 // this.cutToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.cutToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.edit_cut; resources.ApplyResources(this.cutToolStripButton1, "cutToolStripButton1"); this.cutToolStripButton1.Name = "cutToolStripButton1"; this.cutToolStripButton1.Tag = "Cut"; this.cutToolStripButton1.Click += new System.EventHandler(this.menuEditCut_Click); // // copyToolStripButton1 // this.copyToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.copyToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.edit_copy; resources.ApplyResources(this.copyToolStripButton1, "copyToolStripButton1"); this.copyToolStripButton1.Name = "copyToolStripButton1"; this.copyToolStripButton1.Tag = "Copy"; this.copyToolStripButton1.Click += new System.EventHandler(this.menuEditCopy_Click); // // pasteToolStripButton1 // this.pasteToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.pasteToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.edit_paste; resources.ApplyResources(this.pasteToolStripButton1, "pasteToolStripButton1"); this.pasteToolStripButton1.Name = "pasteToolStripButton1"; this.pasteToolStripButton1.Tag = "Paste"; this.pasteToolStripButton1.Click += new System.EventHandler(this.menuEditPaste_Click); // // undoToolStripButton1 // this.undoToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.undoToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.edit_undo; resources.ApplyResources(this.undoToolStripButton1, "undoToolStripButton1"); this.undoToolStripButton1.Name = "undoToolStripButton1"; this.undoToolStripButton1.Tag = "Undo"; this.undoToolStripButton1.Click += new System.EventHandler(this.menuEditUndo_Click); // // textboxToolStripButton1 // this.textboxToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.textboxToolStripButton1, "textboxToolStripButton1"); this.textboxToolStripButton1.Name = "textboxToolStripButton1"; this.textboxToolStripButton1.Tag = "Textbox"; this.textboxToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // chartToolStripButton1 // this.chartToolStripButton1.CheckOnClick = true; this.chartToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.chart; resources.ApplyResources(this.chartToolStripButton1, "chartToolStripButton1"); this.chartToolStripButton1.Name = "chartToolStripButton1"; this.chartToolStripButton1.Tag = "Chart"; this.chartToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // tableToolStripButton1 // this.tableToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.tableToolStripButton1, "tableToolStripButton1"); this.tableToolStripButton1.Name = "tableToolStripButton1"; this.tableToolStripButton1.Tag = "Table"; this.tableToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // listToolStripButton1 // this.listToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.listToolStripButton1, "listToolStripButton1"); this.listToolStripButton1.Name = "listToolStripButton1"; this.listToolStripButton1.Tag = "List"; this.listToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // imageToolStripButton1 // this.imageToolStripButton1.CheckOnClick = true; this.imageToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.Image; resources.ApplyResources(this.imageToolStripButton1, "imageToolStripButton1"); this.imageToolStripButton1.Name = "imageToolStripButton1"; this.imageToolStripButton1.Tag = "Image"; this.imageToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // matrixToolStripButton1 // this.matrixToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.matrixToolStripButton1, "matrixToolStripButton1"); this.matrixToolStripButton1.Name = "matrixToolStripButton1"; this.matrixToolStripButton1.Tag = "Matrix"; this.matrixToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // subreportToolStripButton1 // this.subreportToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.subreportToolStripButton1, "subreportToolStripButton1"); this.subreportToolStripButton1.Name = "subreportToolStripButton1"; this.subreportToolStripButton1.Tag = "Subreport"; this.subreportToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // rectangleToolStripButton1 // this.rectangleToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.rectangleToolStripButton1, "rectangleToolStripButton1"); this.rectangleToolStripButton1.Name = "rectangleToolStripButton1"; this.rectangleToolStripButton1.Tag = "Rectangle"; this.rectangleToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // lineToolStripButton1 // this.lineToolStripButton1.CheckOnClick = true; resources.ApplyResources(this.lineToolStripButton1, "lineToolStripButton1"); this.lineToolStripButton1.Name = "lineToolStripButton1"; this.lineToolStripButton1.Tag = "Line"; this.lineToolStripButton1.Click += new System.EventHandler(this.Insert_Click); // // fxToolStripLabel1 // resources.ApplyResources(this.fxToolStripLabel1, "fxToolStripLabel1"); this.fxToolStripLabel1.Name = "fxToolStripLabel1"; this.fxToolStripLabel1.Tag = "fx"; this.fxToolStripLabel1.Click += new System.EventHandler(this.fxExpr_Click); this.fxToolStripLabel1.MouseEnter += new System.EventHandler(this.fxExpr_MouseEnter); this.fxToolStripLabel1.MouseLeave += new System.EventHandler(this.fxExpr_MouseLeave); // // ctlEditTextbox // this.ctlEditTextbox.Name = "ctlEditTextbox"; resources.ApplyResources(this.ctlEditTextbox, "ctlEditTextbox"); this.ctlEditTextbox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.EditTextBox_KeyDown); this.ctlEditTextbox.Validated += new System.EventHandler(this.EditTextbox_Validated); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.boldToolStripButton1, this.italiacToolStripButton1, this.underlineToolStripButton2, this.leftAlignToolStripButton2, this.centerAlignToolStripButton2, this.rightAlignToolStripButton3, this.fontToolStripComboBox1, this.fontSizeToolStripComboBox1, this.printToolStripButton2, this.zoomToolStripComboBox1, this.selectToolStripButton2, this.pdfToolStripButton2, this.htmlToolStripButton2, this.excelToolStripButton2, this.XmlToolStripButton2, this.MhtToolStripButton2, this.CsvToolStripButton2, this.RtfToolStripButton2, this.TifToolStripButton2}); resources.ApplyResources(this.toolStrip1, "toolStrip1"); this.toolStrip1.Name = "toolStrip1"; // // boldToolStripButton1 // this.boldToolStripButton1.CheckOnClick = true; this.boldToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.boldToolStripButton1, "boldToolStripButton1"); this.boldToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.format_text_bold; this.boldToolStripButton1.Name = "boldToolStripButton1"; this.boldToolStripButton1.Tag = "bold"; // // italiacToolStripButton1 // this.italiacToolStripButton1.CheckOnClick = true; this.italiacToolStripButton1.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.italiacToolStripButton1, "italiacToolStripButton1"); this.italiacToolStripButton1.Image = global::fyiReporting.RdlDesign.Properties.Resources.format_text_italic; this.italiacToolStripButton1.Name = "italiacToolStripButton1"; this.italiacToolStripButton1.Tag = "italic"; this.italiacToolStripButton1.Click += new System.EventHandler(this.ctlItalic_Click); // // underlineToolStripButton2 // this.underlineToolStripButton2.CheckOnClick = true; this.underlineToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.underlineToolStripButton2, "underlineToolStripButton2"); this.underlineToolStripButton2.Image = global::fyiReporting.RdlDesign.Properties.Resources.format_text_underline; this.underlineToolStripButton2.Name = "underlineToolStripButton2"; this.underlineToolStripButton2.Tag = "underline"; this.underlineToolStripButton2.Click += new System.EventHandler(this.ctlUnderline_Click); // // leftAlignToolStripButton2 // this.leftAlignToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.leftAlignToolStripButton2.Image = global::fyiReporting.RdlDesign.Properties.Resources.format_justify_left; resources.ApplyResources(this.leftAlignToolStripButton2, "leftAlignToolStripButton2"); this.leftAlignToolStripButton2.Name = "leftAlignToolStripButton2"; this.leftAlignToolStripButton2.Tag = "Left Align"; this.leftAlignToolStripButton2.Click += new System.EventHandler(this.bottomsToolStripMenuItemutton_Click); // // centerAlignToolStripButton2 // this.centerAlignToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.centerAlignToolStripButton2.Image = global::fyiReporting.RdlDesign.Properties.Resources.format_justify_center; resources.ApplyResources(this.centerAlignToolStripButton2, "centerAlignToolStripButton2"); this.centerAlignToolStripButton2.Name = "centerAlignToolStripButton2"; this.centerAlignToolStripButton2.Tag = "Center Align"; this.centerAlignToolStripButton2.Click += new System.EventHandler(this.bottomsToolStripMenuItemutton_Click); // // rightAlignToolStripButton3 // this.rightAlignToolStripButton3.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.rightAlignToolStripButton3.Image = global::fyiReporting.RdlDesign.Properties.Resources.format_justify_right; resources.ApplyResources(this.rightAlignToolStripButton3, "rightAlignToolStripButton3"); this.rightAlignToolStripButton3.Name = "rightAlignToolStripButton3"; this.rightAlignToolStripButton3.Tag = "Right Align"; this.rightAlignToolStripButton3.Click += new System.EventHandler(this.bottomsToolStripMenuItemutton_Click); // // fontToolStripComboBox1 // this.fontToolStripComboBox1.Name = "fontToolStripComboBox1"; resources.ApplyResources(this.fontToolStripComboBox1, "fontToolStripComboBox1"); this.fontToolStripComboBox1.Tag = "Font"; this.fontToolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.ctlFont_Change); this.fontToolStripComboBox1.Validated += new System.EventHandler(this.ctlFont_Change); // // fontSizeToolStripComboBox1 // this.fontSizeToolStripComboBox1.Name = "fontSizeToolStripComboBox1"; resources.ApplyResources(this.fontSizeToolStripComboBox1, "fontSizeToolStripComboBox1"); this.fontSizeToolStripComboBox1.Tag = "Font Size"; this.fontSizeToolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.ctlFontSize_Change); this.fontSizeToolStripComboBox1.Validated += new System.EventHandler(this.ctlFontSize_Change); // // printToolStripButton2 // this.printToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.printToolStripButton2.Image = global::fyiReporting.RdlDesign.Properties.Resources.document_print; resources.ApplyResources(this.printToolStripButton2, "printToolStripButton2"); this.printToolStripButton2.Name = "printToolStripButton2"; this.printToolStripButton2.Tag = "Print"; this.printToolStripButton2.Click += new System.EventHandler(this.menuFilePrint_Click); // // zoomToolStripComboBox1 // this.zoomToolStripComboBox1.Name = "zoomToolStripComboBox1"; resources.ApplyResources(this.zoomToolStripComboBox1, "zoomToolStripComboBox1"); this.zoomToolStripComboBox1.Tag = "Zoom"; this.zoomToolStripComboBox1.SelectedIndexChanged += new System.EventHandler(this.ctlZoom_Change); this.zoomToolStripComboBox1.Validated += new System.EventHandler(this.ctlZoom_Change); // // selectToolStripButton2 // this.selectToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.selectToolStripButton2, "selectToolStripButton2"); this.selectToolStripButton2.Name = "selectToolStripButton2"; this.selectToolStripButton2.Tag = "Select Tool"; this.selectToolStripButton2.Click += new System.EventHandler(this.ctlSelectTool_Click); // // pdfToolStripButton2 // this.pdfToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.pdfToolStripButton2, "pdfToolStripButton2"); this.pdfToolStripButton2.Name = "pdfToolStripButton2"; this.pdfToolStripButton2.Tag = "PDF"; this.pdfToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemPdf_Click); // // htmlToolStripButton2 // this.htmlToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.htmlToolStripButton2, "htmlToolStripButton2"); this.htmlToolStripButton2.Name = "htmlToolStripButton2"; this.htmlToolStripButton2.Tag = "HTML"; this.htmlToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemHtml_Click); // // excelToolStripButton2 // this.excelToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.excelToolStripButton2, "excelToolStripButton2"); this.excelToolStripButton2.Name = "excelToolStripButton2"; this.excelToolStripButton2.Tag = "Excel"; this.excelToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemExcel_Click); // // XmlToolStripButton2 // this.XmlToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.XmlToolStripButton2, "XmlToolStripButton2"); this.XmlToolStripButton2.Name = "XmlToolStripButton2"; this.XmlToolStripButton2.Tag = "XML"; this.XmlToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemXml_Click); // // MhtToolStripButton2 // this.MhtToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.MhtToolStripButton2, "MhtToolStripButton2"); this.MhtToolStripButton2.Name = "MhtToolStripButton2"; this.MhtToolStripButton2.Tag = "MHT"; this.MhtToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemMHtml_Click); // // CsvToolStripButton2 // this.CsvToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.CsvToolStripButton2, "CsvToolStripButton2"); this.CsvToolStripButton2.Name = "CsvToolStripButton2"; this.CsvToolStripButton2.Tag = "CSV"; this.CsvToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemCsv_Click); // // RtfToolStripButton2 // this.RtfToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.RtfToolStripButton2, "RtfToolStripButton2"); this.RtfToolStripButton2.Name = "RtfToolStripButton2"; this.RtfToolStripButton2.Tag = "RTF"; this.RtfToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemRtf_Click); // // TifToolStripButton2 // this.TifToolStripButton2.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; resources.ApplyResources(this.TifToolStripButton2, "TifToolStripButton2"); this.TifToolStripButton2.Name = "TifToolStripButton2"; this.TifToolStripButton2.Tag = "TIF"; this.TifToolStripButton2.Click += new System.EventHandler(this.exportToolStripMenuItemTif_Click); // // mainTC // resources.ApplyResources(this.mainTC, "mainTC"); this.mainTC.Name = "mainTC"; this.mainTC.SelectedIndex = 0; this.mainTC.SelectedIndexChanged += new System.EventHandler(this.mainTC_SelectedIndexChanged); this.mainTC.MouseClick += new System.Windows.Forms.MouseEventHandler(this.mainTC_MouseClick); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.Name = "label1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // panel1 // this.panel1.Controls.Add(this.label1); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.foreColorPicker1); this.panel1.Controls.Add(this.backColorPicker1); this.panel1.Controls.Add(this.mainTC); resources.ApplyResources(this.panel1, "panel1"); this.panel1.Name = "panel1"; // // foreColorPicker1 // this.foreColorPicker1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.foreColorPicker1.DropDownHeight = 1; this.foreColorPicker1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.foreColorPicker1, "foreColorPicker1"); this.foreColorPicker1.FormattingEnabled = true; this.foreColorPicker1.Name = "foreColorPicker1"; this.foreColorPicker1.Tag = "Fore Color"; this.foreColorPicker1.SelectedValueChanged += new System.EventHandler(this.ctlForeColor_Change); this.foreColorPicker1.Validated += new System.EventHandler(this.ctlForeColor_Change); // // backColorPicker1 // this.backColorPicker1.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.backColorPicker1.DropDownHeight = 1; this.backColorPicker1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; resources.ApplyResources(this.backColorPicker1, "backColorPicker1"); this.backColorPicker1.FormattingEnabled = true; this.backColorPicker1.Name = "backColorPicker1"; this.backColorPicker1.Tag = "Back Color"; this.backColorPicker1.SelectedValueChanged += new System.EventHandler(this.ctlBackColor_Change); this.backColorPicker1.Validated += new System.EventHandler(this.ctlBackColor_Change); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.statusSelected, this.toolStripStatusLabel2, this.statusPosition}); resources.ApplyResources(this.statusStrip1, "statusStrip1"); this.statusStrip1.Name = "statusStrip1"; // // statusSelected // this.statusSelected.Name = "statusSelected"; resources.ApplyResources(this.statusSelected, "statusSelected"); // // toolStripStatusLabel2 // this.toolStripStatusLabel2.ForeColor = System.Drawing.Color.Gray; this.toolStripStatusLabel2.Name = "toolStripStatusLabel2"; resources.ApplyResources(this.toolStripStatusLabel2, "toolStripStatusLabel2"); // // statusPosition // this.statusPosition.Name = "statusPosition"; resources.ApplyResources(this.statusPosition, "statusPosition"); // // mainSP // resources.ApplyResources(this.mainSP, "mainSP"); this.mainSP.Name = "mainSP"; this.mainSP.TabStop = false; // // mainProperties // resources.ApplyResources(this.mainProperties, "mainProperties"); this.mainProperties.Name = "mainProperties"; // // ContextMenuTB // this.ContextMenuTB.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.MenuTBClose, this.MenuTBSave, this.MenuTBCloseAllButThis}); this.ContextMenuTB.Name = "ContextMenuTB"; resources.ApplyResources(this.ContextMenuTB, "ContextMenuTB"); // // MenuTBClose // this.MenuTBClose.Name = "MenuTBClose"; resources.ApplyResources(this.MenuTBClose, "MenuTBClose"); this.MenuTBClose.Click += new System.EventHandler(this.menuFileClose_Click); // // MenuTBSave // this.MenuTBSave.Name = "MenuTBSave"; resources.ApplyResources(this.MenuTBSave, "MenuTBSave"); this.MenuTBSave.Click += new System.EventHandler(this.menuFileSave_Click); // // MenuTBCloseAllButThis // this.MenuTBCloseAllButThis.Name = "MenuTBCloseAllButThis"; resources.ApplyResources(this.MenuTBCloseAllButThis, "MenuTBCloseAllButThis"); this.MenuTBCloseAllButThis.Click += new System.EventHandler(this.menuWndCloseAllButCurrent_Click); // // RdlDesigner // this.AllowDrop = true; resources.ApplyResources(this, "$this"); this.Controls.Add(this.mainSP); this.Controls.Add(this.mainProperties); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.panel1); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.mainTB); this.Controls.Add(this.menuStrip1); this.MainMenuStrip = this.menuStrip1; this.Name = "RdlDesigner"; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide; this.WindowState = System.Windows.Forms.FormWindowState.Maximized; this.Load += new System.EventHandler(this.RdlDesigner_Load); this.DragDrop += new System.Windows.Forms.DragEventHandler(this.RdlDesigner_DragDrop); this.DragEnter += new System.Windows.Forms.DragEventHandler(this.RdlDesigner_DragEnter); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.mainTB.ResumeLayout(false); this.mainTB.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.ContextMenuTB.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion protected override void Dispose( bool disposing ) { if( disposing ) { if (components != null) { components.Dispose(); } } base.Dispose( disposing ); } private MenuStrip menuStrip1; private ToolStripMenuItem fileToolStripMenuItem; private ToolStripMenuItem editToolStripMenuItem; private ToolStripMenuItem viewToolStripMenuItem; private ToolStripMenuItem dataToolStripMenuItem; private ToolStripMenuItem formatToolStripMenuItem; private ToolStripMenuItem toolsToolStripMenuItem; private ToolStripMenuItem windowToolStripMenuItem; private ToolStripMenuItem helpToolStripMenuItem; private ToolStripMenuItem newReportToolStripMenuItem; private ToolStripMenuItem openToolStripMenuItem; private ToolStripMenuItem closeToolStripMenuItem; private ToolStripSeparator toolStripSeparator1; private ToolStripMenuItem saveToolStripMenuItem; private ToolStripMenuItem saveAsToolStripMenuItem; private ToolStripMenuItem printToolStripMenuItem; private ToolStripMenuItem exportToolStripMenuItem; private ToolStripMenuItem pDFToolStripMenuItem; private ToolStripMenuItem tIFFToolStripMenuItem; private ToolStripMenuItem cSVToolStripMenuItem; private ToolStripMenuItem excelToolStripMenuItem; private ToolStripMenuItem rTFDOCToolStripMenuItem; private ToolStripMenuItem xMLToolStripMenuItem; private ToolStripMenuItem webPageHTMLToolStripMenuItem; private ToolStripMenuItem webArchiveSingleFileMHTToolStripMenuItem; private ToolStripSeparator toolStripSeparator2; private ToolStripMenuItem recentFilesToolStripMenuItem; private ToolStripSeparator toolStripSeparator3; private ToolStripMenuItem exitToolStripMenuItem; private ToolStripMenuItem undoToolStripMenuItem; private ToolStripMenuItem redoToolStripMenuItem; private ToolStripSeparator toolStripSeparator4; private ToolStripMenuItem cutToolStripMenuItem; private ToolStripMenuItem copyToolStripMenuItem; private ToolStripMenuItem pasteToolStripMenuItem; private ToolStripMenuItem deleteToolStripMenuItem; private ToolStripSeparator toolStripSeparator5; private ToolStripMenuItem selectAllToolStripMenuItem; private ToolStripSeparator toolStripSeparator6; private ToolStripMenuItem findToolStripMenuItem; private ToolStripMenuItem findNextToolStripMenuItem; private ToolStripMenuItem replaceToolStripMenuItem; private ToolStripMenuItem goToToolStripMenuItem; private ToolStripSeparator toolStripSeparator7; private ToolStripMenuItem formatXMLToolStripMenuItem; private ToolStripMenuItem designerToolStripMenuItem; private ToolStripMenuItem rDLTextToolStripMenuItem; private ToolStripMenuItem previewToolStripMenuItem; private ToolStripMenuItem showReportInBrowserToolStripMenuItem; private ToolStripMenuItem propertiesWindowsToolStripMenuItem; private ToolStripMenuItem dataSetsToolStripMenuItem; private ToolStripMenuItem embeddedImagesToolStripMenuItem; private ToolStripMenuItem createSharedDataSourceToolStripMenuItem; private ToolStripMenuItem dataSourcesToolStripMenuItem1; private ToolStripSeparator toolStripSeparator8; private ToolStripSeparator toolStripSeparator9; private ToolStripMenuItem alignToolStripMenuItem; private ToolStripMenuItem leftsToolStripMenuItem; private ToolStripMenuItem centersToolStripMenuItem; private ToolStripMenuItem rightsToolStripMenuItem; private ToolStripMenuItem topsToolStripMenuItem; private ToolStripMenuItem middlesToolStripMenuItem; private ToolStripMenuItem bottomsToolStripMenuItem; private ToolStripSeparator toolStripSeparator10; private ToolStripMenuItem sizeToolStripMenuItem; private ToolStripMenuItem widthToolStripMenuItem; private ToolStripMenuItem heightToolStripMenuItem; private ToolStripMenuItem bothToolStripMenuItem; private ToolStripMenuItem horizontalSpacingToolStripMenuItem; private ToolStripMenuItem makeEqualToolStripMenuItem; private ToolStripMenuItem increaseToolStripMenuItem; private ToolStripMenuItem decreaseToolStripMenuItem; private ToolStripMenuItem zeroToolStripMenuItem; private ToolStripMenuItem verticalSpacingToolStripMenuItem; private ToolStripMenuItem makeEqualToolStripMenuItem1; private ToolStripMenuItem increaseToolStripMenuItem1; private ToolStripMenuItem decreaseToolStripMenuItem1; private ToolStripMenuItem zeroToolStripMenuItem1; private ToolStripSeparator toolStripSeparator11; private ToolStripMenuItem paddingLeftToolStripMenuItem; private ToolStripMenuItem increaseToolStripMenuItem2; private ToolStripMenuItem decreaseToolStripMenuItem2; private ToolStripMenuItem zeroToolStripMenuItem2; private ToolStripMenuItem paddingRightToolStripMenuItem; private ToolStripMenuItem increaseToolStripMenuItem3; private ToolStripMenuItem decreaseToolStripMenuItem3; private ToolStripMenuItem zeroToolStripMenuItem3; private ToolStripMenuItem paddintTopToolStripMenuItem; private ToolStripMenuItem increaseToolStripMenuItem4; private ToolStripMenuItem decreaseToolStripMenuItem4; private ToolStripMenuItem zeroToolStripMenuItem4; private ToolStripMenuItem paddingBottomToolStripMenuItem; private ToolStripMenuItem increaseToolStripMenuItem5; private ToolStripMenuItem decreaseToolStripMenuItem5; private ToolStripMenuItem zeroToolStripMenuItem5; private ToolStripMenuItem validateRDLToolStripMenuItem; private ToolStripMenuItem startDesktopServerToolStripMenuItem; private ToolStripMenuItem optionsToolStripMenuItem; private ToolStripSeparator toolStripSeparator12; private ToolStripSeparator toolStripSeparator13; private ToolStripMenuItem cascadeToolStripMenuItem; private ToolStripMenuItem tileToolStripMenuItem; private ToolStripMenuItem horizontalToolStripMenuItem; private ToolStripMenuItem verticallyToolStripMenuItem; private ToolStripMenuItem closeAllToolStripMenuItem; private ToolStripMenuItem helpToolStripMenuItem1; private ToolStripMenuItem supportToolStripMenuItem; private ToolStripMenuItem aboutToolStripMenuItem; private ToolStrip mainTB; private ToolStripButton newToolStripButton1; private ToolStrip toolStrip1; private ToolStripButton openToolStripButton1; private ToolStripButton saveToolStripButton1; private ToolStripButton cutToolStripButton1; private ToolStripButton copyToolStripButton1; private ToolStripButton pasteToolStripButton1; private ToolStripButton undoToolStripButton1; private ToolStripButton textboxToolStripButton1; private ToolStripButton chartToolStripButton1; private ToolStripButton tableToolStripButton1; private ToolStripButton listToolStripButton1; private ToolStripButton imageToolStripButton1; private ToolStripButton matrixToolStripButton1; private ToolStripButton subreportToolStripButton1; private ToolStripButton rectangleToolStripButton1; private ToolStripButton lineToolStripButton1; private ToolStripLabel fxToolStripLabel1; private ToolStripTextBox ctlEditTextbox; private ToolStripButton boldToolStripButton1; private ToolStripButton italiacToolStripButton1; private ToolStripButton underlineToolStripButton2; private ToolStripButton leftAlignToolStripButton2; private ToolStripButton centerAlignToolStripButton2; private ToolStripButton rightAlignToolStripButton3; private ToolStripComboBox fontToolStripComboBox1; private ToolStripComboBox fontSizeToolStripComboBox1; private ColorPicker foreColorPicker1; private ColorPicker backColorPicker1; private ToolStripButton printToolStripButton2; private ToolStripComboBox zoomToolStripComboBox1; private ToolStripButton selectToolStripButton2; private TabControl mainTC; private ToolStripButton pdfToolStripButton2; private ToolStripButton htmlToolStripButton2; private ToolStripButton excelToolStripButton2; private ToolStripButton XmlToolStripButton2; private ToolStripButton MhtToolStripButton2; private ToolStripButton CsvToolStripButton2; private ToolStripButton RtfToolStripButton2; private ToolStripButton TifToolStripButton2; private Label label1; private Label label2; private Panel panel1; private StatusStrip statusStrip1; private Splitter mainSP; private PropertyCtl mainProperties; private ToolStripStatusLabel statusSelected; private ToolStripStatusLabel toolStripStatusLabel2; private ToolStripStatusLabel statusPosition; private ToolStripMenuItem insertToolStripMenuItem; private ToolStripMenuItem chartToolStripMenuItem; private ToolStripMenuItem gridToolStripMenuItem; private ToolStripMenuItem imageToolStripMenuItem; private ToolStripMenuItem lineToolStripMenuItem; private ToolStripMenuItem listToolStripMenuItem; private ToolStripMenuItem matrixToolStripMenuItem; private ToolStripMenuItem rectangleToolStripMenuItem; private ToolStripMenuItem subReportToolStripMenuItem; private ToolStripMenuItem tableToolStripMenuItem; private ToolStripMenuItem textboxToolStripMenuItem; private ToolStripMenuItem barCodeEAN13ToolStripMenuItem; private ToolStripMenuItem barCodeBooklandToolStripMenuItem; private ToolStripMenuItem pDFOldStyleToolStripMenuItem; private ToolStripMenuItem dOCToolStripMenuItem; private ContextMenuStrip ContextMenuTB; private IContainer components; private ToolStripMenuItem MenuTBClose; private ToolStripMenuItem MenuTBSave; private ToolStripMenuItem MenuTBCloseAllButThis; } }
// // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2015 Jb Evain // Copyright (c) 2008 - 2011 Novell, Inc. // // Licensed under the MIT/X11 license. // using System.Text; using SquabPie.Mono.Collections.Generic; namespace SquabPie.Mono.Cecil { public sealed class PropertyDefinition : PropertyReference, IMemberDefinition, IConstantProvider { bool? has_this; ushort attributes; Collection<CustomAttribute> custom_attributes; internal MethodDefinition get_method; internal MethodDefinition set_method; internal Collection<MethodDefinition> other_methods; object constant = Mixin.NotResolved; public PropertyAttributes Attributes { get { return (PropertyAttributes) attributes; } set { attributes = (ushort) value; } } public bool HasThis { get { if (has_this.HasValue) return has_this.Value; if (GetMethod != null) return get_method.HasThis; if (SetMethod != null) return set_method.HasThis; return false; } set { has_this = value; } } public bool HasCustomAttributes { get { if (custom_attributes != null) return custom_attributes.Count > 0; return this.GetHasCustomAttributes (Module); } } public Collection<CustomAttribute> CustomAttributes { get { return custom_attributes ?? (this.GetCustomAttributes (ref custom_attributes, Module)); } } public MethodDefinition GetMethod { get { if (get_method != null) return get_method; InitializeMethods (); return get_method; } set { get_method = value; } } public MethodDefinition SetMethod { get { if (set_method != null) return set_method; InitializeMethods (); return set_method; } set { set_method = value; } } public bool HasOtherMethods { get { if (other_methods != null) return other_methods.Count > 0; InitializeMethods (); return !other_methods.IsNullOrEmpty (); } } public Collection<MethodDefinition> OtherMethods { get { if (other_methods != null) return other_methods; InitializeMethods (); if (other_methods != null) return other_methods; return other_methods = new Collection<MethodDefinition> (); } } public bool HasParameters { get { InitializeMethods (); if (get_method != null) return get_method.HasParameters; if (set_method != null) return set_method.HasParameters && set_method.Parameters.Count > 1; return false; } } public override Collection<ParameterDefinition> Parameters { get { InitializeMethods (); if (get_method != null) return MirrorParameters (get_method, 0); if (set_method != null) return MirrorParameters (set_method, 1); return new Collection<ParameterDefinition> (); } } static Collection<ParameterDefinition> MirrorParameters (MethodDefinition method, int bound) { var parameters = new Collection<ParameterDefinition> (); if (!method.HasParameters) return parameters; var original_parameters = method.Parameters; var end = original_parameters.Count - bound; for (int i = 0; i < end; i++) parameters.Add (original_parameters [i]); return parameters; } public bool HasConstant { get { this.ResolveConstant (ref constant, Module); return constant != Mixin.NoValue; } set { if (!value) constant = Mixin.NoValue; } } public object Constant { get { return HasConstant ? constant : null; } set { constant = value; } } #region PropertyAttributes public bool IsSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.SpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.SpecialName, value); } } public bool IsRuntimeSpecialName { get { return attributes.GetAttributes ((ushort) PropertyAttributes.RTSpecialName); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.RTSpecialName, value); } } public bool HasDefault { get { return attributes.GetAttributes ((ushort) PropertyAttributes.HasDefault); } set { attributes = attributes.SetAttributes ((ushort) PropertyAttributes.HasDefault, value); } } #endregion public new TypeDefinition DeclaringType { get { return (TypeDefinition) base.DeclaringType; } set { base.DeclaringType = value; } } public override bool IsDefinition { get { return true; } } public override string FullName { get { var builder = new StringBuilder (); builder.Append (PropertyType.ToString ()); builder.Append (' '); builder.Append (MemberFullName ()); builder.Append ('('); if (HasParameters) { var parameters = Parameters; for (int i = 0; i < parameters.Count; i++) { if (i > 0) builder.Append (','); builder.Append (parameters [i].ParameterType.FullName); } } builder.Append (')'); return builder.ToString (); } } public PropertyDefinition (string name, PropertyAttributes attributes, TypeReference propertyType) : base (name, propertyType) { this.attributes = (ushort) attributes; this.token = new MetadataToken (TokenType.Property); } void InitializeMethods () { var module = this.Module; if (module == null) return; lock (module.SyncRoot) { if (get_method != null || set_method != null) return; if (!module.HasImage ()) return; module.Read (this, (property, reader) => reader.ReadMethods (property)); } } public override PropertyDefinition Resolve () { return this; } } }
using NetMud.Communication.Lexical; using NetMud.Data.Linguistic; using NetMud.DataAccess.Cache; using NetMud.DataStructure.Architectural.ActorBase; using NetMud.DataStructure.Architectural.EntityBase; using NetMud.DataStructure.Inanimate; using NetMud.DataStructure.Linguistic; using NetMud.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace NetMud.Interp { /// <summary> /// Engine for interpreting and merging observances /// </summary> public class LexicalInterpretationEngine { private IEnumerable<ILexeme> _currentDictionary => ConfigDataCache.GetAll<ILexeme>(); private ILocation _currentPlace; private IEntity _actor; /// <summary> /// Initial experience, takes in an observance and emits the new contexts related to it. Merge and Convey will merge new contexts into existing ones /// </summary> /// <param name="actor">Who did the action</param> /// <param name="action">The raw input that was observed</param> /// <returns>A list of the new contexts generated</returns> public IEnumerable<IDictata> Parse(IEntity actor, string action, bool push = false) { List<IDictata> returnList = new List<IDictata>(); _currentPlace = actor.CurrentLocation.CurrentLocation(); _actor = actor; string[] spaceSplit = action.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, IDictata> brandedWords = BrandWords(spaceSplit); List<string> sentences = new List<string>(); if (brandedWords.Count(bWord => bWord.Value != null && bWord.Value.WordType == LexicalType.Verb) > 1) { //multiple verbs means multiple sentences IEnumerable<string> punctuationSentences = IsolateSentences(action); foreach (string sentence in punctuationSentences) { string[] innerSplit = sentence.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries); Dictionary<string, IDictata> innerBrands = BrandWords(innerSplit); if (!innerBrands.Any(inWord => inWord.Value != null && inWord.Value.WordType == LexicalType.Conjunction)) { sentences.Add(sentence); continue; } bool found = false; foreach ((KeyValuePair<string, IDictata> value, int i) innerVerb in innerBrands.Select((value, i) => (value, i))) { KeyValuePair<string, IDictata> value = innerVerb.value; int index = innerVerb.i; if(value.Value != null && value.Value.WordType != LexicalType.Verb) { continue; } found = true; if (index > 0 && index < innerBrands.Count() - 1) { IDictata wordBefore = innerBrands.ElementAt(index - 1).Value; if(wordBefore.WordType == LexicalType.Conjunction) { int splitIndex = innerBrands.Take(index - 1).Sum(brand => brand.Key.Length + 1); int bumpCount = sentence.Substring(0, splitIndex - 1).Count(ch => ch == ',' || ch == ':'); string sentenceOne = sentence.Substring(0, splitIndex - 1 + bumpCount); string sentenceTwo = sentence.Substring(splitIndex + wordBefore.Name.Length + bumpCount); sentences.Add(sentenceOne); sentences.Add(sentenceTwo); } } } if(!found) { sentences.Add(sentence); } } } else { sentences.Add(action); } IDictata currentSubject = null; foreach (string sentence in sentences) { IList<Tuple<string, bool>> words = IsolateIndividuals(sentence); //can't parse nothing if (words.Count == 0) { continue; } IEnumerable<IDictata> fullCommand = ParseAction(words, push, currentSubject); currentSubject = fullCommand.LastOrDefault(word => word.WordType == LexicalType.Noun || word.WordType == LexicalType.ProperNoun); returnList.AddRange(fullCommand); } return returnList; } /* * TODO: Wow this is inefficient, maybe clean up how many loops we do */ private IEnumerable<IDictata> ParseAction(IList<Tuple<string, bool>> words, bool push, IDictata lastSubject) { /* * I kick the can * kick the can * kicks the can * kick the red can * kick the large red can */ List<IDictata> returnList = new List<IDictata>(); Dictionary<string, IDictata> brandedWords = BrandWords(words); IDictata currentVerb = null; //Find unknown nouns potentially with conjunctions foreach ((KeyValuePair<string, IDictata> value, int i) item in brandedWords.Where(ctx => ctx.Value == null).Select((value, i) => (value, i)).OrderByDescending(keypair => keypair.i)) { KeyValuePair<string, IDictata> value = item.value; int index = item.i; if (index < brandedWords.Count() - 1 && index > 0) { IDictata wordAfter = brandedWords.ElementAt(index + 1).Value; IDictata wordBefore = brandedWords.ElementAt(index - 1).Value; if (wordBefore != null && wordBefore.WordType == LexicalType.Adverb && wordAfter != null && wordAfter.WordType == LexicalType.Verb) { brandedWords[value.Key] = new Dictata() { Name = value.Key, WordType = LexicalType.Adverb }; continue; } if ((wordBefore != null && (wordBefore.WordType == LexicalType.Adjective) || wordBefore.WordType == LexicalType.Article) && (wordAfter != null && (wordAfter.WordType == LexicalType.Noun) || wordAfter.WordType == LexicalType.ProperNoun)) { brandedWords[value.Key] = new Dictata() { Name = value.Key, WordType = LexicalType.Adjective }; continue; } continue; } if (index < brandedWords.Count() - 1) { IDictata wordAfter = brandedWords.ElementAt(index + 1).Value; if (wordAfter != null && wordAfter.WordType == LexicalType.Noun) { brandedWords[value.Key] = new Dictata() { Name = value.Key, WordType = LexicalType.Adjective }; continue; } if (wordAfter != null && wordAfter.WordType == LexicalType.Verb) { brandedWords[value.Key] = new Dictata() { Name = value.Key, WordType = LexicalType.Adverb }; continue; } } if (index > 0) { IDictata wordBefore = brandedWords.ElementAt(index - 1).Value; if (wordBefore != null && (wordBefore.WordType == LexicalType.Article || wordBefore.WordType == LexicalType.Adjective)) { brandedWords[value.Key] = new Dictata() { Name = value.Key, WordType = LexicalType.Noun }; continue; } if (wordBefore != null && wordBefore.WordType == LexicalType.Adverb) { brandedWords[value.Key] = new Dictata() { Name = value.Key, WordType = LexicalType.Verb }; continue; } } } //No verb? if (!brandedWords.Any(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Verb)) { string verbWord = brandedWords.First(ctx => ctx.Value == null).Key; currentVerb = new Dictata() { Name = verbWord, WordType = LexicalType.Verb }; brandedWords[verbWord] = currentVerb; } else { currentVerb = brandedWords.FirstOrDefault(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Verb).Value; } //We might have nouns already if (!brandedWords.Any(ctx => ctx.Value == null || (ctx.Value != null && (ctx.Value.WordType == LexicalType.Noun || ctx.Value.WordType == LexicalType.ProperNoun)))) { bool lastSubjectReplaced = false; if (lastSubject != null) { List<string> keyList = new List<string>(); foreach(KeyValuePair<string, IDictata> word in brandedWords.Where(ctx => ctx.Value != null && ctx.Value.WordType == LexicalType.Pronoun)) { keyList.Add(word.Key); lastSubjectReplaced = true; } foreach(string key in keyList) { brandedWords[key] = (IDictata)lastSubject.Clone(); } } if (!lastSubjectReplaced) { string targetWord = string.Empty; //No valid nouns to make the target? Pick the last one if (!brandedWords.Any(ctx => ctx.Value == null)) { targetWord = brandedWords.LastOrDefault().Key; } else { targetWord = brandedWords.LastOrDefault(ctx => ctx.Value == null).Key; } brandedWords[targetWord] = new Dictata() { Name = targetWord, WordType = LexicalType.Noun }; } } List<IDictata> descriptors = new List<IDictata>(); foreach ((KeyValuePair<string, IDictata> value, int i) item in brandedWords.Where(ctx => ctx.Value == null).Select((value, i) => (value, i))) { KeyValuePair<string, IDictata> value = item.value; int index = item.i; LexicalType wordType = LexicalType.Adjective; if (index == brandedWords.Count() - 1) { IDictata wordAfter = brandedWords.ElementAt(index + 1).Value; if (wordAfter != null) { if (wordAfter.WordType == LexicalType.Verb) { wordType = LexicalType.Adverb; } if (wordAfter.WordType == LexicalType.Pronoun) { wordType = LexicalType.Article; } } } descriptors.Add(new Dictata() { Name = value.Key, WordType = wordType }); } //Add the nonadjectives and the adjectives returnList.AddRange(brandedWords.Where(bws => bws.Value != null).Select(bws => bws.Value)); returnList.AddRange(descriptors.Select(desc => desc)); if (push) { foreach (IDictata item in returnList) { LexicalProcessor.VerifyLexeme(item.GetLexeme()); } } return returnList; } /* * TODO: First pass: parse out existing things, the place we're in and decorators * Second pass: search for places in the world to make links * Third pass: More robust logic to avoid extra merging later */ private IEnumerable<IDictata> ParseSpeech(IList<Tuple<string, bool>> words) { /* * hello * hi there * did you go to the store * what are you doing there * I saw a red ball in the living room */ List<IDictata> returnList = new List<IDictata>(); ILocation currentPlace = _actor.CurrentLocation.CurrentLocation(); Dictionary<string, IDictata> brandedWords = BrandWords(words); string targetWord = string.Empty; //No valid nouns to make the target? Pick the last one if (!brandedWords.Any(ctx => ctx.Value == null)) { targetWord = brandedWords.LastOrDefault().Key; } else { targetWord = brandedWords.LastOrDefault(ctx => ctx.Value == null).Key; } brandedWords.Remove(targetWord); List<IDictata> descriptors = new List<IDictata>(); foreach (KeyValuePair<string, IDictata> adjective in brandedWords.Where(ctx => ctx.Value == null || (ctx.Value != null && (ctx.Value.WordType == LexicalType.Adjective || ctx.Value.WordType == LexicalType.Adverb)))) { if (adjective.Value != null) { descriptors.Add(adjective.Value); } else { descriptors.Add(new Dictata() { Name = adjective.Key, WordType = LexicalType.Adjective }); } } returnList.AddRange(descriptors); return returnList; } private Dictionary<string, IDictata> BrandWords(string [] words) { List<Tuple<string, bool>> blankSlate = new List<Tuple<string, bool>>(); blankSlate.AddRange(words.Select(word => new Tuple<string, bool>(word, false))); return BrandWords(blankSlate); } private Dictionary<string, IDictata> BrandWords(IList<Tuple<string, bool>> words) { Dictionary<string, IDictata> brandedWords = new Dictionary<string, IDictata>(); //Brand all the words with their current meaning. Continues are in there because the listword inflation might cause collision foreach (Tuple<string, bool> word in words.Distinct()) { if (brandedWords.ContainsKey(word.Item1)) { continue; } //We have a comma/and list if (word.Item2) { string[] listWords = word.Item1.Split(new string[] { "and", ",", " " }, StringSplitOptions.RemoveEmptyEntries); IDictata listMeaning = null; foreach (string listWord in listWords) { if (listMeaning != null) { break; } if (brandedWords.ContainsKey(listWord)) { listMeaning = brandedWords[listWord]; } if (listMeaning == null) { listMeaning = GetExistingMeaning(listWord); } } foreach (string listWord in listWords) { if (brandedWords.ContainsKey(listWord)) { continue; } Dictata meaning = new Dictata() { Name = listWord, WordType = listMeaning.WordType }; brandedWords.Add(listWord, meaning); } continue; } brandedWords.Add(word.Item1, GetExistingMeaning(word.Item1)); } return brandedWords; } private IDictata GetExistingMeaning(string word, LexicalType wordType = LexicalType.Noun) { List<string> allContext = new List<string>(); //Get all local nouns allContext.AddRange(_currentPlace.GetContents<IInanimate>().SelectMany(thing => thing.Keywords)); allContext.AddRange(_currentPlace.GetContents<IMobile>().SelectMany(thing => thing.Keywords)); allContext.AddRange(_currentPlace.Keywords); allContext.AddRange(_actor.Keywords); IDictata existingMeaning = null; //It's a thing we can see if (allContext.Contains(word)) { existingMeaning = new Dictata() { Name = word, WordType = LexicalType.ProperNoun }; } else { //TODO: We need to discriminate based on lexical type as well, we could have multiple of the same word with different types if (_currentDictionary.Any(dict => dict.Name.Equals(word, StringComparison.InvariantCultureIgnoreCase))) { existingMeaning = _currentDictionary.FirstOrDefault(dict => dict.Name.Equals(word, StringComparison.InvariantCultureIgnoreCase))?.GetForm(wordType); } } return existingMeaning; } private IList<Tuple<string, bool>> IsolateIndividuals(string baseString) { int iterator = 0; baseString = baseString.ToLower(); List<Tuple<string, bool>> foundStrings = ParseQuotesOut(ref baseString, ref iterator); foundStrings.AddRange(ParseEntitiesOut(ref iterator, ref baseString)); foundStrings.AddRange(ParseCommaListsOut(ref iterator, ref baseString)); List<string> originalStrings = new List<string>(); originalStrings.AddRange(baseString.Split(new char[] { ' ', ',', ':' }, StringSplitOptions.RemoveEmptyEntries)); //So thanks to the commalist puller potentially adding replacement strings to the found collection we have to do a pass there first List<Tuple<int, string>> cleanerList = new List<Tuple<int, string>>(); foreach (Tuple<string, bool> dirtyString in foundStrings.Where(str => str.Item1.Contains("%%"))) { int dirtyIndex = foundStrings.IndexOf(dirtyString); string cleanString = dirtyString.Item1; while (cleanString.Contains("%%")) { int i = DataUtility.TryConvert<int>(cleanString.Substring(cleanString.IndexOf("%%") + 2, 1)); cleanString = cleanString.Replace(string.Format("%%{0}%%", i), foundStrings[i].Item1); } cleanerList.Add(new Tuple<int, string>(dirtyIndex, cleanString)); } foreach (Tuple<int, string> cleaner in cleanerList) { int dirtyIndex = cleaner.Item1; string cleanString = cleaner.Item2; foundStrings[dirtyIndex] = new Tuple<string, bool>(cleanString, foundStrings[dirtyIndex].Item2); } //Either add the modified one or add the normal one List<Tuple<string, bool>> returnStrings = new List<Tuple<string, bool>>(); foreach (string returnString in originalStrings) { if (returnString.StartsWith("%%") && returnString.EndsWith("%%")) { int i = DataUtility.TryConvert<int>(returnString.Substring(2, returnString.Length - 4)); returnStrings.Add(foundStrings[i]); } else { returnStrings.Add(new Tuple<string, bool>(returnString, false)); } } return returnStrings; } /* * word, word, word, word- ([a-zA-Z0-9_.-|(%%\d%%)]+)((,|,\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+ * word, word, word and word- ([a-zA-Z0-9_.-|(%%\d%%)]+)((,|,\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+(\sand\s)([a-zA-Z0-9_.-|(%%\d%%)]+) * word, word, word, and word ([a-zA-Z0-9_.-|(%%\d%%)]+)((,|,\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+(,\sand\s)([a-zA-Z0-9_.-|(%%\d%%)]+) * word and word and word and word- ([a-zA-Z0-9_.-|(%%\d%%)]+)((\sand\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+ */ private IList<Tuple<string, bool>> ParseCommaListsOut(ref int iterator, ref string baseString) { List<Tuple<string, bool>> foundStrings = new List<Tuple<string, bool>>(); Regex cccPattern = new Regex(@"([a-zA-Z0-9_.-|(%%\d%%)]+)((,|,\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+", RegexOptions.IgnorePatternWhitespace); Regex ccaPattern = new Regex(@"([a-zA-Z0-9_.-|(%%\d%%)]+)((,|,\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+(\sand\s)([a-zA-Z0-9_.-|(%%\d%%)]+)", RegexOptions.IgnorePatternWhitespace); Regex ccacPattern = new Regex(@"([a-zA-Z0-9_.-|(%%\d%%)]+)((,|,\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+(,\sand\s)([a-zA-Z0-9_.-|(%%\d%%)]+)", RegexOptions.IgnorePatternWhitespace); Regex aaaPattern = new Regex(@"([a-zA-Z0-9_.-|(%%\d%%)]+)((\sand\s)[a-zA-Z0-9_.-|(%%\d%%)]+)+", RegexOptions.IgnorePatternWhitespace); foundStrings.AddRange(RunListPattern(ccacPattern, ref iterator, ref baseString)); foundStrings.AddRange(RunListPattern(ccaPattern, ref iterator, ref baseString)); foundStrings.AddRange(RunListPattern(aaaPattern, ref iterator, ref baseString)); foundStrings.AddRange(RunListPattern(cccPattern, ref iterator, ref baseString)); return foundStrings; } private IList<Tuple<string, bool>> RunListPattern(Regex capturePattern, ref int iterator, ref string baseString) { List<Tuple<string, bool>> foundStrings = new List<Tuple<string, bool>>(); MatchCollection cccMatches = capturePattern.Matches(baseString); for (int i = 0; i < cccMatches.Count; i++) { Match currentMatch = cccMatches[i]; if (currentMatch == null || !currentMatch.Success) { continue; } CaptureCollection cccCaptures = currentMatch.Captures; for (int iC = 0; iC < cccCaptures.Count; iC++) { Capture currentCapture = cccCaptures[iC]; if (currentCapture == null || currentCapture.Length == 0) { continue; } string commaList = currentCapture.Value; foundStrings.Add(new Tuple<string, bool>(commaList, true)); baseString = baseString.Replace(commaList, "%%" + iterator.ToString() + "%%"); iterator++; } } return foundStrings; } private IList<Tuple<string, bool>> ParseEntitiesOut(ref int iterator, ref string baseString) { List<Tuple<string, bool>> foundStrings = new List<Tuple<string, bool>>(); List<string> allContext = new List<string>(); //Get all local nouns allContext.AddRange(_actor.CurrentLocation.CurrentLocation().GetContents<IInanimate>().SelectMany(thing => thing.Keywords)); allContext.AddRange(_actor.CurrentLocation.CurrentLocation().GetContents<IMobile>().SelectMany(thing => thing.Keywords)); allContext.AddRange(_actor.CurrentLocation.CurrentLocation().Keywords); allContext.AddRange(_actor.Keywords); //Brand all the words with their current meaning foreach (string word in allContext.Distinct()) { if (baseString.Contains(word)) { foundStrings.Add(new Tuple<string, bool>(word, false)); baseString = baseString.Replace(word, "%%" + iterator.ToString() + "%%"); iterator++; } } return foundStrings; } /// <summary> /// Scrubs "s and 's out and figures out what the parameters really are /// </summary> /// <returns>the right parameters</returns> private List<Tuple<string, bool>> ParseQuotesOut(ref string baseString, ref int iterator) { List<Tuple<string, bool>> foundStrings = new List<Tuple<string, bool>>(); baseString = IsolateStrings(baseString, "\"", foundStrings, ref iterator); baseString = IsolateStrings(baseString, "'", foundStrings, ref iterator); return foundStrings; } //Do we have magic string collectors? quotation marks demarcate a single parameter being passed in private string IsolateStrings(string baseString, string closure, List<Tuple<string, bool>> foundStrings, ref int foundStringIterator) { while (baseString.Contains("\"")) { int firstQuoteIndex = baseString.IndexOf('"'); int secondQuoteIndex = baseString.IndexOf('"', firstQuoteIndex + 1); //What? Why would this even happen if (firstQuoteIndex < 0) { break; } //Only one means let's just kill the stupid quotemark and move on if (secondQuoteIndex < 0) { baseString = baseString.Replace("\"", string.Empty); break; } string foundString = baseString.Substring(firstQuoteIndex + 1, secondQuoteIndex - firstQuoteIndex - 1); foundStrings.Add(new Tuple<string, bool>(foundString, false)); baseString = baseString.Replace(string.Format("\"{0}\"", foundString), "%%" + foundStringIterator.ToString() + "%%"); foundStringIterator++; } return baseString; } IEnumerable<string> IsolateSentences(string input) { List<string> sentences = new List<string>(); //TODO: recognize "and <verb>" string[] initialSplit = input.Split(new string[] { ";", "?", ". ", "!" }, StringSplitOptions.RemoveEmptyEntries); foreach (string phrase in initialSplit) { string[] potentialWords = phrase.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); if (potentialWords.Count() > 1) { sentences.Add(phrase); } } if (sentences.Count > 1) { return sentences; } //Fall back to just the initial sentence because we couldn't find multiple full sentences. return new List<string>() { input }; } /// <summary> /// Removes stuff we don't care about like to, into, the, etc /// </summary> /// <param name="currentParams">The current set of params</param> /// <returns>the scrubbed params</returns> private IList<string> RemoveGrammaticalNiceities(IList<string> currentParams) { List<string> parmList = currentParams.ToList(); parmList.RemoveAll(str => str.Equals("the", StringComparison.InvariantCulture) || str.Equals("of", StringComparison.InvariantCulture) || str.Equals("to", StringComparison.InvariantCulture) || str.Equals("into", StringComparison.InvariantCulture) || str.Equals("in", StringComparison.InvariantCulture) || str.Equals("from", StringComparison.InvariantCulture) || str.Equals("inside", StringComparison.InvariantCulture) || str.Equals("at", StringComparison.InvariantCulture) || str.Equals("a", StringComparison.InvariantCulture) || str.Equals("an", StringComparison.InvariantCulture) || str.Equals("that", StringComparison.InvariantCulture) || str.Equals("this", StringComparison.InvariantCulture) ); return parmList; } } }
// Generated by ProtoGen, Version=2.4.1.521, Culture=neutral, PublicKeyToken=55f7125234beb589. DO NOT EDIT! #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.ProtocolBuffers; using pbc = global::Google.ProtocolBuffers.Collections; using pbd = global::Google.ProtocolBuffers.Descriptors; using scg = global::System.Collections.Generic; [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public static partial class Containerformats { #region Extension registration public static void RegisterAllExtensions(pb::ExtensionRegistry registry) { } #endregion #region Static variables internal static pbd::MessageDescriptor internal__static_SelectionEnvelope__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::SelectionEnvelope, global::SelectionEnvelope.Builder> internal__static_SelectionEnvelope__FieldAccessorTable; internal static pbd::MessageDescriptor internal__static_Selection__Descriptor; internal static pb::FieldAccess.FieldAccessorTable<global::Selection, global::Selection.Builder> internal__static_Selection__FieldAccessorTable; #endregion #region Descriptor private static pbd::FileDescriptor descriptor; static Containerformats() { byte[] descriptorData = global::System.Convert.FromBase64String( "ChZjb250YWluZXJmb3JtYXRzLnByb3RvIngKEVNlbGVjdGlvbkVudmVsb3Bl" + "EhcKD2VuY2xvc2VkTWVzc2FnZRgBIAIoDBIUCgxzZXJpYWxpemVySWQYAiAC" + "KAUSGwoHcGF0dGVybhgDIAMoCzIKLlNlbGVjdGlvbhIXCg9tZXNzYWdlTWFu" + "aWZlc3QYBCABKAwiOAoJU2VsZWN0aW9uEhoKBHR5cGUYASACKA4yDC5QYXR0" + "ZXJuVHlwZRIPCgdtYXRjaGVyGAIgASgJKjwKC1BhdHRlcm5UeXBlEgoKBlBB" + "UkVOVBAAEg4KCkNISUxEX05BTUUQARIRCg1DSElMRF9QQVRURVJOEAJCAkgB"); pbd::FileDescriptor.InternalDescriptorAssigner assigner = delegate(pbd::FileDescriptor root) { descriptor = root; internal__static_SelectionEnvelope__Descriptor = Descriptor.MessageTypes[0]; internal__static_SelectionEnvelope__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::SelectionEnvelope, global::SelectionEnvelope.Builder>( internal__static_SelectionEnvelope__Descriptor, new string[] {"EnclosedMessage", "SerializerId", "Pattern", "MessageManifest",}); internal__static_Selection__Descriptor = Descriptor.MessageTypes[1]; internal__static_Selection__FieldAccessorTable = new pb::FieldAccess.FieldAccessorTable<global::Selection, global::Selection.Builder>( internal__static_Selection__Descriptor, new string[] {"Type", "Matcher",}); return null; }; pbd::FileDescriptor.InternalBuildGeneratedFileFrom(descriptorData, new pbd::FileDescriptor[] { }, assigner); } public static pbd::FileDescriptor Descriptor { get { return descriptor; } } #endregion } #region Enums public enum PatternType { PARENT = 0, CHILD_NAME = 1, CHILD_PATTERN = 2, } #endregion #region Messages [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class SelectionEnvelope : pb::GeneratedMessage<SelectionEnvelope, SelectionEnvelope.Builder> { public const int EnclosedMessageFieldNumber = 1; public const int SerializerIdFieldNumber = 2; public const int PatternFieldNumber = 3; public const int MessageManifestFieldNumber = 4; private static readonly SelectionEnvelope defaultInstance = new SelectionEnvelope().MakeReadOnly(); private static readonly string[] _selectionEnvelopeFieldNames = new string[] {"enclosedMessage", "messageManifest", "pattern", "serializerId"}; private static readonly uint[] _selectionEnvelopeFieldTags = new uint[] {10, 34, 26, 16}; private pb::ByteString enclosedMessage_ = pb::ByteString.Empty; private bool hasEnclosedMessage; private bool hasMessageManifest; private bool hasSerializerId; private int memoizedSerializedSize = -1; private pb::ByteString messageManifest_ = pb::ByteString.Empty; private pbc::PopsicleList<global::Selection> pattern_ = new pbc::PopsicleList<global::Selection>(); private int serializerId_; static SelectionEnvelope() { ReferenceEquals(global::Containerformats.Descriptor, null); } private SelectionEnvelope() { } public static SelectionEnvelope DefaultInstance { get { return defaultInstance; } } public override SelectionEnvelope DefaultInstanceForType { get { return DefaultInstance; } } protected override SelectionEnvelope ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Containerformats.internal__static_SelectionEnvelope__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<SelectionEnvelope, SelectionEnvelope.Builder> InternalFieldAccessors { get { return global::Containerformats.internal__static_SelectionEnvelope__FieldAccessorTable; } } public bool HasEnclosedMessage { get { return hasEnclosedMessage; } } public pb::ByteString EnclosedMessage { get { return enclosedMessage_; } } public bool HasSerializerId { get { return hasSerializerId; } } public int SerializerId { get { return serializerId_; } } public scg::IList<global::Selection> PatternList { get { return pattern_; } } public int PatternCount { get { return pattern_.Count; } } public bool HasMessageManifest { get { return hasMessageManifest; } } public pb::ByteString MessageManifest { get { return messageManifest_; } } public override bool IsInitialized { get { if (!hasEnclosedMessage) return false; if (!hasSerializerId) return false; foreach (global::Selection element in PatternList) { if (!element.IsInitialized) return false; } return true; } } public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasEnclosedMessage) { size += pb::CodedOutputStream.ComputeBytesSize(1, EnclosedMessage); } if (hasSerializerId) { size += pb::CodedOutputStream.ComputeInt32Size(2, SerializerId); } foreach (global::Selection element in PatternList) { size += pb::CodedOutputStream.ComputeMessageSize(3, element); } if (hasMessageManifest) { size += pb::CodedOutputStream.ComputeBytesSize(4, MessageManifest); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public global::Selection GetPattern(int index) { return pattern_[index]; } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _selectionEnvelopeFieldNames; if (hasEnclosedMessage) { output.WriteBytes(1, field_names[0], EnclosedMessage); } if (hasSerializerId) { output.WriteInt32(2, field_names[3], SerializerId); } if (pattern_.Count > 0) { output.WriteMessageArray(3, field_names[2], pattern_); } if (hasMessageManifest) { output.WriteBytes(4, field_names[1], MessageManifest); } UnknownFields.WriteTo(output); } public static SelectionEnvelope ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static SelectionEnvelope ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static SelectionEnvelope ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static SelectionEnvelope ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static SelectionEnvelope ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static SelectionEnvelope ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static SelectionEnvelope ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static SelectionEnvelope ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static SelectionEnvelope ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static SelectionEnvelope ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private SelectionEnvelope MakeReadOnly() { pattern_.MakeReadOnly(); return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(SelectionEnvelope prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<SelectionEnvelope, Builder> { private SelectionEnvelope result; private bool resultIsReadOnly; public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(SelectionEnvelope cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } protected override Builder ThisBuilder { get { return this; } } public override bool IsInitialized { get { return result.IsInitialized; } } protected override SelectionEnvelope MessageBeingBuilt { get { return PrepareBuilder(); } } public override pbd::MessageDescriptor DescriptorForType { get { return Descriptor; } } public override SelectionEnvelope DefaultInstanceForType { get { return DefaultInstance; } } public bool HasEnclosedMessage { get { return result.hasEnclosedMessage; } } public pb::ByteString EnclosedMessage { get { return result.EnclosedMessage; } set { SetEnclosedMessage(value); } } public bool HasSerializerId { get { return result.hasSerializerId; } } public int SerializerId { get { return result.SerializerId; } set { SetSerializerId(value); } } public pbc::IPopsicleList<global::Selection> PatternList { get { return PrepareBuilder().pattern_; } } public int PatternCount { get { return result.PatternCount; } } public bool HasMessageManifest { get { return result.hasMessageManifest; } } public pb::ByteString MessageManifest { get { return result.MessageManifest; } set { SetMessageManifest(value); } } private SelectionEnvelope PrepareBuilder() { if (resultIsReadOnly) { SelectionEnvelope original = result; result = new SelectionEnvelope(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override SelectionEnvelope BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is SelectionEnvelope) { return MergeFrom((SelectionEnvelope) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(SelectionEnvelope other) { if (other == DefaultInstance) return this; PrepareBuilder(); if (other.HasEnclosedMessage) { EnclosedMessage = other.EnclosedMessage; } if (other.HasSerializerId) { SerializerId = other.SerializerId; } if (other.pattern_.Count != 0) { result.pattern_.Add(other.pattern_); } if (other.HasMessageManifest) { MessageManifest = other.MessageManifest; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if (tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_selectionEnvelopeFieldNames, field_name, global::System.StringComparer.Ordinal); if (field_ordinal >= 0) tag = _selectionEnvelopeFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 10: { result.hasEnclosedMessage = input.ReadBytes(ref result.enclosedMessage_); break; } case 16: { result.hasSerializerId = input.ReadInt32(ref result.serializerId_); break; } case 26: { input.ReadMessageArray(tag, field_name, result.pattern_, global::Selection.DefaultInstance, extensionRegistry); break; } case 34: { result.hasMessageManifest = input.ReadBytes(ref result.messageManifest_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public Builder SetEnclosedMessage(pb::ByteString value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasEnclosedMessage = true; result.enclosedMessage_ = value; return this; } public Builder ClearEnclosedMessage() { PrepareBuilder(); result.hasEnclosedMessage = false; result.enclosedMessage_ = pb::ByteString.Empty; return this; } public Builder SetSerializerId(int value) { PrepareBuilder(); result.hasSerializerId = true; result.serializerId_ = value; return this; } public Builder ClearSerializerId() { PrepareBuilder(); result.hasSerializerId = false; result.serializerId_ = 0; return this; } public global::Selection GetPattern(int index) { return result.GetPattern(index); } public Builder SetPattern(int index, global::Selection value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.pattern_[index] = value; return this; } public Builder SetPattern(int index, global::Selection.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.pattern_[index] = builderForValue.Build(); return this; } public Builder AddPattern(global::Selection value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.pattern_.Add(value); return this; } public Builder AddPattern(global::Selection.Builder builderForValue) { pb::ThrowHelper.ThrowIfNull(builderForValue, "builderForValue"); PrepareBuilder(); result.pattern_.Add(builderForValue.Build()); return this; } public Builder AddRangePattern(scg::IEnumerable<global::Selection> values) { PrepareBuilder(); result.pattern_.Add(values); return this; } public Builder ClearPattern() { PrepareBuilder(); result.pattern_.Clear(); return this; } public Builder SetMessageManifest(pb::ByteString value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasMessageManifest = true; result.messageManifest_ = value; return this; } public Builder ClearMessageManifest() { PrepareBuilder(); result.hasMessageManifest = false; result.messageManifest_ = pb::ByteString.Empty; return this; } } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Selection : pb::GeneratedMessage<Selection, Selection.Builder> { public const int TypeFieldNumber = 1; public const int MatcherFieldNumber = 2; private static readonly Selection defaultInstance = new Selection().MakeReadOnly(); private static readonly string[] _selectionFieldNames = new string[] {"matcher", "type"}; private static readonly uint[] _selectionFieldTags = new uint[] {18, 8}; private bool hasMatcher; private bool hasType; private string matcher_ = ""; private int memoizedSerializedSize = -1; private global::PatternType type_ = global::PatternType.PARENT; static Selection() { ReferenceEquals(global::Containerformats.Descriptor, null); } private Selection() { } public static Selection DefaultInstance { get { return defaultInstance; } } public override Selection DefaultInstanceForType { get { return DefaultInstance; } } protected override Selection ThisMessage { get { return this; } } public static pbd::MessageDescriptor Descriptor { get { return global::Containerformats.internal__static_Selection__Descriptor; } } protected override pb::FieldAccess.FieldAccessorTable<Selection, Selection.Builder> InternalFieldAccessors { get { return global::Containerformats.internal__static_Selection__FieldAccessorTable; } } public bool HasType { get { return hasType; } } public global::PatternType Type { get { return type_; } } public bool HasMatcher { get { return hasMatcher; } } public string Matcher { get { return matcher_; } } public override bool IsInitialized { get { if (!hasType) return false; return true; } } public override int SerializedSize { get { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (hasType) { size += pb::CodedOutputStream.ComputeEnumSize(1, (int) Type); } if (hasMatcher) { size += pb::CodedOutputStream.ComputeStringSize(2, Matcher); } size += UnknownFields.SerializedSize; memoizedSerializedSize = size; return size; } } public override void WriteTo(pb::ICodedOutputStream output) { int size = SerializedSize; string[] field_names = _selectionFieldNames; if (hasType) { output.WriteEnum(1, field_names[1], (int) Type, Type); } if (hasMatcher) { output.WriteString(2, field_names[0], Matcher); } UnknownFields.WriteTo(output); } public static Selection ParseFrom(pb::ByteString data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Selection ParseFrom(pb::ByteString data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Selection ParseFrom(byte[] data) { return ((Builder) CreateBuilder().MergeFrom(data)).BuildParsed(); } public static Selection ParseFrom(byte[] data, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(data, extensionRegistry)).BuildParsed(); } public static Selection ParseFrom(global::System.IO.Stream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Selection ParseFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } public static Selection ParseDelimitedFrom(global::System.IO.Stream input) { return CreateBuilder().MergeDelimitedFrom(input).BuildParsed(); } public static Selection ParseDelimitedFrom(global::System.IO.Stream input, pb::ExtensionRegistry extensionRegistry) { return CreateBuilder().MergeDelimitedFrom(input, extensionRegistry).BuildParsed(); } public static Selection ParseFrom(pb::ICodedInputStream input) { return ((Builder) CreateBuilder().MergeFrom(input)).BuildParsed(); } public static Selection ParseFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { return ((Builder) CreateBuilder().MergeFrom(input, extensionRegistry)).BuildParsed(); } private Selection MakeReadOnly() { return this; } public static Builder CreateBuilder() { return new Builder(); } public override Builder ToBuilder() { return CreateBuilder(this); } public override Builder CreateBuilderForType() { return new Builder(); } public static Builder CreateBuilder(Selection prototype) { return new Builder(prototype); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public sealed partial class Builder : pb::GeneratedBuilder<Selection, Builder> { private Selection result; private bool resultIsReadOnly; public Builder() { result = DefaultInstance; resultIsReadOnly = true; } internal Builder(Selection cloneFrom) { result = cloneFrom; resultIsReadOnly = true; } protected override Builder ThisBuilder { get { return this; } } public override bool IsInitialized { get { return result.IsInitialized; } } protected override Selection MessageBeingBuilt { get { return PrepareBuilder(); } } public override pbd::MessageDescriptor DescriptorForType { get { return Descriptor; } } public override Selection DefaultInstanceForType { get { return DefaultInstance; } } public bool HasType { get { return result.hasType; } } public global::PatternType Type { get { return result.Type; } set { SetType(value); } } public bool HasMatcher { get { return result.hasMatcher; } } public string Matcher { get { return result.Matcher; } set { SetMatcher(value); } } private Selection PrepareBuilder() { if (resultIsReadOnly) { Selection original = result; result = new Selection(); resultIsReadOnly = false; MergeFrom(original); } return result; } public override Builder Clear() { result = DefaultInstance; resultIsReadOnly = true; return this; } public override Builder Clone() { if (resultIsReadOnly) { return new Builder(result); } else { return new Builder().MergeFrom(result); } } public override Selection BuildPartial() { if (resultIsReadOnly) { return result; } resultIsReadOnly = true; return result.MakeReadOnly(); } public override Builder MergeFrom(pb::IMessage other) { if (other is Selection) { return MergeFrom((Selection) other); } else { base.MergeFrom(other); return this; } } public override Builder MergeFrom(Selection other) { if (other == DefaultInstance) return this; PrepareBuilder(); if (other.HasType) { Type = other.Type; } if (other.HasMatcher) { Matcher = other.Matcher; } this.MergeUnknownFields(other.UnknownFields); return this; } public override Builder MergeFrom(pb::ICodedInputStream input) { return MergeFrom(input, pb::ExtensionRegistry.Empty); } public override Builder MergeFrom(pb::ICodedInputStream input, pb::ExtensionRegistry extensionRegistry) { PrepareBuilder(); pb::UnknownFieldSet.Builder unknownFields = null; uint tag; string field_name; while (input.ReadTag(out tag, out field_name)) { if (tag == 0 && field_name != null) { int field_ordinal = global::System.Array.BinarySearch(_selectionFieldNames, field_name, global::System.StringComparer.Ordinal); if (field_ordinal >= 0) tag = _selectionFieldTags[field_ordinal]; else { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); continue; } } switch (tag) { case 0: { throw pb::InvalidProtocolBufferException.InvalidTag(); } default: { if (pb::WireFormat.IsEndGroupTag(tag)) { if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } ParseUnknownField(input, unknownFields, extensionRegistry, tag, field_name); break; } case 8: { object unknown; if (input.ReadEnum(ref result.type_, out unknown)) { result.hasType = true; } else if (unknown is int) { if (unknownFields == null) { unknownFields = pb::UnknownFieldSet.CreateBuilder(this.UnknownFields); } unknownFields.MergeVarintField(1, (ulong) (int) unknown); } break; } case 18: { result.hasMatcher = input.ReadString(ref result.matcher_); break; } } } if (unknownFields != null) { this.UnknownFields = unknownFields.Build(); } return this; } public Builder SetType(global::PatternType value) { PrepareBuilder(); result.hasType = true; result.type_ = value; return this; } public Builder ClearType() { PrepareBuilder(); result.hasType = false; result.type_ = global::PatternType.PARENT; return this; } public Builder SetMatcher(string value) { pb::ThrowHelper.ThrowIfNull(value, "value"); PrepareBuilder(); result.hasMatcher = true; result.matcher_ = value; return this; } public Builder ClearMatcher() { PrepareBuilder(); result.hasMatcher = false; result.matcher_ = ""; return this; } } } #endregion #endregion Designer generated code
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Config { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Windows; using System.Xml; using NLog.Common; using NLog.Filters; using NLog.Internal; using NLog.Layouts; using NLog.Targets; using NLog.Targets.Wrappers; using NLog.Time; /// <summary> /// A class for configuring NLog through an XML configuration file /// (App.config style or App.nlog style). /// </summary> public class XmlLoggingConfiguration : LoggingConfiguration { private readonly ConfigurationItemFactory configurationItemFactory = ConfigurationItemFactory.Default; private readonly Dictionary<string, bool> visitedFile = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, string> variables = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); private string originalFileName; /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> public XmlLoggingConfiguration(string fileName) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="fileName">Configuration file to be read.</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(string fileName, bool ignoreErrors) { using (XmlReader reader = XmlReader.Create(fileName)) { this.Initialize(reader, fileName, ignoreErrors); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> public XmlLoggingConfiguration(XmlReader reader, string fileName) { this.Initialize(reader, fileName, false); } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> public XmlLoggingConfiguration(XmlReader reader, string fileName, bool ignoreErrors) { this.Initialize(reader, fileName, ignoreErrors); } #if !SILVERLIGHT /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, false); } } /// <summary> /// Initializes a new instance of the <see cref="XmlLoggingConfiguration" /> class. /// </summary> /// <param name="element">The XML element.</param> /// <param name="fileName">Name of the XML file.</param> /// <param name="ignoreErrors">If set to <c>true</c> errors will be ignored during file processing.</param> internal XmlLoggingConfiguration(XmlElement element, string fileName, bool ignoreErrors) { using (var stringReader = new StringReader(element.OuterXml)) { XmlReader reader = XmlReader.Create(stringReader); this.Initialize(reader, fileName, ignoreErrors); } } #endif #if !SILVERLIGHT /// <summary> /// Gets the default <see cref="LoggingConfiguration" /> object by parsing /// the application configuration file (<c>app.exe.config</c>). /// </summary> public static LoggingConfiguration AppConfig { get { object o = System.Configuration.ConfigurationManager.GetSection("nlog"); return o as LoggingConfiguration; } } #endif /// <summary> /// Gets or sets a value indicating whether the configuration files /// should be watched for changes and reloaded automatically when changed. /// </summary> public bool AutoReload { get; set; } /// <summary> /// Gets the collection of file names which should be watched for changes by NLog. /// This is the list of configuration files processed. /// If the <c>autoReload</c> attribute is not set it returns empty collection. /// </summary> public override IEnumerable<string> FileNamesToWatch { get { if (this.AutoReload) { return this.visitedFile.Keys; } return new string[0]; } } /// <summary> /// Re-reads the original configuration file and returns the new <see cref="LoggingConfiguration" /> object. /// </summary> /// <returns>The new <see cref="XmlLoggingConfiguration" /> object.</returns> public override LoggingConfiguration Reload() { return new XmlLoggingConfiguration(this.originalFileName); } private static bool IsTargetElement(string name) { return name.Equals("target", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target", StringComparison.OrdinalIgnoreCase); } private static bool IsTargetRefElement(string name) { return name.Equals("target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("wrapper-target-ref", StringComparison.OrdinalIgnoreCase) || name.Equals("compound-target-ref", StringComparison.OrdinalIgnoreCase); } private static string CleanWhitespace(string s) { s = s.Replace(" ", string.Empty); // get rid of the whitespace return s; } private static string StripOptionalNamespacePrefix(string attributeValue) { if (attributeValue == null) { return null; } int p = attributeValue.IndexOf(':'); if (p < 0) { return attributeValue; } return attributeValue.Substring(p + 1); } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Target is disposed elsewhere.")] private static Target WrapWithAsyncTargetWrapper(Target target) { var asyncTargetWrapper = new AsyncTargetWrapper(); asyncTargetWrapper.WrappedTarget = target; asyncTargetWrapper.Name = target.Name; target.Name = target.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with AsyncTargetWrapper and renaming to '{1}", asyncTargetWrapper.Name, target.Name); target = asyncTargetWrapper; return target; } /// <summary> /// Initializes the configuration. /// </summary> /// <param name="reader"><see cref="XmlReader"/> containing the configuration section.</param> /// <param name="fileName">Name of the file that contains the element (to be used as a base for including other files).</param> /// <param name="ignoreErrors">Ignore any errors during configuration.</param> private void Initialize(XmlReader reader, string fileName, bool ignoreErrors) { try { reader.MoveToContent(); var content = new NLogXmlElement(reader); if (fileName != null) { #if SILVERLIGHT string key = fileName; #else string key = Path.GetFullPath(fileName); #endif this.visitedFile[key] = true; this.originalFileName = fileName; this.ParseTopLevel(content, Path.GetDirectoryName(fileName)); InternalLogger.Info("Configured from an XML element in {0}...", fileName); } else { this.ParseTopLevel(content, null); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } NLogConfigurationException ConfigException = new NLogConfigurationException("Exception occurred when loading configuration from " + fileName, exception); if (!ignoreErrors) { if (LogManager.ThrowExceptions) { throw ConfigException; } else { InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException); } } else { InternalLogger.Error("Error in Parsing Configuration File. Exception : {0}", ConfigException); } } } private void ConfigureFromFile(string fileName) { #if SILVERLIGHT // file names are relative to XAP string key = fileName; #else string key = Path.GetFullPath(fileName); #endif if (this.visitedFile.ContainsKey(key)) { return; } this.visitedFile[key] = true; this.ParseTopLevel(new NLogXmlElement(fileName), Path.GetDirectoryName(fileName)); } private void ParseTopLevel(NLogXmlElement content, string baseDirectory) { content.AssertName("nlog", "configuration"); switch (content.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "CONFIGURATION": this.ParseConfigurationElement(content, baseDirectory); break; case "NLOG": this.ParseNLogElement(content, baseDirectory); break; } } private void ParseConfigurationElement(NLogXmlElement configurationElement, string baseDirectory) { InternalLogger.Trace("ParseConfigurationElement"); configurationElement.AssertName("configuration"); foreach (var el in configurationElement.Elements("nlog")) { this.ParseNLogElement(el, baseDirectory); } } private void ParseNLogElement(NLogXmlElement nlogElement, string baseDirectory) { InternalLogger.Trace("ParseNLogElement"); nlogElement.AssertName("nlog"); if (nlogElement.GetOptionalBooleanAttribute("useInvariantCulture", false)) { this.DefaultCultureInfo = CultureInfo.InvariantCulture; } this.AutoReload = nlogElement.GetOptionalBooleanAttribute("autoReload", false); LogManager.ThrowExceptions = nlogElement.GetOptionalBooleanAttribute("throwExceptions", LogManager.ThrowExceptions); InternalLogger.LogToConsole = nlogElement.GetOptionalBooleanAttribute("internalLogToConsole", InternalLogger.LogToConsole); InternalLogger.LogToConsoleError = nlogElement.GetOptionalBooleanAttribute("internalLogToConsoleError", InternalLogger.LogToConsoleError); InternalLogger.LogFile = nlogElement.GetOptionalAttribute("internalLogFile", InternalLogger.LogFile); InternalLogger.LogLevel = LogLevel.FromString(nlogElement.GetOptionalAttribute("internalLogLevel", InternalLogger.LogLevel.Name)); LogManager.GlobalThreshold = LogLevel.FromString(nlogElement.GetOptionalAttribute("globalThreshold", LogManager.GlobalThreshold.Name)); foreach (var el in nlogElement.Children) { switch (el.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "EXTENSIONS": this.ParseExtensionsElement(el, baseDirectory); break; case "INCLUDE": this.ParseIncludeElement(el, baseDirectory); break; case "APPENDERS": case "TARGETS": this.ParseTargetsElement(el); break; case "VARIABLE": this.ParseVariableElement(el); break; case "RULES": this.ParseRulesElement(el, this.LoggingRules); break; case "TIME": this.ParseTimeElement(el); break; default: InternalLogger.Warn("Skipping unknown node: {0}", el.LocalName); break; } } } private void ParseRulesElement(NLogXmlElement rulesElement, IList<LoggingRule> rulesCollection) { InternalLogger.Trace("ParseRulesElement"); rulesElement.AssertName("rules"); foreach (var loggerElement in rulesElement.Elements("logger")) { this.ParseLoggerElement(loggerElement, rulesCollection); } } private void ParseLoggerElement(NLogXmlElement loggerElement, IList<LoggingRule> rulesCollection) { loggerElement.AssertName("logger"); var namePattern = loggerElement.GetOptionalAttribute("name", "*"); var enabled = loggerElement.GetOptionalBooleanAttribute("enabled", true); if (!enabled) { InternalLogger.Debug("The logger named '{0}' are disabled"); return; } var rule = new LoggingRule(); string appendTo = loggerElement.GetOptionalAttribute("appendTo", null); if (appendTo == null) { appendTo = loggerElement.GetOptionalAttribute("writeTo", null); } rule.LoggerNamePattern = namePattern; if (appendTo != null) { foreach (string t in appendTo.Split(',')) { string targetName = t.Trim(); Target target = FindTargetByName(targetName); if (target != null) { rule.Targets.Add(target); } else { throw new NLogConfigurationException("Target " + targetName + " not found."); } } } rule.Final = loggerElement.GetOptionalBooleanAttribute("final", false); string levelString; if (loggerElement.AttributeValues.TryGetValue("level", out levelString)) { LogLevel level = LogLevel.FromString(levelString); rule.EnableLoggingForLevel(level); } else if (loggerElement.AttributeValues.TryGetValue("levels", out levelString)) { levelString = CleanWhitespace(levelString); string[] tokens = levelString.Split(','); foreach (string s in tokens) { if (!string.IsNullOrEmpty(s)) { LogLevel level = LogLevel.FromString(s); rule.EnableLoggingForLevel(level); } } } else { int minLevel = 0; int maxLevel = LogLevel.MaxLevel.Ordinal; string minLevelString; string maxLevelString; if (loggerElement.AttributeValues.TryGetValue("minLevel", out minLevelString)) { minLevel = LogLevel.FromString(minLevelString).Ordinal; } if (loggerElement.AttributeValues.TryGetValue("maxLevel", out maxLevelString)) { maxLevel = LogLevel.FromString(maxLevelString).Ordinal; } for (int i = minLevel; i <= maxLevel; ++i) { rule.EnableLoggingForLevel(LogLevel.FromOrdinal(i)); } } foreach (var child in loggerElement.Children) { switch (child.LocalName.ToUpper(CultureInfo.InvariantCulture)) { case "FILTERS": this.ParseFilters(rule, child); break; case "LOGGER": this.ParseLoggerElement(child, rule.ChildRules); break; } } rulesCollection.Add(rule); } private void ParseFilters(LoggingRule rule, NLogXmlElement filtersElement) { filtersElement.AssertName("filters"); foreach (var filterElement in filtersElement.Children) { string name = filterElement.LocalName; Filter filter = this.configurationItemFactory.Filters.CreateInstance(name); this.ConfigureObjectFromAttributes(filter, filterElement, false); rule.Filters.Add(filter); } } private void ParseVariableElement(NLogXmlElement variableElement) { variableElement.AssertName("variable"); string name = variableElement.GetRequiredAttribute("name"); string value = this.ExpandVariables(variableElement.GetRequiredAttribute("value")); this.variables[name] = value; } private void ParseTargetsElement(NLogXmlElement targetsElement) { targetsElement.AssertName("targets", "appenders"); bool asyncWrap = targetsElement.GetOptionalBooleanAttribute("async", false); NLogXmlElement defaultWrapperElement = null; var typeNameToDefaultTargetParameters = new Dictionary<string, NLogXmlElement>(); foreach (var targetElement in targetsElement.Children) { string name = targetElement.LocalName; string type = StripOptionalNamespacePrefix(targetElement.GetOptionalAttribute("type", null)); switch (name.ToUpper(CultureInfo.InvariantCulture)) { case "DEFAULT-WRAPPER": defaultWrapperElement = targetElement; break; case "DEFAULT-TARGET-PARAMETERS": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } typeNameToDefaultTargetParameters[type] = targetElement; break; case "TARGET": case "APPENDER": case "WRAPPER": case "WRAPPER-TARGET": case "COMPOUND-TARGET": if (type == null) { throw new NLogConfigurationException("Missing 'type' attribute on <" + name + "/>."); } Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); NLogXmlElement defaults; if (typeNameToDefaultTargetParameters.TryGetValue(type, out defaults)) { this.ParseTargetElement(newTarget, defaults); } this.ParseTargetElement(newTarget, targetElement); if (asyncWrap) { newTarget = WrapWithAsyncTargetWrapper(newTarget); } if (defaultWrapperElement != null) { newTarget = this.WrapWithDefaultWrapper(newTarget, defaultWrapperElement); } InternalLogger.Info("Adding target {0}", newTarget); AddTarget(newTarget.Name, newTarget); break; } } } private void ParseTargetElement(Target target, NLogXmlElement targetElement) { var compound = target as CompoundTargetBase; var wrapper = target as WrapperTargetBase; this.ConfigureObjectFromAttributes(target, targetElement, true); foreach (var childElement in targetElement.Children) { string name = childElement.LocalName; if (compound != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } compound.Targets.Add(newTarget); continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } compound.Targets.Add(newTarget); } continue; } } if (wrapper != null) { if (IsTargetRefElement(name)) { string targetName = childElement.GetRequiredAttribute("name"); Target newTarget = this.FindTargetByName(targetName); if (newTarget == null) { throw new NLogConfigurationException("Referenced target '" + targetName + "' not found."); } wrapper.WrappedTarget = newTarget; continue; } if (IsTargetElement(name)) { string type = StripOptionalNamespacePrefix(childElement.GetRequiredAttribute("type")); Target newTarget = this.configurationItemFactory.Targets.CreateInstance(type); if (newTarget != null) { this.ParseTargetElement(newTarget, childElement); if (newTarget.Name != null) { // if the new target has name, register it AddTarget(newTarget.Name, newTarget); } if (wrapper.WrappedTarget != null) { throw new NLogConfigurationException("Wrapped target already defined."); } wrapper.WrappedTarget = newTarget; } continue; } } this.SetPropertyFromElement(target, childElement); } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods", MessageId = "System.Reflection.Assembly.LoadFrom", Justification = "Need to load external assembly.")] private void ParseExtensionsElement(NLogXmlElement extensionsElement, string baseDirectory) { extensionsElement.AssertName("extensions"); foreach (var addElement in extensionsElement.Elements("add")) { string prefix = addElement.GetOptionalAttribute("prefix", null); if (prefix != null) { prefix = prefix + "."; } string type = StripOptionalNamespacePrefix(addElement.GetOptionalAttribute("type", null)); if (type != null) { this.configurationItemFactory.RegisterType(Type.GetType(type, true), prefix); } string assemblyFile = addElement.GetOptionalAttribute("assemblyFile", null); if (assemblyFile != null) { try { #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyFile, UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else string fullFileName = Path.Combine(baseDirectory, assemblyFile); InternalLogger.Info("Loading assembly file: {0}", fullFileName); Assembly asm = Assembly.LoadFrom(fullFileName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyFile, exception); } } continue; } string assemblyName = addElement.GetOptionalAttribute("assembly", null); if (assemblyName != null) { try { InternalLogger.Info("Loading assembly name: {0}", assemblyName); #if SILVERLIGHT var si = Application.GetResourceStream(new Uri(assemblyName + ".dll", UriKind.Relative)); var assemblyPart = new AssemblyPart(); Assembly asm = assemblyPart.Load(si.Stream); #else Assembly asm = Assembly.Load(assemblyName); #endif this.configurationItemFactory.RegisterItemsFromAssembly(asm, prefix); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error loading extensions: {0}", exception); if (LogManager.ThrowExceptions) { throw new NLogConfigurationException("Error loading extensions: " + assemblyName, exception); } } continue; } } } private void ParseIncludeElement(NLogXmlElement includeElement, string baseDirectory) { includeElement.AssertName("include"); string newFileName = includeElement.GetRequiredAttribute("file"); try { newFileName = this.ExpandVariables(newFileName); newFileName = SimpleLayout.Evaluate(newFileName); if (baseDirectory != null) { newFileName = Path.Combine(baseDirectory, newFileName); } #if SILVERLIGHT newFileName = newFileName.Replace("\\", "/"); if (Application.GetResourceStream(new Uri(newFileName, UriKind.Relative)) != null) #else if (File.Exists(newFileName)) #endif { InternalLogger.Debug("Including file '{0}'", newFileName); this.ConfigureFromFile(newFileName); } else { throw new FileNotFoundException("Included file not found: " + newFileName); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error when including '{0}' {1}", newFileName, exception); if (includeElement.GetOptionalBooleanAttribute("ignoreErrors", false)) { return; } throw new NLogConfigurationException("Error when including: " + newFileName, exception); } } private void ParseTimeElement(NLogXmlElement timeElement) { timeElement.AssertName("time"); string type = timeElement.GetRequiredAttribute("type"); TimeSource newTimeSource = this.configurationItemFactory.TimeSources.CreateInstance(type); this.ConfigureObjectFromAttributes(newTimeSource, timeElement, true); InternalLogger.Info("Selecting time source {0}", newTimeSource); TimeSource.Current = newTimeSource; } private void SetPropertyFromElement(object o, NLogXmlElement element) { if (this.AddArrayItemFromElement(o, element)) { return; } if (this.SetLayoutFromElement(o, element)) { return; } PropertyHelper.SetPropertyFromString(o, element.LocalName, this.ExpandVariables(element.Value), this.configurationItemFactory); } private bool AddArrayItemFromElement(object o, NLogXmlElement element) { string name = element.LocalName; PropertyInfo propInfo; if (!PropertyHelper.TryGetPropertyInfo(o, name, out propInfo)) { return false; } Type elementType = PropertyHelper.GetArrayItemType(propInfo); if (elementType != null) { IList propertyValue = (IList)propInfo.GetValue(o, null); object arrayItem = FactoryHelper.CreateInstance(elementType); this.ConfigureObjectFromAttributes(arrayItem, element, true); this.ConfigureObjectFromElement(arrayItem, element); propertyValue.Add(arrayItem); return true; } return false; } private void ConfigureObjectFromAttributes(object targetObject, NLogXmlElement element, bool ignoreType) { foreach (var kvp in element.AttributeValues) { string childName = kvp.Key; string childValue = kvp.Value; if (ignoreType && childName.Equals("type", StringComparison.OrdinalIgnoreCase)) { continue; } PropertyHelper.SetPropertyFromString(targetObject, childName, this.ExpandVariables(childValue), this.configurationItemFactory); } } private bool SetLayoutFromElement(object o, NLogXmlElement layoutElement) { PropertyInfo targetPropertyInfo; string name = layoutElement.LocalName; // if property exists if (PropertyHelper.TryGetPropertyInfo(o, name, out targetPropertyInfo)) { // and is a Layout if (typeof(Layout).IsAssignableFrom(targetPropertyInfo.PropertyType)) { string layoutTypeName = StripOptionalNamespacePrefix(layoutElement.GetOptionalAttribute("type", null)); // and 'type' attribute has been specified if (layoutTypeName != null) { // configure it from current element Layout layout = this.configurationItemFactory.Layouts.CreateInstance(this.ExpandVariables(layoutTypeName)); this.ConfigureObjectFromAttributes(layout, layoutElement, true); this.ConfigureObjectFromElement(layout, layoutElement); targetPropertyInfo.SetValue(o, layout, null); return true; } } } return false; } private void ConfigureObjectFromElement(object targetObject, NLogXmlElement element) { foreach (var child in element.Children) { this.SetPropertyFromElement(targetObject, child); } } private Target WrapWithDefaultWrapper(Target t, NLogXmlElement defaultParameters) { string wrapperType = StripOptionalNamespacePrefix(defaultParameters.GetRequiredAttribute("type")); Target wrapperTargetInstance = this.configurationItemFactory.Targets.CreateInstance(wrapperType); WrapperTargetBase wtb = wrapperTargetInstance as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Target type specified on <default-wrapper /> is not a wrapper."); } this.ParseTargetElement(wrapperTargetInstance, defaultParameters); while (wtb.WrappedTarget != null) { wtb = wtb.WrappedTarget as WrapperTargetBase; if (wtb == null) { throw new NLogConfigurationException("Child target type specified on <default-wrapper /> is not a wrapper."); } } wtb.WrappedTarget = t; wrapperTargetInstance.Name = t.Name; t.Name = t.Name + "_wrapped"; InternalLogger.Debug("Wrapping target '{0}' with '{1}' and renaming to '{2}", wrapperTargetInstance.Name, wrapperTargetInstance.GetType().Name, t.Name); return wrapperTargetInstance; } private string ExpandVariables(string input) { string output = input; // TODO - make this case-insensitive, will probably require a different approach foreach (var kvp in this.variables) { output = output.Replace("${" + kvp.Key + "}", kvp.Value); } return output; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Security.Cryptography.EcDsa.Tests; using Test.Cryptography; using Xunit; namespace System.Security.Cryptography.Cng.Tests { public class ECDsaCngTests : ECDsaTestsBase { [Fact] public static void TestPositive256WithBlob() { CngKey key = TestData.s_ECDsa256Key; ECDsaCng e = new ECDsaCng(key); Verify256(e, true); } [Fact] public static void TestNegativeVerify256() { CngKey key = TestData.s_ECDsa256Key; ECDsaCng e = new ECDsaCng(key); byte[] tamperedSig = ("998791331eb2e1f4259297f5d9cb82fa20dec98e1cb0900e6b8f014a406c3d02cbdbf5238bde471c3155fc25565524301429" + "e8713dad9a67eb0a5c355e9e23dc").HexToByteArray(); bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig); Assert.False(verified); } [Fact] public static void TestPositiveVerify384() { CngKey key = TestData.s_ECDsa384Key; ECDsaCng e = new ECDsaCng(key); byte[] sig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8" + "2366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray(); bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig); Assert.True(verified); } [Fact] public static void TestNegativeVerify384() { CngKey key = TestData.s_ECDsa384Key; ECDsaCng e = new ECDsaCng(key); byte[] tamperedSig = ("7805c494b17bba8cba09d3e5cdd16d69ce785e56c4f2d9d9061d549fce0a6860cca1cb9326bd534da21ad4ff326a1e0810d8" + "f366eb6afc66ede0d1ffe345f6b37ac622ed77838b42825ceb96cd3996d3d77fd6a248357ae1ae6cb85f048b1b04").HexToByteArray(); bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig); Assert.False(verified); } [Fact] public static void TestPositiveVerify521() { CngKey key = TestData.s_ECDsa521Key; ECDsaCng e = new ECDsaCng(key); byte[] sig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845" + "b6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7" + "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray(); bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, sig); Assert.True(verified); } [Fact] public static void TestNegativeVerify521() { CngKey key = TestData.s_ECDsa521Key; ECDsaCng e = new ECDsaCng(key); byte[] tamperedSig = ("0084461450745672df85735fbf89f2dccef804d6b56e86ca45ea5c366a05a5de96327eddb75582821c6315c8bb823c875845" + "a6f25963ddab70461b786261507f971401fdc300697824129e0a84e0ba1ab4820ac7b29e7f8248bc2e29d152a9190eb3fcb7" + "6e8ebf1aa5dd28ffd582a24cbfebb3426a5f933ce1d995b31c951103d24f6256").HexToByteArray(); bool verified = e.VerifyHash(ECDsaTestData.s_hashSha512, tamperedSig); Assert.False(verified); } [Fact] public static void TestVerify521_EcdhKey() { byte[] keyBlob = (byte[])TestData.s_ECDsa521KeyBlob.Clone(); // Rewrite the dwMagic value to be ECDH // ECDSA prefix: 45 43 53 36 // ECDH prefix : 45 43 4b 36 keyBlob[2] = 0x4b; using (CngKey ecdh521 = CngKey.Import(keyBlob, CngKeyBlobFormat.EccPrivateBlob)) { // Preconditions: Assert.Equal(CngAlgorithmGroup.ECDiffieHellman, ecdh521.AlgorithmGroup); Assert.Equal(CngAlgorithm.ECDiffieHellmanP521, ecdh521.Algorithm); using (ECDsa ecdsaFromEcdsaKey = new ECDsaCng(TestData.s_ECDsa521Key)) using (ECDsa ecdsaFromEcdhKey = new ECDsaCng(ecdh521)) { byte[] ecdhKeySignature = ecdsaFromEcdhKey.SignData(keyBlob, HashAlgorithmName.SHA512); byte[] ecdsaKeySignature = ecdsaFromEcdsaKey.SignData(keyBlob, HashAlgorithmName.SHA512); Assert.True( ecdsaFromEcdhKey.VerifyData(keyBlob, ecdsaKeySignature, HashAlgorithmName.SHA512), "ECDsaCng(ECDHKey) validates ECDsaCng(ECDsaKey)"); Assert.True( ecdsaFromEcdsaKey.VerifyData(keyBlob, ecdhKeySignature, HashAlgorithmName.SHA512), "ECDsaCng(ECDsaKey) validates ECDsaCng(ECDHKey)"); } } } [Fact] public static void CreateEcdsaFromRsaKey_Fails() { using (RSACng rsaCng = new RSACng()) { Assert.Throws<ArgumentException>(() => new ECDsaCng(rsaCng.Key)); } } [Theory, MemberData(nameof(TestCurves))] public static void TestKeyPropertyFromNamedCurve(CurveDef curveDef) { ECDsaCng e = new ECDsaCng(curveDef.Curve); CngKey key1 = e.Key; VerifyKey(key1); e.Exercise(); CngKey key2 = e.Key; Assert.Same(key1, key2); } [Fact] public static void TestCreateKeyFromCngAlgorithmNistP256() { CngAlgorithm alg = CngAlgorithm.ECDsaP256; using (CngKey key = CngKey.Create(alg)) { VerifyKey(key); using (ECDsaCng e = new ECDsaCng(key)) { Assert.Equal(CngAlgorithmGroup.ECDsa, e.Key.AlgorithmGroup); Assert.Equal(CngAlgorithm.ECDsaP256, e.Key.Algorithm); VerifyKey(e.Key); e.Exercise(); } } } [Fact] public static void TestCreateByKeySizeNistP256() { using (ECDsaCng cng = new ECDsaCng(256)) { CngKey key1 = cng.Key; Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup); // The three legacy nist curves are not treated as generic named curves Assert.Equal(CngAlgorithm.ECDsaP256, key1.Algorithm); Assert.Equal(256, key1.KeySize); VerifyKey(key1); } } [Fact] public static void TestCreateByNameNistP521() { using (ECDsaCng cng = new ECDsaCng(ECCurve.NamedCurves.nistP521)) { CngKey key1 = cng.Key; Assert.Equal(CngAlgorithmGroup.ECDsa, key1.AlgorithmGroup); // The three legacy nist curves are not treated as generic named curves Assert.Equal(CngAlgorithm.ECDsaP521, key1.Algorithm); Assert.Equal(521, key1.KeySize); VerifyKey(key1); } } [Theory, MemberData(nameof(TestInvalidCurves))] public static void TestCreateKeyFromCngAlgorithmNegative(CurveDef curveDef) { CngAlgorithm alg = CngAlgorithm.ECDsa; Assert.ThrowsAny<Exception>(() => CngKey.Create(alg)); } [Theory, MemberData(nameof(SpecialNistKeys))] public static void TestSpecialNistKeys(int keySize, string curveName, CngAlgorithm algorithm) { using (ECDsaCng cng = (ECDsaCng)ECDsaFactory.Create(keySize)) { Assert.Equal(keySize, cng.KeySize); ECParameters param = cng.ExportParameters(false); Assert.Equal(curveName, param.Curve.Oid.FriendlyName); Assert.Equal(algorithm, cng.Key.Algorithm); } } public static IEnumerable<object[]> SpecialNistKeys { get { yield return new object[] { 256, "nistP256", CngAlgorithm.ECDsaP256}; yield return new object[] { 384, "nistP384", CngAlgorithm.ECDsaP384}; yield return new object[] { 521, "nistP521", CngAlgorithm.ECDsaP521}; } } private static void VerifyKey(CngKey key) { Assert.Equal("ECDSA", key.AlgorithmGroup.AlgorithmGroup); Assert.False(string.IsNullOrEmpty(key.Algorithm.Algorithm)); Assert.True(key.KeySize > 0); } } }
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ==================================================================== */ namespace TestCases.SS.UserModel { using System; using NUnit.Framework; using NPOI.SS; using NPOI.SS.UserModel; using NPOI.SS.Util; using TestCases.SS; using NPOI.HSSF.Util; using NPOI.HSSF.UserModel; /** * @author Dmitriy Kumshayev * @author Yegor Kozlov */ [TestFixture] public abstract class BaseTestConditionalFormatting { private ITestDataProvider _testDataProvider; public BaseTestConditionalFormatting() { _testDataProvider = TestCases.HSSF.HSSFITestDataProvider.Instance; } public BaseTestConditionalFormatting(ITestDataProvider TestDataProvider) { _testDataProvider = TestDataProvider; } protected abstract void AssertColour(String hexExpected, IColor actual); [Test] public void TestBasic() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; Assert.AreEqual(0, sheetCF.NumConditionalFormattings); try { Assert.IsNull(sheetCF.GetConditionalFormattingAt(0)); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } try { sheetCF.RemoveConditionalFormatting(0); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule("1"); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule("2"); IConditionalFormattingRule rule3 = sheetCF.CreateConditionalFormattingRule("3"); IConditionalFormattingRule rule4 = sheetCF.CreateConditionalFormattingRule("4"); try { sheetCF.AddConditionalFormatting(null, rule1); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("regions must not be null")); } try { sheetCF.AddConditionalFormatting( new CellRangeAddress[] { CellRangeAddress.ValueOf("A1:A3") }, (IConditionalFormattingRule)null); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("cfRules must not be null")); } try { sheetCF.AddConditionalFormatting( new CellRangeAddress[] { CellRangeAddress.ValueOf("A1:A3") }, new IConditionalFormattingRule[0]); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("cfRules must not be empty")); } try { sheetCF.AddConditionalFormatting( new CellRangeAddress[] { CellRangeAddress.ValueOf("A1:A3") }, new IConditionalFormattingRule[] { rule1, rule2, rule3, rule4 }); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Number of rules must not exceed 3")); } wb.Close(); } /** * Test format conditions based on a bool formula */ [Test] public void TestBooleanFormulaConditions() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule("SUM(A1:A5)>10"); Assert.AreEqual(ConditionType.Formula, rule1.ConditionType); Assert.AreEqual("SUM(A1:A5)>10", rule1.Formula1); int formatIndex1 = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("B1"), CellRangeAddress.ValueOf("C3"), }, rule1); Assert.AreEqual(0, formatIndex1); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); CellRangeAddress[] ranges1 = sheetCF.GetConditionalFormattingAt(formatIndex1).GetFormattingRanges(); Assert.AreEqual(2, ranges1.Length); Assert.AreEqual("B1", ranges1[0].FormatAsString()); Assert.AreEqual("C3", ranges1[1].FormatAsString()); // adjacent Address are merged int formatIndex2 = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("B1"), CellRangeAddress.ValueOf("B2"), CellRangeAddress.ValueOf("B3"), }, rule1); Assert.AreEqual(1, formatIndex2); Assert.AreEqual(2, sheetCF.NumConditionalFormattings); CellRangeAddress[] ranges2 = sheetCF.GetConditionalFormattingAt(formatIndex2).GetFormattingRanges(); Assert.AreEqual(1, ranges2.Length); Assert.AreEqual("B1:B3", ranges2[0].FormatAsString()); wb.Close(); } [Test] public void TestSingleFormulaConditions() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sh = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Equal, "SUM(A1:A5)+10"); Assert.AreEqual(ConditionType.CellValueIs, rule1.ConditionType); Assert.AreEqual("SUM(A1:A5)+10", rule1.Formula1); Assert.AreEqual(ComparisonOperator.Equal, rule1.ComparisonOperation); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.NotEqual, "15"); Assert.AreEqual(ConditionType.CellValueIs, rule2.ConditionType); Assert.AreEqual("15", rule2.Formula1); Assert.AreEqual(ComparisonOperator.NotEqual, rule2.ComparisonOperation); IConditionalFormattingRule rule3 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.NotEqual, "15"); Assert.AreEqual(ConditionType.CellValueIs, rule3.ConditionType); Assert.AreEqual("15", rule3.Formula1); Assert.AreEqual(ComparisonOperator.NotEqual, rule3.ComparisonOperation); IConditionalFormattingRule rule4 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.GreaterThan, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule4.ConditionType); Assert.AreEqual("0", rule4.Formula1); Assert.AreEqual(ComparisonOperator.GreaterThan, rule4.ComparisonOperation); IConditionalFormattingRule rule5 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.LessThan, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule5.ConditionType); Assert.AreEqual("0", rule5.Formula1); Assert.AreEqual(ComparisonOperator.LessThan, rule5.ComparisonOperation); IConditionalFormattingRule rule6 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.GreaterThanOrEqual, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule6.ConditionType); Assert.AreEqual("0", rule6.Formula1); Assert.AreEqual(ComparisonOperator.GreaterThanOrEqual, rule6.ComparisonOperation); IConditionalFormattingRule rule7 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.LessThanOrEqual, "0"); Assert.AreEqual(ConditionType.CellValueIs, rule7.ConditionType); Assert.AreEqual("0", rule7.Formula1); Assert.AreEqual(ComparisonOperator.LessThanOrEqual, rule7.ComparisonOperation); IConditionalFormattingRule rule8 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "0", "5"); Assert.AreEqual(ConditionType.CellValueIs, rule8.ConditionType); Assert.AreEqual("0", rule8.Formula1); Assert.AreEqual("5", rule8.Formula2); Assert.AreEqual(ComparisonOperator.Between, rule8.ComparisonOperation); IConditionalFormattingRule rule9 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.NotBetween, "0", "5"); Assert.AreEqual(ConditionType.CellValueIs, rule9.ConditionType); Assert.AreEqual("0", rule9.Formula1); Assert.AreEqual("5", rule9.Formula2); Assert.AreEqual(ComparisonOperator.NotBetween, rule9.ComparisonOperation); wb.Close(); } [Test] public void TestCopy() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); ISheet sheet2 = wb.CreateSheet(); ISheetConditionalFormatting sheet1CF = sheet1.SheetConditionalFormatting; ISheetConditionalFormatting sheet2CF = sheet2.SheetConditionalFormatting; Assert.AreEqual(0, sheet1CF.NumConditionalFormattings); Assert.AreEqual(0, sheet2CF.NumConditionalFormattings); IConditionalFormattingRule rule1 = sheet1CF.CreateConditionalFormattingRule( ComparisonOperator.Equal, "SUM(A1:A5)+10"); IConditionalFormattingRule rule2 = sheet1CF.CreateConditionalFormattingRule( ComparisonOperator.NotEqual, "15"); // adjacent Address are merged int formatIndex = sheet1CF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("A1:A5"), CellRangeAddress.ValueOf("C1:C5") }, rule1, rule2); Assert.AreEqual(0, formatIndex); Assert.AreEqual(1, sheet1CF.NumConditionalFormattings); Assert.AreEqual(0, sheet2CF.NumConditionalFormattings); sheet2CF.AddConditionalFormatting(sheet1CF.GetConditionalFormattingAt(formatIndex)); Assert.AreEqual(1, sheet2CF.NumConditionalFormattings); IConditionalFormatting sheet2cf = sheet2CF.GetConditionalFormattingAt(0); Assert.AreEqual(2, sheet2cf.NumberOfRules); Assert.AreEqual("SUM(A1:A5)+10", sheet2cf.GetRule(0).Formula1); Assert.AreEqual(ComparisonOperator.Equal, sheet2cf.GetRule(0).ComparisonOperation); Assert.AreEqual(ConditionType.CellValueIs, sheet2cf.GetRule(0).ConditionType); Assert.AreEqual("15", sheet2cf.GetRule(1).Formula1); Assert.AreEqual(ComparisonOperator.NotEqual, sheet2cf.GetRule(1).ComparisonOperation); Assert.AreEqual(ConditionType.CellValueIs, sheet2cf.GetRule(1).ConditionType); wb.Close(); } [Test] public void TestRemove() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet1 = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet1.SheetConditionalFormatting; Assert.AreEqual(0, sheetCF.NumConditionalFormattings); IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Equal, "SUM(A1:A5)"); // adjacent Address are merged int formatIndex = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("A1:A5") }, rule1); Assert.AreEqual(0, formatIndex); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); sheetCF.RemoveConditionalFormatting(0); Assert.AreEqual(0, sheetCF.NumConditionalFormattings); try { Assert.IsNull(sheetCF.GetConditionalFormattingAt(0)); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } formatIndex = sheetCF.AddConditionalFormatting( new CellRangeAddress[]{ CellRangeAddress.ValueOf("A1:A5") }, rule1); Assert.AreEqual(0, formatIndex); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); sheetCF.RemoveConditionalFormatting(0); Assert.AreEqual(0, sheetCF.NumConditionalFormattings); try { Assert.IsNull(sheetCF.GetConditionalFormattingAt(0)); Assert.Fail("expected exception"); } catch (ArgumentException e) { Assert.IsTrue(e.Message.StartsWith("Specified CF index 0 is outside the allowable range")); } wb.Close(); } [Test] public void TestCreateCF() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); String formula = "7"; ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(formula); IFontFormatting fontFmt = rule1.CreateFontFormatting(); fontFmt.SetFontStyle(true, false); IBorderFormatting bordFmt = rule1.CreateBorderFormatting(); bordFmt.BorderBottom = (/*setter*/BorderStyle.Thin); bordFmt.BorderTop = (/*setter*/BorderStyle.Thick); bordFmt.BorderLeft = (/*setter*/BorderStyle.Dashed); bordFmt.BorderRight = (/*setter*/BorderStyle.Dotted); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Yellow.Index); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Between, "1", "2"); IConditionalFormattingRule[] cfRules = { rule1, rule2 }; short col = 1; CellRangeAddress[] regions = { new CellRangeAddress(0, 65535, col, col) }; sheetCF.AddConditionalFormatting(regions, cfRules); sheetCF.AddConditionalFormatting(regions, cfRules); // Verification Assert.AreEqual(2, sheetCF.NumConditionalFormattings); sheetCF.RemoveConditionalFormatting(1); Assert.AreEqual(1, sheetCF.NumConditionalFormattings); IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); regions = cf.GetFormattingRanges(); Assert.IsNotNull(regions); Assert.AreEqual(1, regions.Length); CellRangeAddress r = regions[0]; Assert.AreEqual(1, r.FirstColumn); Assert.AreEqual(1, r.LastColumn); Assert.AreEqual(0, r.FirstRow); Assert.AreEqual(65535, r.LastRow); Assert.AreEqual(2, cf.NumberOfRules); rule1 = cf.GetRule(0); Assert.AreEqual("7", rule1.Formula1); Assert.IsNull(rule1.Formula2); IFontFormatting r1fp = rule1.FontFormatting; Assert.IsNotNull(r1fp); Assert.IsTrue(r1fp.IsItalic); Assert.IsFalse(r1fp.IsBold); IBorderFormatting r1bf = rule1.BorderFormatting; Assert.IsNotNull(r1bf); Assert.AreEqual(BorderStyle.Thin, r1bf.BorderBottom); Assert.AreEqual(BorderStyle.Thick, r1bf.BorderTop); Assert.AreEqual(BorderStyle.Dashed, r1bf.BorderLeft); Assert.AreEqual(BorderStyle.Dotted, r1bf.BorderRight); IPatternFormatting r1pf = rule1.PatternFormatting; Assert.IsNotNull(r1pf); // Assert.AreEqual(HSSFColor.Yellow.index,r1pf.FillBackgroundColor); rule2 = cf.GetRule(1); Assert.AreEqual("2", rule2.Formula2); Assert.AreEqual("1", rule2.Formula1); workbook.Close(); } [Test] public void TestClone() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); String formula = "7"; ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(formula); IFontFormatting fontFmt = rule1.CreateFontFormatting(); fontFmt.SetFontStyle(true, false); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Yellow.Index); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Between, "1", "2"); IConditionalFormattingRule[] cfRules = { rule1, rule2 }; short col = 1; CellRangeAddress[] regions = { new CellRangeAddress(0, 65535, col, col) }; sheetCF.AddConditionalFormatting(regions, cfRules); try { wb.CloneSheet(0); Assert.AreEqual(2, wb.NumberOfSheets); } catch (Exception e) { if (e.Message.IndexOf("needs to define a clone method") > 0) { Assert.Fail("Indentified bug 45682"); } throw e; } finally { wb.Close(); } } [Test] public void TestShiftRows() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "SUM(A10:A15)", "1+SUM(B16:B30)"); IFontFormatting fontFmt = rule1.CreateFontFormatting(); fontFmt.SetFontStyle(true, false); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Yellow.Index); IConditionalFormattingRule rule2 = sheetCF.CreateConditionalFormattingRule( ComparisonOperator.Between, "SUM(A10:A15)", "1+SUM(B16:B30)"); IBorderFormatting borderFmt = rule2.CreateBorderFormatting(); borderFmt.BorderDiagonal= BorderStyle.Medium; CellRangeAddress[] regions = { new CellRangeAddress(2, 4, 0, 0), // A3:A5 }; sheetCF.AddConditionalFormatting(regions, rule1); sheetCF.AddConditionalFormatting(regions, rule2); // This row-shift should destroy the CF region sheet.ShiftRows(10, 20, -9); Assert.AreEqual(0, sheetCF.NumConditionalFormattings); // re-add the CF sheetCF.AddConditionalFormatting(regions, rule1); sheetCF.AddConditionalFormatting(regions, rule2); // This row shift should only affect the formulas sheet.ShiftRows(14, 17, 8); IConditionalFormatting cf1 = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual("SUM(A10:A23)", cf1.GetRule(0).Formula1); Assert.AreEqual("1+SUM(B24:B30)", cf1.GetRule(0).Formula2); IConditionalFormatting cf2 = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual("SUM(A10:A23)", cf2.GetRule(0).Formula1); Assert.AreEqual("1+SUM(B24:B30)", cf2.GetRule(0).Formula2); sheet.ShiftRows(0, 8, 21); cf1 = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual("SUM(A10:A21)", cf1.GetRule(0).Formula1); Assert.AreEqual("1+SUM(#REF!)", cf1.GetRule(0).Formula2); cf2 = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual("SUM(A10:A21)", cf2.GetRule(0).Formula1); Assert.AreEqual("1+SUM(#REF!)", cf2.GetRule(0).Formula2); wb.Close(); } // protected void TestRead(string sampleFile) { IWorkbook wb = _testDataProvider.OpenSampleWorkbook(sampleFile); ISheet sh = wb.GetSheet("CF"); ISheetConditionalFormatting sheetCF = sh.SheetConditionalFormatting; Assert.AreEqual(3, sheetCF.NumConditionalFormattings); IConditionalFormatting cf1 = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual(2, cf1.NumberOfRules); CellRangeAddress[] regions1 = cf1.GetFormattingRanges(); Assert.AreEqual(1, regions1.Length); Assert.AreEqual("A1:A8", regions1[0].FormatAsString()); // CF1 has two rules: values less than -3 are bold-italic red, values greater than 3 are green IConditionalFormattingRule rule1 = cf1.GetRule(0); Assert.AreEqual(ConditionType.CellValueIs, rule1.ConditionType); Assert.AreEqual(ComparisonOperator.GreaterThan, rule1.ComparisonOperation); Assert.AreEqual("3", rule1.Formula1); Assert.IsNull(rule1.Formula2); // Fills and borders are not Set Assert.IsNull(rule1.PatternFormatting); Assert.IsNull(rule1.BorderFormatting); IFontFormatting fmt1 = rule1.FontFormatting; // Assert.AreEqual(HSSFColor.GREEN.index, fmt1.FontColorIndex); Assert.IsTrue(fmt1.IsBold); Assert.IsFalse(fmt1.IsItalic); IConditionalFormattingRule rule2 = cf1.GetRule(1); Assert.AreEqual(ConditionType.CellValueIs, rule2.ConditionType); Assert.AreEqual(ComparisonOperator.LessThan, rule2.ComparisonOperation); Assert.AreEqual("-3", rule2.Formula1); Assert.IsNull(rule2.Formula2); Assert.IsNull(rule2.PatternFormatting); Assert.IsNull(rule2.BorderFormatting); IFontFormatting fmt2 = rule2.FontFormatting; // Assert.AreEqual(HSSFColor.Red.index, fmt2.FontColorIndex); Assert.IsTrue(fmt2.IsBold); Assert.IsTrue(fmt2.IsItalic); IConditionalFormatting cf2 = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual(1, cf2.NumberOfRules); CellRangeAddress[] regions2 = cf2.GetFormattingRanges(); Assert.AreEqual(1, regions2.Length); Assert.AreEqual("B9", regions2[0].FormatAsString()); IConditionalFormattingRule rule3 = cf2.GetRule(0); Assert.AreEqual(ConditionType.Formula, rule3.ConditionType); Assert.AreEqual(ComparisonOperator.NoComparison, rule3.ComparisonOperation); Assert.AreEqual("$A$8>5", rule3.Formula1); Assert.IsNull(rule3.Formula2); IFontFormatting fmt3 = rule3.FontFormatting; // Assert.AreEqual(HSSFColor.Red.index, fmt3.FontColorIndex); Assert.IsTrue(fmt3.IsBold); Assert.IsTrue(fmt3.IsItalic); IPatternFormatting fmt4 = rule3.PatternFormatting; // Assert.AreEqual(HSSFColor.LIGHT_CORNFLOWER_BLUE.index, fmt4.FillBackgroundColor); // Assert.AreEqual(HSSFColor.Automatic.index, fmt4.FillForegroundColor); Assert.AreEqual(FillPattern.NoFill, fmt4.FillPattern); // borders are not Set Assert.IsNull(rule3.BorderFormatting); IConditionalFormatting cf3 = sheetCF.GetConditionalFormattingAt(2); CellRangeAddress[] regions3 = cf3.GetFormattingRanges(); Assert.AreEqual(1, regions3.Length); Assert.AreEqual("B1:B7", regions3[0].FormatAsString()); Assert.AreEqual(2, cf3.NumberOfRules); IConditionalFormattingRule rule4 = cf3.GetRule(0); Assert.AreEqual(ConditionType.CellValueIs, rule4.ConditionType); Assert.AreEqual(ComparisonOperator.LessThanOrEqual, rule4.ComparisonOperation); Assert.AreEqual("\"AAA\"", rule4.Formula1); Assert.IsNull(rule4.Formula2); IConditionalFormattingRule rule5 = cf3.GetRule(1); Assert.AreEqual(ConditionType.CellValueIs, rule5.ConditionType); Assert.AreEqual(ComparisonOperator.Between, rule5.ComparisonOperation); Assert.AreEqual("\"A\"", rule5.Formula1); Assert.AreEqual("\"AAA\"", rule5.Formula2); wb.Close(); } public void testReadOffice2007(String filename) { IWorkbook wb = _testDataProvider.OpenSampleWorkbook(filename); ISheet s = wb.GetSheet("CF"); IConditionalFormatting cf = null; IConditionalFormattingRule cr = null; // Sanity check data Assert.AreEqual("Values", s.GetRow(0).GetCell(0).ToString()); Assert.AreEqual("10", s.GetRow(2).GetCell(0).ToString()); //Assert.AreEqual("10.0", s.GetRow(2).GetCell(0).ToString()); // Check we found all the conditional formattings rules we should have ISheetConditionalFormatting sheetCF = s.SheetConditionalFormatting; int numCF = 3; int numCF12 = 15; int numCFEX = 0; // TODO This should be 1, but we don't support CFEX formattings yet Assert.AreEqual(numCF + numCF12 + numCFEX, sheetCF.NumConditionalFormattings); int fCF = 0, fCF12 = 0, fCFEX = 0; for (int i = 0; i < sheetCF.NumConditionalFormattings; i++) { cf = sheetCF.GetConditionalFormattingAt(i); if (cf is HSSFConditionalFormatting) { String str = cf.ToString(); if (str.Contains("[CF]")) fCF++; if (str.Contains("[CF12]")) fCF12++; if (str.Contains("[CFEX]")) fCFEX++; } else { ConditionType type = cf.GetRule(cf.NumberOfRules - 1).ConditionType; if (type == ConditionType.CellValueIs || type == ConditionType.Formula) { fCF++; } else { // TODO Properly detect Ext ones from the xml fCF12++; } } } Assert.AreEqual(numCF, fCF); Assert.AreEqual(numCF12, fCF12); Assert.AreEqual(numCFEX, fCFEX); // Check the rules / values in detail // Highlight Positive values - Column C cf = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("C2:C17", cf.GetFormattingRanges()[0].FormatAsString()); Assert.AreEqual(1, cf.NumberOfRules); cr = cf.GetRule(0); Assert.AreEqual(ConditionType.CellValueIs, cr.ConditionType); Assert.AreEqual(ComparisonOperator.GreaterThan, cr.ComparisonOperation); Assert.AreEqual("0", cr.Formula1); Assert.AreEqual(null, cr.Formula2); // When it matches: // Sets the font colour to dark green // Sets the background colour to lighter green // TODO Should the colours be slightly different between formats? if (cr is HSSFConditionalFormattingRule) { AssertColour("0:8080:0", cr.FontFormatting.FontColor); AssertColour("CCCC:FFFF:CCCC", cr.PatternFormatting.FillBackgroundColorColor); } else { AssertColour("006100", cr.FontFormatting.FontColor); AssertColour("C6EFCE", cr.PatternFormatting.FillBackgroundColorColor); } // Highlight 10-30 - Column D cf = sheetCF.GetConditionalFormattingAt(1); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("D2:D17", cf.GetFormattingRanges()[0].FormatAsString()); Assert.AreEqual(1, cf.NumberOfRules); cr = cf.GetRule(0); Assert.AreEqual(ConditionType.CellValueIs, cr.ConditionType); Assert.AreEqual(ComparisonOperator.Between, cr.ComparisonOperation); Assert.AreEqual("10", cr.Formula1); Assert.AreEqual("30", cr.Formula2); // When it matches: // Sets the font colour to dark red // Sets the background colour to lighter red // TODO Should the colours be slightly different between formats? if (cr is HSSFConditionalFormattingRule) { AssertColour("8080:0:8080", cr.FontFormatting.FontColor); AssertColour("FFFF:9999:CCCC", cr.PatternFormatting.FillBackgroundColorColor); } else { AssertColour("9C0006", cr.FontFormatting.FontColor); AssertColour("FFC7CE", cr.PatternFormatting.FillBackgroundColorColor); } // Data Bars - Column E cf = sheetCF.GetConditionalFormattingAt(2); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("E2:E17", cf.GetFormattingRanges()[0].FormatAsString()); assertDataBar(cf, "FF63C384"); // Colours Red->Yellow->Green - Column F cf = sheetCF.GetConditionalFormattingAt(3); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("F2:F17", cf.GetFormattingRanges()[0].FormatAsString()); assertColorScale(cf, "F8696B", "FFEB84", "63BE7B"); // Colours Blue->White->Red - Column G cf = sheetCF.GetConditionalFormattingAt(4); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("G2:G17", cf.GetFormattingRanges()[0].FormatAsString()); assertColorScale(cf, "5A8AC6", "FCFCFF", "F8696B"); // TODO Simplify asserts // Icons : Default - Column H, percentage thresholds cf = sheetCF.GetConditionalFormattingAt(5); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("H2:H17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_TRAFFIC_LIGHTS, 0d, 33d, 67d); // Icons : 3 signs - Column I cf = sheetCF.GetConditionalFormattingAt(6); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("I2:I17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_SHAPES, 0d, 33d, 67d); // Icons : 3 traffic lights 2 - Column J cf = sheetCF.GetConditionalFormattingAt(7); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("J2:J17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_TRAFFIC_LIGHTS_BOX, 0d, 33d, 67d); // Icons : 4 traffic lights - Column K cf = sheetCF.GetConditionalFormattingAt(8); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("K2:K17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYRB_4_TRAFFIC_LIGHTS, 0d, 25d, 50d, 75d); // Icons : 3 symbols with backgrounds - Column L cf = sheetCF.GetConditionalFormattingAt(9); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("L2:L17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_SYMBOLS_CIRCLE, 0d, 33d, 67d); // Icons : 3 flags - Column M2 Only cf = sheetCF.GetConditionalFormattingAt(10); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("M2", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_FLAGS, 0d, 33d, 67d); // Icons : 3 flags - Column M (all) cf = sheetCF.GetConditionalFormattingAt(11); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("M2:M17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_FLAGS, 0d, 33d, 67d); // Icons : 3 symbols 2 (no background) - Column N cf = sheetCF.GetConditionalFormattingAt(12); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("N2:N17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_SYMBOLS, 0d, 33d, 67d); // Icons : 3 arrows - Column O cf = sheetCF.GetConditionalFormattingAt(13); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("O2:O17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GYR_3_ARROW, 0d, 33d, 67d); // Icons : 5 arrows grey - Column P cf = sheetCF.GetConditionalFormattingAt(14); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("P2:P17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.GREY_5_ARROWS, 0d, 20d, 40d, 60d, 80d); // Icons : 3 stars (ext) - Column Q // TODO Support EXT formattings // Icons : 4 ratings - Column R cf = sheetCF.GetConditionalFormattingAt(15); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("R2:R17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.RATINGS_4, 0d, 25d, 50d, 75d); // Icons : 5 ratings - Column S cf = sheetCF.GetConditionalFormattingAt(16); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("S2:S17", cf.GetFormattingRanges()[0].FormatAsString()); assertIconSetPercentages(cf, IconSet.RATINGS_5, 0d, 20d, 40d, 60d, 80d); // Custom Icon+Format - Column T cf = sheetCF.GetConditionalFormattingAt(17); Assert.AreEqual(1, cf.GetFormattingRanges().Length); Assert.AreEqual("T2:T17", cf.GetFormattingRanges()[0].FormatAsString()); // TODO Support IconSet + Other CFs with 2 rules // Assert.AreEqual(2, cf.NumberOfRules); // cr = cf.getRule(0); // assertIconSetPercentages(cr, IconSet.GYR_3_TRAFFIC_LIGHTS_BOX, 0d, 33d, 67d); // cr = cf.getRule(1); // Assert.AreEqual(ConditionType.FORMULA, cr.ConditionType); // Assert.AreEqual(ComparisonOperator.NO_COMPARISON, cr.ComparisonOperation); // // TODO Why aren't these two the same between formats? // if (cr instanceof HSSFConditionalFormattingRule) { // Assert.AreEqual("MOD(ROW($T1),2)=1", cr.Formula1); // } else { // Assert.AreEqual("MOD(ROW($T2),2)=1", cr.Formula1); // } // Assert.AreEqual(null, cr.Formula2); // Mixed icons - Column U // TODO Support EXT formattings wb.Close(); } private void assertDataBar(IConditionalFormatting cf, String color) { Assert.AreEqual(1, cf.NumberOfRules); IConditionalFormattingRule cr = cf.GetRule(0); assertDataBar(cr, color); } private void assertDataBar(IConditionalFormattingRule cr, String color) { Assert.AreEqual(ConditionType.DataBar, cr.ConditionType); Assert.AreEqual(ComparisonOperator.NoComparison, cr.ComparisonOperation); Assert.AreEqual(null, cr.Formula1); Assert.AreEqual(null, cr.Formula2); IDataBarFormatting databar = cr.DataBarFormatting; Assert.IsNotNull(databar); Assert.AreEqual(false, databar.IsIconOnly); Assert.AreEqual(true, databar.IsLeftToRight); Assert.AreEqual(0, databar.WidthMin); Assert.AreEqual(100, databar.WidthMax); AssertColour(color, databar.Color); IConditionalFormattingThreshold th; th = databar.MinThreshold; Assert.AreEqual(RangeType.MIN, th.RangeType); Assert.AreEqual(null, th.Value); Assert.AreEqual(null, th.Formula); th = databar.MaxThreshold; Assert.AreEqual(RangeType.MAX, th.RangeType); Assert.AreEqual(null, th.Value); Assert.AreEqual(null, th.Formula); } private void assertIconSetPercentages(IConditionalFormatting cf, IconSet iconset, params double[] vals) { Assert.AreEqual(1, cf.NumberOfRules); IConditionalFormattingRule cr = cf.GetRule(0); assertIconSetPercentages(cr, iconset, vals); } private void assertIconSetPercentages(IConditionalFormattingRule cr, IconSet iconset, params double[] vals) { Assert.AreEqual(ConditionType.IconSet, cr.ConditionType); Assert.AreEqual(ComparisonOperator.NoComparison, cr.ComparisonOperation); Assert.AreEqual(null, cr.Formula1); Assert.AreEqual(null, cr.Formula2); IIconMultiStateFormatting icon = cr.MultiStateFormatting; Assert.IsNotNull(icon); Assert.AreEqual(iconset, icon.IconSet); Assert.AreEqual(false, icon.IsIconOnly); Assert.AreEqual(false, icon.IsReversed); Assert.IsNotNull(icon.Thresholds); Assert.AreEqual(vals.Length, icon.Thresholds.Length); for (int i = 0; i < vals.Length; i++) { Double v = vals[i]; IConditionalFormattingThreshold th = icon.Thresholds[i] as IConditionalFormattingThreshold; Assert.AreEqual(RangeType.PERCENT, th.RangeType); Assert.AreEqual(v, th.Value); Assert.AreEqual(null, th.Formula); } } private void assertColorScale(IConditionalFormatting cf, params string[] colors) { Assert.AreEqual(1, cf.NumberOfRules); IConditionalFormattingRule cr = cf.GetRule(0); assertColorScale(cr, colors); } private void assertColorScale(IConditionalFormattingRule cr, params string[] colors) { Assert.AreEqual(ConditionType.ColorScale, cr.ConditionType); Assert.AreEqual(ComparisonOperator.NoComparison, cr.ComparisonOperation); Assert.AreEqual(null, cr.Formula1); Assert.AreEqual(null, cr.Formula2); // TODO Implement if (cr is HSSFConditionalFormattingRule) return; IColorScaleFormatting color = cr.ColorScaleFormatting; Assert.IsNotNull(color); Assert.IsNotNull(color.Colors); Assert.IsNotNull(color.Thresholds); Assert.AreEqual(colors.Length, color.NumControlPoints); Assert.AreEqual(colors.Length, color.Colors.Length); Assert.AreEqual(colors.Length, color.Thresholds.Length); // Thresholds should be Min / (evenly spaced) / Max int steps = 100 / (colors.Length-1); for (int i=0; i<colors.Length; i++) { IConditionalFormattingThreshold th = color.Thresholds[i]; if (i == 0) { Assert.AreEqual(RangeType.MIN, th.RangeType); } else if (i == colors.Length-1) { Assert.AreEqual(RangeType.MAX, th.RangeType); } else { Assert.AreEqual(RangeType.PERCENTILE, th.RangeType); Assert.AreEqual(steps*i, (int)th.Value.Value); } Assert.AreEqual(null, th.Formula); } // Colors should match for (int i=0; i<colors.Length; i++) { AssertColour(colors[i], color.Colors[i]); } } [Test] public void TestCreateFontFormatting() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Equal, "7"); IFontFormatting fontFmt = rule1.CreateFontFormatting(); Assert.IsFalse(fontFmt.IsItalic); Assert.IsFalse(fontFmt.IsBold); fontFmt.SetFontStyle(true, true); Assert.IsTrue(fontFmt.IsItalic); Assert.IsTrue(fontFmt.IsBold); Assert.AreEqual(-1, fontFmt.FontHeight); // not modified fontFmt.FontHeight = (/*setter*/200); Assert.AreEqual(200, fontFmt.FontHeight); fontFmt.FontHeight = (/*setter*/100); Assert.AreEqual(100, fontFmt.FontHeight); Assert.AreEqual(FontSuperScript.None, fontFmt.EscapementType); fontFmt.EscapementType = (/*setter*/FontSuperScript.Sub); Assert.AreEqual(FontSuperScript.Sub, fontFmt.EscapementType); fontFmt.EscapementType = (/*setter*/FontSuperScript.None); Assert.AreEqual(FontSuperScript.None, fontFmt.EscapementType); fontFmt.EscapementType = (/*setter*/FontSuperScript.Super); Assert.AreEqual(FontSuperScript.Super, fontFmt.EscapementType); Assert.AreEqual(FontUnderlineType.None, fontFmt.UnderlineType); fontFmt.UnderlineType = (/*setter*/FontUnderlineType.Single); Assert.AreEqual(FontUnderlineType.Single, fontFmt.UnderlineType); fontFmt.UnderlineType = (/*setter*/FontUnderlineType.None); Assert.AreEqual(FontUnderlineType.None, fontFmt.UnderlineType); fontFmt.UnderlineType = (/*setter*/FontUnderlineType.Double); Assert.AreEqual(FontUnderlineType.Double, fontFmt.UnderlineType); Assert.AreEqual(-1, fontFmt.FontColorIndex); fontFmt.FontColorIndex = (/*setter*/HSSFColor.Red.Index); Assert.AreEqual(HSSFColor.Red.Index, fontFmt.FontColorIndex); fontFmt.FontColorIndex = (/*setter*/HSSFColor.Automatic.Index); Assert.AreEqual(HSSFColor.Automatic.Index, fontFmt.FontColorIndex); fontFmt.FontColorIndex = (/*setter*/HSSFColor.Blue.Index); Assert.AreEqual(HSSFColor.Blue.Index, fontFmt.FontColorIndex); IConditionalFormattingRule[] cfRules = { rule1 }; CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, cfRules); // Verification IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); Assert.AreEqual(1, cf.NumberOfRules); IFontFormatting r1fp = cf.GetRule(0).FontFormatting; Assert.IsNotNull(r1fp); Assert.IsTrue(r1fp.IsItalic); Assert.IsTrue(r1fp.IsBold); Assert.AreEqual(FontSuperScript.Super, r1fp.EscapementType); Assert.AreEqual(FontUnderlineType.Double, r1fp.UnderlineType); Assert.AreEqual(HSSFColor.Blue.Index, r1fp.FontColorIndex); workbook.Close(); } [Test] public void TestCreatePatternFormatting() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Equal, "7"); IPatternFormatting patternFmt = rule1.CreatePatternFormatting(); Assert.AreEqual(0, patternFmt.FillBackgroundColor); patternFmt.FillBackgroundColor = (/*setter*/HSSFColor.Red.Index); Assert.AreEqual(HSSFColor.Red.Index, patternFmt.FillBackgroundColor); Assert.AreEqual(0, patternFmt.FillForegroundColor); patternFmt.FillForegroundColor = (/*setter*/HSSFColor.Blue.Index); Assert.AreEqual(HSSFColor.Blue.Index, patternFmt.FillForegroundColor); Assert.AreEqual(FillPattern.NoFill, patternFmt.FillPattern); patternFmt.FillPattern = FillPattern.SolidForeground; Assert.AreEqual(FillPattern.SolidForeground, patternFmt.FillPattern); patternFmt.FillPattern = FillPattern.NoFill; Assert.AreEqual(FillPattern.NoFill, patternFmt.FillPattern); if (this._testDataProvider.GetSpreadsheetVersion() == SpreadsheetVersion.EXCEL97) { patternFmt.FillPattern = FillPattern.Bricks; Assert.AreEqual(FillPattern.Bricks, patternFmt.FillPattern); } IConditionalFormattingRule[] cfRules = { rule1 }; CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, cfRules); // Verification IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); Assert.AreEqual(1, cf.NumberOfRules); IPatternFormatting r1fp = cf.GetRule(0).PatternFormatting; Assert.IsNotNull(r1fp); Assert.AreEqual(HSSFColor.Red.Index, r1fp.FillBackgroundColor); Assert.AreEqual(HSSFColor.Blue.Index, r1fp.FillForegroundColor); if (this._testDataProvider.GetSpreadsheetVersion() == SpreadsheetVersion.EXCEL97) { Assert.AreEqual(FillPattern.Bricks, r1fp.FillPattern); } workbook.Close(); } [Test] public void TestAllCreateBorderFormatting() { // Make sure it is possible to create a conditional formatting rule // with every type of Border Style IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Equal, "7"); IBorderFormatting borderFmt = rule1.CreateBorderFormatting(); foreach (BorderStyle border in BorderStyleEnum.Values()) { borderFmt.BorderTop = border; Assert.AreEqual(border, borderFmt.BorderTop); borderFmt.BorderBottom = border; Assert.AreEqual(border, borderFmt.BorderBottom); borderFmt.BorderLeft = border; Assert.AreEqual(border, borderFmt.BorderLeft); borderFmt.BorderRight = border; Assert.AreEqual(border, borderFmt.BorderRight); borderFmt.BorderDiagonal = border; Assert.AreEqual(border, borderFmt.BorderDiagonal); } workbook.Close(); } [Test] public void TestCreateBorderFormatting() { IWorkbook workbook = _testDataProvider.CreateWorkbook(); ISheet sheet = workbook.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(ComparisonOperator.Equal, "7"); IBorderFormatting borderFmt = rule1.CreateBorderFormatting(); Assert.AreEqual(BorderStyle.None, borderFmt.BorderBottom); borderFmt.BorderBottom = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderBottom); borderFmt.BorderBottom = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderBottom); borderFmt.BorderBottom = (/*setter*/BorderStyle.Thick); Assert.AreEqual(BorderStyle.Thick, borderFmt.BorderBottom); Assert.AreEqual(BorderStyle.None, borderFmt.BorderTop); borderFmt.BorderTop = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderTop); borderFmt.BorderTop = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderTop); borderFmt.BorderTop = (/*setter*/BorderStyle.Thick); Assert.AreEqual(BorderStyle.Thick, borderFmt.BorderTop); Assert.AreEqual(BorderStyle.None, borderFmt.BorderLeft); borderFmt.BorderLeft = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderLeft); borderFmt.BorderLeft = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderLeft); borderFmt.BorderLeft = (/*setter*/BorderStyle.Thin); Assert.AreEqual(BorderStyle.Thin, borderFmt.BorderLeft); Assert.AreEqual(BorderStyle.None, borderFmt.BorderRight); borderFmt.BorderRight = (/*setter*/BorderStyle.Dotted); Assert.AreEqual(BorderStyle.Dotted, borderFmt.BorderRight); borderFmt.BorderRight = (/*setter*/BorderStyle.None); Assert.AreEqual(BorderStyle.None, borderFmt.BorderRight); borderFmt.BorderRight = (/*setter*/BorderStyle.Hair); Assert.AreEqual(BorderStyle.Hair, borderFmt.BorderRight); IConditionalFormattingRule[] cfRules = { rule1 }; CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, cfRules); // Verification IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.IsNotNull(cf); Assert.AreEqual(1, cf.NumberOfRules); IBorderFormatting r1fp = cf.GetRule(0).BorderFormatting; Assert.IsNotNull(r1fp); Assert.AreEqual(BorderStyle.Thick, r1fp.BorderBottom); Assert.AreEqual(BorderStyle.Thick, r1fp.BorderTop); Assert.AreEqual(BorderStyle.Thin, r1fp.BorderLeft); Assert.AreEqual(BorderStyle.Hair, r1fp.BorderRight); workbook.Close(); } [Test] public void TestCreateIconFormatting() { IWorkbook wb1 = _testDataProvider.CreateWorkbook(); ISheet sheet = wb1.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(IconSet.GYRB_4_TRAFFIC_LIGHTS); IIconMultiStateFormatting iconFmt = rule1.MultiStateFormatting; Assert.AreEqual(IconSet.GYRB_4_TRAFFIC_LIGHTS, iconFmt.IconSet); Assert.AreEqual(4, iconFmt.Thresholds.Length); Assert.AreEqual(false, iconFmt.IsIconOnly); Assert.AreEqual(false, iconFmt.IsReversed); iconFmt.IsIconOnly = (true); iconFmt.Thresholds[0].RangeType = RangeType.MIN; iconFmt.Thresholds[1].RangeType = RangeType.NUMBER; iconFmt.Thresholds[1].Value = (10d); iconFmt.Thresholds[2].RangeType = RangeType.PERCENT; iconFmt.Thresholds[2].Value = (75d); iconFmt.Thresholds[3].RangeType = RangeType.MAX; CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, rule1); // Save, re-load and re-check IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1); wb1.Close(); sheet = wb2.GetSheetAt(0); sheetCF = sheet.SheetConditionalFormatting; Assert.AreEqual(1, sheetCF.NumConditionalFormattings); IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual(1, cf.NumberOfRules); rule1 = cf.GetRule(0); Assert.AreEqual(ConditionType.IconSet, rule1.ConditionType); iconFmt = rule1.MultiStateFormatting; Assert.AreEqual(IconSet.GYRB_4_TRAFFIC_LIGHTS, iconFmt.IconSet); Assert.AreEqual(4, iconFmt.Thresholds.Length); Assert.AreEqual(true, iconFmt.IsIconOnly); Assert.AreEqual(false, iconFmt.IsReversed); Assert.AreEqual(RangeType.MIN, iconFmt.Thresholds[0].RangeType); Assert.AreEqual(RangeType.NUMBER, iconFmt.Thresholds[1].RangeType); Assert.AreEqual(RangeType.PERCENT, iconFmt.Thresholds[2].RangeType); Assert.AreEqual(RangeType.MAX, iconFmt.Thresholds[3].RangeType); Assert.AreEqual(null, iconFmt.Thresholds[0].Value); Assert.AreEqual(10d, iconFmt.Thresholds[1].Value, 0); Assert.AreEqual(75d, iconFmt.Thresholds[2].Value, 0); Assert.AreEqual(null, iconFmt.Thresholds[3].Value); wb2.Close(); } [Test] public void TestCreateColorScaleFormatting() { IWorkbook wb1 = _testDataProvider.CreateWorkbook(); ISheet sheet = wb1.CreateSheet(); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingColorScaleRule(); IColorScaleFormatting clrFmt = rule1.ColorScaleFormatting; Assert.AreEqual(3, clrFmt.NumControlPoints); Assert.AreEqual(3, clrFmt.Colors.Length); Assert.AreEqual(3, clrFmt.Thresholds.Length); clrFmt.Thresholds[0].RangeType = (RangeType.MIN); clrFmt.Thresholds[1].RangeType = (RangeType.NUMBER); clrFmt.Thresholds[1].Value = (10d); clrFmt.Thresholds[2].RangeType = (RangeType.MAX); CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, rule1); // Save, re-load and re-check IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1); wb1.Close(); sheet = wb2.GetSheetAt(0); sheetCF = sheet.SheetConditionalFormatting; Assert.AreEqual(1, sheetCF.NumConditionalFormattings); IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual(1, cf.NumberOfRules); rule1 = cf.GetRule(0); clrFmt = rule1.ColorScaleFormatting; Assert.AreEqual(ConditionType.ColorScale, rule1.ConditionType); Assert.AreEqual(3, clrFmt.NumControlPoints); Assert.AreEqual(3, clrFmt.Colors.Length); Assert.AreEqual(3, clrFmt.Thresholds.Length); Assert.AreEqual(RangeType.MIN, clrFmt.Thresholds[0].RangeType); Assert.AreEqual(RangeType.NUMBER, clrFmt.Thresholds[1].RangeType); Assert.AreEqual(RangeType.MAX, clrFmt.Thresholds[2].RangeType); Assert.AreEqual(null, clrFmt.Thresholds[0].Value); Assert.AreEqual(10d, clrFmt.Thresholds[1].Value, 0); Assert.AreEqual(null, clrFmt.Thresholds[2].Value); wb2.Close(); } [Test] public void TestCreateDataBarFormatting() { IWorkbook wb1 = _testDataProvider.CreateWorkbook(); ISheet sheet = wb1.CreateSheet(); String colorHex = "FFFFEB84"; ExtendedColor color = wb1.GetCreationHelper().CreateExtendedColor(); color.ARGBHex = (colorHex); ISheetConditionalFormatting sheetCF = sheet.SheetConditionalFormatting; IConditionalFormattingRule rule1 = sheetCF.CreateConditionalFormattingRule(color); IDataBarFormatting dbFmt = rule1.DataBarFormatting; Assert.AreEqual(false, dbFmt.IsIconOnly); Assert.AreEqual(true, dbFmt.IsLeftToRight); Assert.AreEqual(0, dbFmt.WidthMin); Assert.AreEqual(100, dbFmt.WidthMax); AssertColour(colorHex, dbFmt.Color); dbFmt.MinThreshold.RangeType = (RangeType.MIN); dbFmt.MaxThreshold.RangeType = (RangeType.MAX); CellRangeAddress[] regions = { CellRangeAddress.ValueOf("A1:A5") }; sheetCF.AddConditionalFormatting(regions, rule1); // Save, re-load and re-check IWorkbook wb2 = _testDataProvider.WriteOutAndReadBack(wb1); wb1.Close(); sheet = wb2.GetSheetAt(0); sheetCF = sheet.SheetConditionalFormatting; Assert.AreEqual(1, sheetCF.NumConditionalFormattings); IConditionalFormatting cf = sheetCF.GetConditionalFormattingAt(0); Assert.AreEqual(1, cf.NumberOfRules); rule1 = cf.GetRule(0); dbFmt = rule1.DataBarFormatting; Assert.AreEqual(ConditionType.DataBar, rule1.ConditionType); Assert.AreEqual(false, dbFmt.IsIconOnly); Assert.AreEqual(true, dbFmt.IsLeftToRight); Assert.AreEqual(0, dbFmt.WidthMin); Assert.AreEqual(100, dbFmt.WidthMax); AssertColour(colorHex, dbFmt.Color); Assert.AreEqual(RangeType.MIN, dbFmt.MinThreshold.RangeType); Assert.AreEqual(RangeType.MAX, dbFmt.MaxThreshold.RangeType); Assert.AreEqual(null, dbFmt.MinThreshold.Value); Assert.AreEqual(null, dbFmt.MaxThreshold.Value); wb2.Close(); } [Test] public void TestBug55380() { IWorkbook wb = _testDataProvider.CreateWorkbook(); ISheet sheet = wb.CreateSheet(); CellRangeAddress[] ranges = new CellRangeAddress[] { CellRangeAddress.ValueOf("C9:D30"), CellRangeAddress.ValueOf("C7:C31") }; IConditionalFormattingRule rule = sheet.SheetConditionalFormatting.CreateConditionalFormattingRule("$A$1>0"); sheet.SheetConditionalFormatting.AddConditionalFormatting(ranges, rule); wb.Close(); } } }
using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace VRS.UI.Controls { [Flags] public enum TextStyle { Text3D = 0, Shadow = 1, } /// <summary> /// Label control. /// </summary> public class WLabel : System.Windows.Forms.UserControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; protected ViewStyle m_ViewStyle = null; protected bool m_UseStaticViewStyle = false; private HorizontalAlignment m_TextAlignment = HorizontalAlignment.Center; private string m_Text = ""; private Color m_BorderColor = Color.DarkGray; private Color m_BorderHotColor = Color.Green; /// <summary> /// Default constructor. /// </summary> public WLabel() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); // TODO: Add any initialization after the InitForm call SetStyle(ControlStyles.ResizeRedraw,true); SetStyle(ControlStyles.DoubleBuffer,true); SetStyle(ControlStyles.AllPaintingInWmPaint,true); SetStyle(ControlStyles.Selectable,false); m_ViewStyle = new ViewStyle(); ViewStyle.staticViewStyle.StyleChanged += new ViewStyleChangedEventHandler(this.OnStaticViewStyleChanged); } #region function Dispose /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #endregion #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { // // WLabel // this.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.Name = "WLabel"; this.Size = new System.Drawing.Size(150, 24); } #endregion #region Events handling #region function OnViewStyleChanged private void OnStaticViewStyleChanged(object sender,ViewStyle_EventArgs e) { if(m_UseStaticViewStyle){ m_ViewStyle.CopyFrom(ViewStyle.staticViewStyle); } this.Invalidate(); } #endregion #endregion #region function OnPaint protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); StringFormat format = new StringFormat(); format.LineAlignment = StringAlignment.Center; if(m_TextAlignment == HorizontalAlignment.Left){ format.Alignment = StringAlignment.Near; } if(m_TextAlignment == HorizontalAlignment.Center){ format.Alignment = StringAlignment.Center; } if(m_TextAlignment == HorizontalAlignment.Right){ format.Alignment = StringAlignment.Far; } Rectangle txtRect = this.ClientRectangle; // if(m_Shadow){ // Draw Shadow Rectangle sRect = new Rectangle(new Point(txtRect.X+2,txtRect.Y+2),txtRect.Size); e.Graphics.DrawString(this.Text,this.Font,new SolidBrush(m_ViewStyle.TextShadowColor),sRect,format); // } // if(m_Effect3D){ // Draw 3d effect Rectangle dRect = new Rectangle(new Point(txtRect.X+1,txtRect.Y+1),txtRect.Size); e.Graphics.DrawString(this.Text,this.Font,new SolidBrush(m_ViewStyle.Text3DColor),dRect,format); // } // Draw normal text e.Graphics.DrawString(m_Text,this.Font,new SolidBrush(m_ViewStyle.TextColor),txtRect,format); } #endregion #region function IsMouseInButtonRect private bool IsMouseInControl() { Rectangle rectButton = this.ClientRectangle; Point mPos = Control.MousePosition; if(rectButton.Contains(this.PointToClient(mPos))){ return true; } else{ return false; } } #endregion #region Properties Implementation [ TypeConverter(typeof(ExpandableObjectConverter)), Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Content), Category("View style") ] public virtual ViewStyle ViewStyle { get{ return m_ViewStyle; } } [ Category("View style") ] public virtual bool UseStaticViewStyle { get{ return m_UseStaticViewStyle; } set { m_UseStaticViewStyle = value; if(value){ ViewStyle.staticViewStyle.CopyTo(m_ViewStyle); m_ViewStyle.ReadOnly = true; } else{ m_ViewStyle.ReadOnly = false; } } } /// <summary> /// /// </summary> [ Browsable(true), DesignerSerializationVisibility(DesignerSerializationVisibility.Visible) ] public override string Text { get{ return m_Text; } set{ m_Text = value; this.Invalidate(); } } public HorizontalAlignment TextAlign { get{ return m_TextAlignment; } set{ m_TextAlignment = value; this.Invalidate(); } } #endregion } }
// Copyright (c) 2015 Alachisoft // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using Alachisoft.NCache.Parser; namespace Alachisoft.NCache.Caching.Queries.Filters { public class IsInListPredicate : Predicate, IComparable { private IFunctor functor; private ArrayList members; public IsInListPredicate() { members = new ArrayList(); } public IFunctor Functor { set { functor = value; } } public ArrayList Values { get { return members; } } public void Append(object item) { object obj = ((IGenerator)item).Evaluate(); if (members.Contains(obj)) return; members.Add(obj); members.Sort(); } public override bool ApplyPredicate(object o) { object lhs = functor.Evaluate(o); if (Inverse) return !members.Contains(lhs); return members.Contains(lhs); } internal override void ExecuteInternal(QueryContext queryContext, ref SortedList list) { AttributeIndex index = queryContext.Index; IIndexStore store = ((MemberFunction)functor).GetStore(index); ArrayList keyList = new ArrayList(); if (store != null) { members = queryContext.AttributeValues[((MemberFunction)functor).MemberName] as ArrayList; if (members == null) { if (queryContext.AttributeValues.Count > 0) { members = new ArrayList(); members.Add(queryContext.AttributeValues[((MemberFunction)functor).MemberName]); } else { throw new Exception("Value(s) not specified for indexed attribute " + ((MemberFunction)functor).MemberName + "."); } } if (!Inverse) { for (int i = 0; i < members.Count; i++) { ArrayList temp = store.GetData(members[i], ComparisonType.EQUALS); if (temp != null) if (temp.Count > 0) keyList.AddRange(temp); } } else { ArrayList temp = store.GetData(members[0], ComparisonType.NOT_EQUALS); if (temp != null) { if (temp.Count > 0) { for (int i = 1; i < members.Count; i++) { ArrayList extras = store.GetData(members[i], ComparisonType.EQUALS); if (extras != null) { IEnumerator ie = extras.GetEnumerator(); if (ie != null) { while (ie.MoveNext()) { if (temp.Contains(ie.Current)) temp.Remove(ie.Current); } } } } keyList.AddRange(temp); } } } if (keyList != null) list.Add(keyList.Count, keyList); } else { throw new AttributeIndexNotDefined("Index is not defined for attribute '" + ((MemberFunction)functor).MemberName + "'"); } } internal override void Execute(QueryContext queryContext, Predicate nextPredicate) { AttributeIndex index = queryContext.Index; IIndexStore store = ((MemberFunction)functor).GetStore(index); if (store != null) { members = queryContext.AttributeValues[((MemberFunction)functor).MemberName] as ArrayList; if (members == null) { if (queryContext.AttributeValues.Count > 0) { members = new ArrayList(); members.Add(queryContext.AttributeValues[((MemberFunction)functor).MemberName]); } else { throw new Exception("Value(s) not specified for indexed attribute " + ((MemberFunction)functor).MemberName + "."); } } ArrayList keyList = new ArrayList(); if (!Inverse) { ArrayList distinctMembers = new ArrayList(); for (int i = 0; i < members.Count; i++) { if (!distinctMembers.Contains(members[i])) { distinctMembers.Add(members[i]); ArrayList temp = store.GetData(members[i], ComparisonType.EQUALS); if (temp != null) if (temp.Count > 0) keyList.AddRange(temp); } } } else { ArrayList distinctMembers = new ArrayList(); ArrayList temp = store.GetData(members[0], ComparisonType.NOT_EQUALS); if (temp != null) { if (temp.Count > 0) { for (int i = 0; i < members.Count; i++) { if (!distinctMembers.Contains(members[i])) { distinctMembers.Add(members[i]); ArrayList extras = store.GetData(members[i], ComparisonType.EQUALS); if (extras != null) { IEnumerator ie = extras.GetEnumerator(); if (ie != null) { while (ie.MoveNext()) { if (temp.Contains(ie.Current)) temp.Remove(ie.Current); } } } } keyList = temp; } } } } if (keyList != null && keyList.Count > 0) { IEnumerator keyListEnum = keyList.GetEnumerator(); if (queryContext.PopulateTree) { queryContext.Tree.RightList = keyList; queryContext.PopulateTree = false; } else { while (keyListEnum.MoveNext()) { if (queryContext.Tree.LeftList.Contains(keyListEnum.Current)) queryContext.Tree.Shift(keyListEnum.Current); } } } } else { throw new AttributeIndexNotDefined("Index is not defined for attribute '" + ((MemberFunction)functor).MemberName + "'"); } } public override string ToString() { string text = Inverse ? "is not in (" : "is in ("; for (int i = 0; i < members.Count; i++) { if (i > 0) text += ", "; text += members[i].ToString(); } text += ")"; return text; } #region IComparable Members public int CompareTo(object obj) { if (obj is IsInListPredicate) { IsInListPredicate other = (IsInListPredicate)obj; if (Inverse == other.Inverse) { if (members.Count == other.members.Count) { for (int i = 0; i < members.Count; i++) if (members[i] != other.members[i]) return -1; return 0; } } } return -1; } #endregion } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Net; using System.Net.Security; using System.Reflection; using System.Text; using System.Web; using log4net; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse.StructuredData; namespace OpenSim.Framework { /// <summary> /// Miscellaneous static methods and extension methods related to the web /// </summary> public static class WebUtil { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Send LLSD to an HTTP client in application/llsd+json form /// </summary> /// <param name="response">HTTP response to send the data in</param> /// <param name="body">LLSD to send to the client</param> public static void SendJSONResponse(OSHttpResponse response, OSDMap body) { byte[] responseData = Encoding.UTF8.GetBytes(OSDParser.SerializeJsonString(body)); response.ContentEncoding = Encoding.UTF8; response.ContentLength = responseData.Length; response.ContentType = "application/llsd+json"; response.Body.Write(responseData, 0, responseData.Length); } /// <summary> /// Send LLSD to an HTTP client in application/llsd+xml form /// </summary> /// <param name="response">HTTP response to send the data in</param> /// <param name="body">LLSD to send to the client</param> public static void SendXMLResponse(OSHttpResponse response, OSDMap body) { byte[] responseData = OSDParser.SerializeLLSDXmlBytes(body); response.ContentEncoding = Encoding.UTF8; response.ContentLength = responseData.Length; response.ContentType = "application/llsd+xml"; response.Body.Write(responseData, 0, responseData.Length); } /// <summary> /// Make a GET or GET-like request to a web service that returns LLSD /// or JSON data /// </summary> public static OSDMap ServiceRequest(string url, string httpVerb) { string errorMessage; try { HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = httpVerb; using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { try { string responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) return (OSDMap)responseOSD; else errorMessage = "Response format was invalid."; } catch { errorMessage = "Failed to parse the response."; } } } } catch (Exception ex) { m_log.Warn(httpVerb + " on URL " + url + " failed: " + ex.Message); errorMessage = ex.Message; } return new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } }; } /// <summary> /// POST URL-encoded form data to a web service that returns LLSD or /// JSON data /// </summary> public static OSDMap PostToService(string url, NameValueCollection data) { string errorMessage; try { string queryString = BuildQueryString(data); byte[] requestData = System.Text.Encoding.UTF8.GetBytes(queryString); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url); request.Method = "POST"; request.ContentLength = requestData.Length; request.ContentType = "application/x-www-form-urlencoded"; using (Stream requestStream = request.GetRequestStream()) requestStream.Write(requestData, 0, requestData.Length); using (WebResponse response = request.GetResponse()) { using (Stream responseStream = response.GetResponseStream()) { string responseStr = null; try { responseStr = responseStream.GetStreamString(); OSD responseOSD = OSDParser.Deserialize(responseStr); if (responseOSD.Type == OSDType.Map) return (OSDMap)responseOSD; else errorMessage = "Response format was invalid."; } catch (Exception ex) { if (!String.IsNullOrEmpty(responseStr)) errorMessage = "Failed to parse the response:\n" + responseStr; else errorMessage = "Failed to retrieve the response: " + ex.Message; } } } } catch (Exception ex) { m_log.Warn("POST to URL " + url + " failed: " + ex.Message); errorMessage = ex.Message; } return new OSDMap { { "Message", OSD.FromString("Service request failed. " + errorMessage) } }; } #region Uri /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri</param> /// <returns>The combined Uri</returns> /// <remarks>This is similar to the Uri constructor that takes a base /// Uri and the relative path, except this method can append a relative /// path fragment on to an existing relative path</remarks> public static Uri Combine(this Uri uri, string fragment) { string fragment1 = uri.Fragment; string fragment2 = fragment; if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Combines a Uri that can contain both a base Uri and relative path /// with a second relative path fragment. If the fragment is absolute, /// it will be returned without modification /// </summary> /// <param name="uri">Starting (base) Uri</param> /// <param name="fragment">Relative path fragment to append to the end /// of the Uri, or an absolute Uri to return unmodified</param> /// <returns>The combined Uri</returns> public static Uri Combine(this Uri uri, Uri fragment) { if (fragment.IsAbsoluteUri) return fragment; string fragment1 = uri.Fragment; string fragment2 = fragment.ToString(); if (!fragment1.EndsWith("/")) fragment1 = fragment1 + '/'; if (fragment2.StartsWith("/")) fragment2 = fragment2.Substring(1); return new Uri(uri, fragment1 + fragment2); } /// <summary> /// Appends a query string to a Uri that may or may not have existing /// query parameters /// </summary> /// <param name="uri">Uri to append the query to</param> /// <param name="query">Query string to append. Can either start with ? /// or just containg key/value pairs</param> /// <returns>String representation of the Uri with the query string /// appended</returns> public static string AppendQuery(this Uri uri, string query) { if (String.IsNullOrEmpty(query)) return uri.ToString(); if (query[0] == '?' || query[0] == '&') query = query.Substring(1); string uriStr = uri.ToString(); if (uriStr.Contains("?")) return uriStr + '&' + query; else return uriStr + '?' + query; } #endregion Uri #region NameValueCollection /// <summary> /// Convert a NameValueCollection into a query string. This is the /// inverse of HttpUtility.ParseQueryString() /// </summary> /// <param name="parameters">Collection of key/value pairs to convert</param> /// <returns>A query string with URL-escaped values</returns> public static string BuildQueryString(NameValueCollection parameters) { List<string> items = new List<string>(parameters.Count); foreach (string key in parameters.Keys) { string[] values = parameters.GetValues(key); if (values != null) { foreach (string value in values) items.Add(String.Concat(key, "=", HttpUtility.UrlEncode(value ?? String.Empty))); } } return String.Join("&", items.ToArray()); } /// <summary> /// /// </summary> /// <param name="collection"></param> /// <param name="key"></param> /// <returns></returns> public static string GetOne(this NameValueCollection collection, string key) { string[] values = collection.GetValues(key); if (values != null && values.Length > 0) return values[0]; return null; } #endregion NameValueCollection #region Stream /// <summary> /// Copies the contents of one stream to another, starting at the /// current position of each stream /// </summary> /// <param name="copyFrom">The stream to copy from, at the position /// where copying should begin</param> /// <param name="copyTo">The stream to copy to, at the position where /// bytes should be written</param> /// <param name="maximumBytesToCopy">The maximum bytes to copy</param> /// <returns>The total number of bytes copied</returns> /// <remarks> /// Copying begins at the streams' current positions. The positions are /// NOT reset after copying is complete. /// </remarks> public static int CopyTo(this Stream copyFrom, Stream copyTo, int maximumBytesToCopy) { byte[] buffer = new byte[4096]; int readBytes; int totalCopiedBytes = 0; while ((readBytes = copyFrom.Read(buffer, 0, Math.Min(4096, maximumBytesToCopy))) > 0) { int writeBytes = Math.Min(maximumBytesToCopy, readBytes); copyTo.Write(buffer, 0, writeBytes); totalCopiedBytes += writeBytes; maximumBytesToCopy -= writeBytes; } return totalCopiedBytes; } /// <summary> /// Converts an entire stream to a string, regardless of current stream /// position /// </summary> /// <param name="stream">The stream to convert to a string</param> /// <returns></returns> /// <remarks>When this method is done, the stream position will be /// reset to its previous position before this method was called</remarks> public static string GetStreamString(this Stream stream) { string value = null; if (stream != null && stream.CanRead) { long rewindPos = -1; if (stream.CanSeek) { rewindPos = stream.Position; stream.Seek(0, SeekOrigin.Begin); } StreamReader reader = new StreamReader(stream); value = reader.ReadToEnd(); if (rewindPos >= 0) stream.Seek(rewindPos, SeekOrigin.Begin); } return value; } #endregion Stream } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using QuantConnect.Data; using QuantConnect.Data.UniverseSelection; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// In this algortihm we show how you can easily use the universe selection feature to fetch symbols /// to be traded using the AddUniverse method. This method accepts a function that will return the /// desired current set of symbols. Return Universe.Unchanged if no universe changes should be made /// </summary> /// <meta name="tag" content="using data" /> /// <meta name="tag" content="universes" /> /// <meta name="tag" content="custom universes" /> public class DropboxUniverseSelectionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { // the changes from the previous universe selection private SecurityChanges _changes = SecurityChanges.None; // only used in backtest for caching the file results private readonly Dictionary<DateTime, List<string>> _backtestSymbolsPerDay = new Dictionary<DateTime, List<string>>(); /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> /// <seealso cref="QCAlgorithm.SetStartDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetEndDate(System.DateTime)"/> /// <seealso cref="QCAlgorithm.SetCash(decimal)"/> public override void Initialize() { // this sets the resolution for data subscriptions added by our universe UniverseSettings.Resolution = Resolution.Daily; // Order margin value has to have a minimum of 0.5% of Portfolio value, allows filtering out small trades and reduce fees. // Commented so regression algorithm is more sensitive //Settings.MinimumOrderMarginPortfolioPercentage = 0.005m; // set our start and end for backtest mode SetStartDate(2017, 07, 04); SetEndDate(2018, 07, 04); // define a new custom universe that will trigger each day at midnight AddUniverse("my-dropbox-universe", Resolution.Daily, dateTime => { // handle live mode file format if (LiveMode) { // fetch the file from dropbox var file = Download(@"https://www.dropbox.com/s/2l73mu97gcehmh7/daily-stock-picker-live.csv?dl=1"); // if we have a file for today, break apart by commas and return symbols if (file.Length > 0) return file.ToCsv(); // no symbol today, leave universe unchanged return Universe.Unchanged; } // backtest - first cache the entire file if (_backtestSymbolsPerDay.Count == 0) { // No need for headers for authorization with dropbox, these two lines are for example purposes var byteKey = Encoding.ASCII.GetBytes($"UserName:Password"); // The headers must be passed to the Download method as list of key/value pair. var headers = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Authorization", $"Basic ({Convert.ToBase64String(byteKey)})") }; var file = Download(@"https://www.dropbox.com/s/ae1couew5ir3z9y/daily-stock-picker-backtest.csv?dl=1", headers); // split the file into lines and add to our cache foreach (var line in file.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)) { var csv = line.ToCsv(); var date = DateTime.ParseExact(csv[0], "yyyyMMdd", null); var symbols = csv.Skip(1).ToList(); _backtestSymbolsPerDay[date] = symbols; } } // if we have symbols for this date return them, else specify Universe.Unchanged List<string> result; if (_backtestSymbolsPerDay.TryGetValue(dateTime.Date, out result)) { return result; } return Universe.Unchanged; }); } /// <summary> /// Event - v3.0 DATA EVENT HANDLER: (Pattern) Basic template for user to override for receiving all subscription data in a single event /// </summary> /// <code> /// TradeBars bars = slice.Bars; /// Ticks ticks = slice.Ticks; /// TradeBar spy = slice["SPY"]; /// List{Tick} aaplTicks = slice["AAPL"] /// Quandl oil = slice["OIL"] /// dynamic anySymbol = slice[symbol]; /// DataDictionary{Quandl} allQuandlData = slice.Get{Quand} /// Quandl oil = slice.Get{Quandl}("OIL") /// </code> /// <param name="slice">The current slice of data keyed by symbol string</param> public override void OnData(Slice slice) { if (slice.Bars.Count == 0) return; if (_changes == SecurityChanges.None) return; // start fresh Liquidate(); var percentage = 1m/slice.Bars.Count; foreach (var tradeBar in slice.Bars.Values) { SetHoldings(tradeBar.Symbol, percentage); } // reset changes _changes = SecurityChanges.None; } /// <summary> /// Event fired each time the we add/remove securities from the data feed /// </summary> /// <param name="changes"></param> public override void OnSecuritiesChanged(SecurityChanges changes) { // each time our securities change we'll be notified here _changes = changes; } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp, Language.Python }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "5059"}, {"Average Win", "0.08%"}, {"Average Loss", "-0.08%"}, {"Compounding Annual Return", "16.153%"}, {"Drawdown", "10.300%"}, {"Expectancy", "0.081"}, {"Net Profit", "16.153%"}, {"Sharpe Ratio", "1.17"}, {"Probabilistic Sharpe Ratio", "54.048%"}, {"Loss Rate", "45%"}, {"Win Rate", "55%"}, {"Profit-Loss Ratio", "0.97"}, {"Alpha", "0.147"}, {"Beta", "-0.068"}, {"Annual Standard Deviation", "0.119"}, {"Annual Variance", "0.014"}, {"Information Ratio", "0.11"}, {"Tracking Error", "0.169"}, {"Treynor Ratio", "-2.057"}, {"Total Fees", "$5869.25"}, {"Estimated Strategy Capacity", "$320000.00"}, {"Lowest Capacity Asset", "BNO UN3IMQ2JU1YD"}, {"Fitness Score", "0.711"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "1.389"}, {"Return Over Maximum Drawdown", "1.564"}, {"Portfolio Turnover", "1.271"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "5f08ae4997156d48171559e452dda9d3"} }; } }
using XenAdmin.Controls; namespace XenAdmin.Wizards.HAWizard_Pages { partial class AssignPriorities { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AssignPriorities)); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.pictureBoxStatus = new System.Windows.Forms.PictureBox(); this.labelHaStatus = new System.Windows.Forms.Label(); this.labelProtectionLevel = new System.Windows.Forms.Label(); this.m_dropDownButtonRestartPriority = new XenAdmin.Controls.DropDownButton(); this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components); this.labelStartOrder = new System.Windows.Forms.Label(); this.nudOrder = new System.Windows.Forms.NumericUpDown(); this.labelStartDelay = new System.Windows.Forms.Label(); this.nudStartDelay = new System.Windows.Forms.NumericUpDown(); this.labelStartDelayUnits = new System.Windows.Forms.Label(); this.linkLabelTellMeMore = new System.Windows.Forms.LinkLabel(); this.haNtolIndicator = new XenAdmin.Controls.HaNtolIndicator(); this.dataGridViewVms = new XenAdmin.Controls.DataGridViewEx.DataGridViewEx(); this.colImage = new System.Windows.Forms.DataGridViewImageColumn(); this.colVm = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colRestartPriority = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colStartOrder = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colDelay = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.colAgile = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.button1 = new System.Windows.Forms.Button(); this.bgWorker = new System.ComponentModel.BackgroundWorker(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudOrder)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudStartDelay)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewVms)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // resources.ApplyResources(this.tableLayoutPanel1, "tableLayoutPanel1"); this.tableLayoutPanel1.Controls.Add(this.pictureBoxStatus, 0, 0); this.tableLayoutPanel1.Controls.Add(this.labelHaStatus, 1, 0); this.tableLayoutPanel1.Controls.Add(this.labelProtectionLevel, 0, 2); this.tableLayoutPanel1.Controls.Add(this.m_dropDownButtonRestartPriority, 2, 2); this.tableLayoutPanel1.Controls.Add(this.labelStartOrder, 0, 3); this.tableLayoutPanel1.Controls.Add(this.nudOrder, 3, 3); this.tableLayoutPanel1.Controls.Add(this.labelStartDelay, 0, 4); this.tableLayoutPanel1.Controls.Add(this.nudStartDelay, 3, 4); this.tableLayoutPanel1.Controls.Add(this.labelStartDelayUnits, 4, 4); this.tableLayoutPanel1.Controls.Add(this.linkLabelTellMeMore, 0, 5); this.tableLayoutPanel1.Controls.Add(this.haNtolIndicator, 5, 2); this.tableLayoutPanel1.Controls.Add(this.dataGridViewVms, 0, 1); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; // // pictureBoxStatus // this.pictureBoxStatus.Image = global::XenAdmin.Properties.Resources._000_Tick_h32bit_16; resources.ApplyResources(this.pictureBoxStatus, "pictureBoxStatus"); this.pictureBoxStatus.Name = "pictureBoxStatus"; this.pictureBoxStatus.TabStop = false; // // labelHaStatus // resources.ApplyResources(this.labelHaStatus, "labelHaStatus"); this.tableLayoutPanel1.SetColumnSpan(this.labelHaStatus, 5); this.labelHaStatus.Name = "labelHaStatus"; // // labelProtectionLevel // resources.ApplyResources(this.labelProtectionLevel, "labelProtectionLevel"); this.tableLayoutPanel1.SetColumnSpan(this.labelProtectionLevel, 2); this.labelProtectionLevel.Name = "labelProtectionLevel"; // // m_dropDownButtonRestartPriority // this.tableLayoutPanel1.SetColumnSpan(this.m_dropDownButtonRestartPriority, 2); this.m_dropDownButtonRestartPriority.ContextMenuStrip = this.contextMenuStrip; resources.ApplyResources(this.m_dropDownButtonRestartPriority, "m_dropDownButtonRestartPriority"); this.m_dropDownButtonRestartPriority.Name = "m_dropDownButtonRestartPriority"; this.m_dropDownButtonRestartPriority.UseVisualStyleBackColor = true; this.m_dropDownButtonRestartPriority.Click += new System.EventHandler(this.m_dropDownButtonRestartPriority_Click); // // contextMenuStrip // this.contextMenuStrip.Name = "contextMenuStrip"; resources.ApplyResources(this.contextMenuStrip, "contextMenuStrip"); // // labelStartOrder // resources.ApplyResources(this.labelStartOrder, "labelStartOrder"); this.tableLayoutPanel1.SetColumnSpan(this.labelStartOrder, 3); this.labelStartOrder.Name = "labelStartOrder"; // // nudOrder // resources.ApplyResources(this.nudOrder, "nudOrder"); this.nudOrder.Name = "nudOrder"; this.nudOrder.ValueChanged += new System.EventHandler(this.nudOrder_ValueChanged); // // labelStartDelay // resources.ApplyResources(this.labelStartDelay, "labelStartDelay"); this.tableLayoutPanel1.SetColumnSpan(this.labelStartDelay, 3); this.labelStartDelay.Name = "labelStartDelay"; // // nudStartDelay // resources.ApplyResources(this.nudStartDelay, "nudStartDelay"); this.nudStartDelay.Name = "nudStartDelay"; this.nudStartDelay.ValueChanged += new System.EventHandler(this.nudStartDelay_ValueChanged); // // labelStartDelayUnits // resources.ApplyResources(this.labelStartDelayUnits, "labelStartDelayUnits"); this.labelStartDelayUnits.Name = "labelStartDelayUnits"; // // linkLabelTellMeMore // resources.ApplyResources(this.linkLabelTellMeMore, "linkLabelTellMeMore"); this.tableLayoutPanel1.SetColumnSpan(this.linkLabelTellMeMore, 5); this.linkLabelTellMeMore.Name = "linkLabelTellMeMore"; this.linkLabelTellMeMore.TabStop = true; this.linkLabelTellMeMore.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelTellMeMore_LinkClicked); // // haNtolIndicator // resources.ApplyResources(this.haNtolIndicator, "haNtolIndicator"); this.haNtolIndicator.Name = "haNtolIndicator"; this.tableLayoutPanel1.SetRowSpan(this.haNtolIndicator, 4); // // dataGridViewVms // this.dataGridViewVms.BackgroundColor = System.Drawing.SystemColors.Window; this.dataGridViewVms.CellBorderStyle = System.Windows.Forms.DataGridViewCellBorderStyle.None; this.dataGridViewVms.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.DisableResizing; this.dataGridViewVms.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.colImage, this.colVm, this.colRestartPriority, this.colStartOrder, this.colDelay, this.colAgile}); this.tableLayoutPanel1.SetColumnSpan(this.dataGridViewVms, 6); resources.ApplyResources(this.dataGridViewVms, "dataGridViewVms"); this.dataGridViewVms.MultiSelect = true; this.dataGridViewVms.Name = "dataGridViewVms"; this.dataGridViewVms.SelectionChanged += new System.EventHandler(this.dataGridViewVms_SelectionChanged); this.dataGridViewVms.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dataGridViewVms_KeyDown); // // colImage // this.colImage.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.AllCells; resources.ApplyResources(this.colImage, "colImage"); this.colImage.Name = "colImage"; // // colVm // this.colVm.FillWeight = 123.8597F; resources.ApplyResources(this.colVm, "colVm"); this.colVm.Name = "colVm"; // // colRestartPriority // this.colRestartPriority.FillWeight = 142.0455F; resources.ApplyResources(this.colRestartPriority, "colRestartPriority"); this.colRestartPriority.Name = "colRestartPriority"; // // colStartOrder // this.colStartOrder.FillWeight = 78.03161F; resources.ApplyResources(this.colStartOrder, "colStartOrder"); this.colStartOrder.Name = "colStartOrder"; // // colDelay // this.colDelay.FillWeight = 78.03161F; resources.ApplyResources(this.colDelay, "colDelay"); this.colDelay.Name = "colDelay"; // // colAgile // this.colAgile.FillWeight = 78.03161F; resources.ApplyResources(this.colAgile, "colAgile"); this.colAgile.Name = "colAgile"; // // button1 // resources.ApplyResources(this.button1, "button1"); this.button1.Name = "button1"; this.button1.UseVisualStyleBackColor = true; // // bgWorker // this.bgWorker.WorkerSupportsCancellation = true; this.bgWorker.DoWork += new System.ComponentModel.DoWorkEventHandler(this.bgWorker_DoWork); this.bgWorker.RunWorkerCompleted += new System.ComponentModel.RunWorkerCompletedEventHandler(this.bgWorker_RunWorkerCompleted); // // AssignPriorities // resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.Controls.Add(this.tableLayoutPanel1); this.Name = "AssignPriorities"; this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBoxStatus)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudOrder)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudStartDelay)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewVms)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ContextMenuStrip contextMenuStrip; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label labelHaStatus; private System.Windows.Forms.PictureBox pictureBoxStatus; private HaNtolIndicator haNtolIndicator; private System.Windows.Forms.Label labelStartDelayUnits; private System.Windows.Forms.NumericUpDown nudStartDelay; private System.Windows.Forms.Label labelStartDelay; private System.Windows.Forms.Label labelStartOrder; private System.Windows.Forms.NumericUpDown nudOrder; private DropDownButton m_dropDownButtonRestartPriority; private System.Windows.Forms.Label labelProtectionLevel; private System.Windows.Forms.LinkLabel linkLabelTellMeMore; private XenAdmin.Controls.DataGridViewEx.DataGridViewEx dataGridViewVms; private System.Windows.Forms.DataGridViewImageColumn colImage; private System.Windows.Forms.DataGridViewTextBoxColumn colVm; private System.Windows.Forms.DataGridViewTextBoxColumn colRestartPriority; private System.Windows.Forms.DataGridViewTextBoxColumn colStartOrder; private System.Windows.Forms.DataGridViewTextBoxColumn colDelay; private System.Windows.Forms.DataGridViewTextBoxColumn colAgile; private System.ComponentModel.BackgroundWorker bgWorker; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.IdentityModel; using System.IdentityModel.Tokens; using System.ServiceModel.Channels; using System.ServiceModel.Description; using System.ServiceModel.Diagnostics; using System.ServiceModel.Security.Tokens; using System.Xml; using IPrefixGenerator = System.IdentityModel.IPrefixGenerator; namespace System.ServiceModel.Security { internal abstract class SendSecurityHeader : SecurityHeader, IMessageHeaderWithSharedNamespace { private bool _encryptSignature; private bool _primarySignatureDone; private SignatureConfirmations _signatureValuesGenerated; private SignatureConfirmations _signatureConfirmationsToSend; private int _idCounter; private string _idPrefix; private MessagePartSpecification _signatureParts; private List<SecurityTokenParameters> _basicSupportingTokenParameters = null; private List<SecurityTokenParameters> _endorsingTokenParameters = null; private List<SecurityTokenParameters> _signedEndorsingTokenParameters = null; private List<SecurityTokenParameters> _signedTokenParameters = null; private byte[] _primarySignatureValue = null; private bool _shouldProtectTokens; private BufferManager _bufferManager; private SecurityProtocolCorrelationState _correlationState; private bool _signThenEncrypt = true; private static readonly string[] s_ids = new string[] { "_0", "_1", "_2", "_3", "_4", "_5", "_6", "_7", "_8", "_9" }; protected SendSecurityHeader(Message message, string actor, bool mustUnderstand, bool relay, SecurityStandardsManager standardsManager, SecurityAlgorithmSuite algorithmSuite, MessageDirection transferDirection) : base(message, actor, mustUnderstand, relay, standardsManager, algorithmSuite, transferDirection) { ElementContainer = new SendSecurityHeaderElementContainer(); } public SendSecurityHeaderElementContainer ElementContainer { get; } public BufferManager StreamBufferManager { get { if (_bufferManager == null) { _bufferManager = BufferManager.CreateBufferManager(0, int.MaxValue); } return _bufferManager; } set { _bufferManager = value; } } protected SecurityAppliedMessage SecurityAppliedMessage { get { return (SecurityAppliedMessage)Message; } } public bool SignThenEncrypt { get { return _signThenEncrypt; } set { ThrowIfProcessingStarted(); _signThenEncrypt = value; } } public bool ShouldProtectTokens { get { return _shouldProtectTokens; } set { ThrowIfProcessingStarted(); _shouldProtectTokens = value; } } public void AddBasicSupportingToken(SecurityToken token, SecurityTokenParameters parameters) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(token)); } if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters)); } ThrowIfProcessingStarted(); SendSecurityHeaderElement tokenElement = new SendSecurityHeaderElement(token.Id, new TokenElement(token, StandardsManager)); tokenElement.MarkedForEncryption = true; ElementContainer.AddBasicSupportingToken(tokenElement); AddParameters(ref _basicSupportingTokenParameters, parameters); } public void AddEndorsingSupportingToken(SecurityToken token, SecurityTokenParameters parameters) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(token)); } if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters)); } ThrowIfProcessingStarted(); ElementContainer.AddEndorsingSupportingToken(token); ShouldSignToHeader |= (!RequireMessageProtection) && (SecurityUtils.GetSecurityKey<AsymmetricSecurityKey>(token) != null); AddParameters(ref _endorsingTokenParameters, parameters); } public void AddSignedEndorsingSupportingToken(SecurityToken token, SecurityTokenParameters parameters) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(token)); } if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters)); } ThrowIfProcessingStarted(); ElementContainer.AddSignedEndorsingSupportingToken(token); AddParameters(ref _signedEndorsingTokenParameters, parameters); } public void AddSignedSupportingToken(SecurityToken token, SecurityTokenParameters parameters) { if (token == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(token)); } if (parameters == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(parameters)); } ThrowIfProcessingStarted(); ElementContainer.AddSignedSupportingToken(token); AddParameters(ref _signedTokenParameters, parameters); } public bool EncryptPrimarySignature { get { return _encryptSignature; } set { ThrowIfProcessingStarted(); if (value) { throw ExceptionHelper.PlatformNotSupported(); } _encryptSignature = value; } } protected bool ShouldUseStrTransformForToken(SecurityToken securityToken, int position, SecurityTokenAttachmentMode mode, out SecurityKeyIdentifierClause keyIdentifierClause) { keyIdentifierClause = null; return false; } XmlDictionaryString IMessageHeaderWithSharedNamespace.SharedNamespace { get { return XD.UtilityDictionary.Namespace; } } XmlDictionaryString IMessageHeaderWithSharedNamespace.SharedPrefix { get { return XD.UtilityDictionary.Prefix; } } public string IdPrefix { get { return _idPrefix; } set { ThrowIfProcessingStarted(); _idPrefix = string.IsNullOrEmpty(value) || value == "_" ? null : value; } } protected internal SecurityTokenParameters SigningTokenParameters { get; } protected bool ShouldSignToHeader { get; private set; } = false; public override string Name { get { return StandardsManager.SecurityVersion.HeaderName.Value; } } public override string Namespace { get { return StandardsManager.SecurityVersion.HeaderNamespace.Value; } } public SecurityTimestamp Timestamp { get { return ElementContainer.Timestamp; } } private void AddParameters(ref List<SecurityTokenParameters> list, SecurityTokenParameters item) { if (list == null) { list = new List<SecurityTokenParameters>(); } list.Add(item); } public abstract void ApplyBodySecurity(XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator); public abstract void ApplySecurityAndWriteHeaders(MessageHeaders headers, XmlDictionaryWriter writer, IPrefixGenerator prefixGenerator); protected override void OnWriteStartHeader(XmlDictionaryWriter writer, MessageVersion messageVersion) { StandardsManager.SecurityVersion.WriteStartHeader(writer); WriteHeaderAttributes(writer, messageVersion); } protected override void OnWriteHeaderContents(XmlDictionaryWriter writer, MessageVersion messageVersion) { if (ElementContainer.Timestamp != null && Layout != SecurityHeaderLayout.LaxTimestampLast) { StandardsManager.WSUtilitySpecificationVersion.WriteTimestamp(writer, ElementContainer.Timestamp); } if (ElementContainer.PrerequisiteToken != null) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, ElementContainer.PrerequisiteToken); } if (ElementContainer.SourceSigningToken != null) { if (ShouldSerializeToken(SigningTokenParameters, MessageDirection)) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, ElementContainer.SourceSigningToken); // Implement Protect token // NOTE: The spec says sign the primary token if it is not included in the message. But we currently are not supporting it // as we do not support STR-Transform for external references. Hence we can not sign the token which is external ie not in the message. // This only affects the messages from service to client where // 1. allowSerializedSigningTokenOnReply is false. // 2. SymmetricSecurityBindingElement with IssuedTokens binding where the issued token has a symmetric key. if (ShouldProtectTokens) { WriteSecurityTokenReferencyEntry(writer, ElementContainer.SourceSigningToken, SigningTokenParameters); } } } if (ElementContainer.DerivedSigningToken != null) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, ElementContainer.DerivedSigningToken); } if (ElementContainer.WrappedEncryptionToken != null) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, ElementContainer.WrappedEncryptionToken); } if (ElementContainer.DerivedEncryptionToken != null) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, ElementContainer.DerivedEncryptionToken); } if (SignThenEncrypt) { if (ElementContainer.ReferenceList != null) { ElementContainer.ReferenceList.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } SecurityToken[] signedTokens = ElementContainer.GetSignedSupportingTokens(); if (signedTokens != null) { for (int i = 0; i < signedTokens.Length; ++i) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, signedTokens[i]); WriteSecurityTokenReferencyEntry(writer, signedTokens[i], _signedTokenParameters[i]); } } SendSecurityHeaderElement[] basicTokensXml = ElementContainer.GetBasicSupportingTokens(); if (basicTokensXml != null) { for (int i = 0; i < basicTokensXml.Length; ++i) { basicTokensXml[i].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); if (SignThenEncrypt) { WriteSecurityTokenReferencyEntry(writer, null, _basicSupportingTokenParameters[i]); } } } SecurityToken[] endorsingTokens = ElementContainer.GetEndorsingSupportingTokens(); if (endorsingTokens != null) { for (int i = 0; i < endorsingTokens.Length; ++i) { if (ShouldSerializeToken(_endorsingTokenParameters[i], MessageDirection)) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, endorsingTokens[i]); } } } SecurityToken[] endorsingDerivedTokens = ElementContainer.GetEndorsingDerivedSupportingTokens(); if (endorsingDerivedTokens != null) { for (int i = 0; i < endorsingDerivedTokens.Length; ++i) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, endorsingDerivedTokens[i]); } } SecurityToken[] signedEndorsingTokens = ElementContainer.GetSignedEndorsingSupportingTokens(); if (signedEndorsingTokens != null) { for (int i = 0; i < signedEndorsingTokens.Length; ++i) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, signedEndorsingTokens[i]); WriteSecurityTokenReferencyEntry(writer, signedEndorsingTokens[i], _signedEndorsingTokenParameters[i]); } } SecurityToken[] signedEndorsingDerivedTokens = ElementContainer.GetSignedEndorsingDerivedSupportingTokens(); if (signedEndorsingDerivedTokens != null) { for (int i = 0; i < signedEndorsingDerivedTokens.Length; ++i) { StandardsManager.SecurityTokenSerializer.WriteToken(writer, signedEndorsingDerivedTokens[i]); } } SendSecurityHeaderElement[] signatureConfirmations = ElementContainer.GetSignatureConfirmations(); if (signatureConfirmations != null) { for (int i = 0; i < signatureConfirmations.Length; ++i) { signatureConfirmations[i].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } if (ElementContainer.PrimarySignature != null && ElementContainer.PrimarySignature.Item != null) { ElementContainer.PrimarySignature.Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } SendSecurityHeaderElement[] endorsingSignatures = ElementContainer.GetEndorsingSignatures(); if (endorsingSignatures != null) { for (int i = 0; i < endorsingSignatures.Length; ++i) { endorsingSignatures[i].Item.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } if (!SignThenEncrypt) { if (ElementContainer.ReferenceList != null) { ElementContainer.ReferenceList.WriteTo(writer, ServiceModelDictionaryManager.Instance); } } if (ElementContainer.Timestamp != null && Layout == SecurityHeaderLayout.LaxTimestampLast) { StandardsManager.WSUtilitySpecificationVersion.WriteTimestamp(writer, ElementContainer.Timestamp); } } public void AddTimestamp(TimeSpan timestampValidityDuration) { DateTime now = DateTime.UtcNow; string id = RequireMessageProtection ? SecurityUtils.GenerateId() : GenerateId(); AddTimestamp(new SecurityTimestamp(now, now + timestampValidityDuration, id)); } public void AddTimestamp(SecurityTimestamp timestamp) { ThrowIfProcessingStarted(); if (ElementContainer.Timestamp != null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.TimestampAlreadySetForSecurityHeader), Message); } ElementContainer.Timestamp = timestamp ?? throw TraceUtility.ThrowHelperArgumentNull(nameof(timestamp), Message); } protected abstract void WriteSecurityTokenReferencyEntry(XmlDictionaryWriter writer, SecurityToken securityToken, SecurityTokenParameters securityTokenParameters); public Message SetupExecution() { ThrowIfProcessingStarted(); SetProcessingStarted(); bool signBody = false; if (ElementContainer.SourceSigningToken != null) { throw ExceptionHelper.PlatformNotSupported(); } bool encryptBody = false; if (ElementContainer.SourceEncryptionToken != null) { throw ExceptionHelper.PlatformNotSupported(); } SecurityAppliedMessage message = new SecurityAppliedMessage(Message, this, signBody, encryptBody); Message = message; return message; } protected virtual ISignatureValueSecurityElement[] CreateSignatureConfirmationElements(SignatureConfirmations signatureConfirmations) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException( SR.SignatureConfirmationNotSupported)); } private void StartEncryption() { if (ElementContainer.SourceEncryptionToken == null) { return; } throw ExceptionHelper.PlatformNotSupported(); // Encrypting isn't supported } private void CompleteEncryption() { // No-op as encryption not supported } internal void StartSecurityApplication() { if (SignThenEncrypt) { StartSignature(); StartEncryption(); } else { throw ExceptionHelper.PlatformNotSupported(); // Encrypting can only come first when using message encryption which isn't supported } } internal void CompleteSecurityApplication() { if (SignThenEncrypt) { CompleteSignature(); SignWithSupportingTokens(); CompleteEncryption(); } else { throw ExceptionHelper.PlatformNotSupported(); // Encrypting can only come first when using message encryption which isn't supported } if (_correlationState != null) { _correlationState.SignatureConfirmations = GetSignatureValues(); } } public void RemoveSignatureEncryptionIfAppropriate() { // No-op as no support for encryption } public string GenerateId() { int id = _idCounter++; if (_idPrefix != null) { return _idPrefix + id; } if (id < s_ids.Length) { return s_ids[id]; } else { return "_" + id; } } private SignatureConfirmations GetSignatureValues() { return _signatureValuesGenerated; } internal static bool ShouldSerializeToken(SecurityTokenParameters parameters, MessageDirection transferDirection) { switch (parameters.InclusionMode) { case SecurityTokenInclusionMode.AlwaysToInitiator: return (transferDirection == MessageDirection.Output); case SecurityTokenInclusionMode.Once: case SecurityTokenInclusionMode.AlwaysToRecipient: return (transferDirection == MessageDirection.Input); case SecurityTokenInclusionMode.Never: return false; default: throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.UnsupportedTokenInclusionMode, parameters.InclusionMode))); } } protected internal SecurityTokenReferenceStyle GetTokenReferenceStyle(SecurityTokenParameters parameters) { return (ShouldSerializeToken(parameters, MessageDirection)) ? SecurityTokenReferenceStyle.Internal : SecurityTokenReferenceStyle.External; } private void StartSignature() { if (ElementContainer.SourceSigningToken == null) { return; } // determine the key identifier clause to use for the source SecurityTokenReferenceStyle sourceSigningKeyReferenceStyle = GetTokenReferenceStyle(SigningTokenParameters); SecurityKeyIdentifierClause sourceSigningKeyIdentifierClause = SigningTokenParameters.CreateKeyIdentifierClause(ElementContainer.SourceSigningToken, sourceSigningKeyReferenceStyle); if (sourceSigningKeyIdentifierClause == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.TokenManagerCannotCreateTokenReference), Message); } SecurityToken signingToken; SecurityKeyIdentifierClause signingKeyIdentifierClause; // determine if a token needs to be derived if (SigningTokenParameters.RequireDerivedKeys && !SigningTokenParameters.HasAsymmetricKey) { // Derived keys not required for initial implementation throw ExceptionHelper.PlatformNotSupported(); } else { signingToken = ElementContainer.SourceSigningToken; signingKeyIdentifierClause = sourceSigningKeyIdentifierClause; } SecurityKeyIdentifier signingKeyIdentifier = new SecurityKeyIdentifier(signingKeyIdentifierClause); if (_signatureConfirmationsToSend != null && _signatureConfirmationsToSend.Count > 0) { ISecurityElement[] signatureConfirmationElements; signatureConfirmationElements = CreateSignatureConfirmationElements(_signatureConfirmationsToSend); for (int i = 0; i < signatureConfirmationElements.Length; ++i) { SendSecurityHeaderElement sigConfElement = new SendSecurityHeaderElement(signatureConfirmationElements[i].Id, signatureConfirmationElements[i]); sigConfElement.MarkedForEncryption = _signatureConfirmationsToSend.IsMarkedForEncryption; ElementContainer.AddSignatureConfirmation(sigConfElement); } } bool generateTargettablePrimarySignature = ((_endorsingTokenParameters != null) || (_signedEndorsingTokenParameters != null)); StartPrimarySignatureCore(signingToken, signingKeyIdentifier, _signatureParts, generateTargettablePrimarySignature); } private void CompleteSignature() { ISignatureValueSecurityElement signedXml = CompletePrimarySignatureCore( ElementContainer.GetSignatureConfirmations(), ElementContainer.GetSignedEndorsingSupportingTokens(), ElementContainer.GetSignedSupportingTokens(), ElementContainer.GetBasicSupportingTokens(), true); if (signedXml == null) { return; } ElementContainer.PrimarySignature = new SendSecurityHeaderElement(signedXml.Id, signedXml); ElementContainer.PrimarySignature.MarkedForEncryption = _encryptSignature; AddGeneratedSignatureValue(signedXml.GetSignatureValue(), EncryptPrimarySignature); _primarySignatureDone = true; _primarySignatureValue = signedXml.GetSignatureValue(); } protected abstract void StartPrimarySignatureCore(SecurityToken token, SecurityKeyIdentifier identifier, MessagePartSpecification signatureParts, bool generateTargettablePrimarySignature); protected abstract ISignatureValueSecurityElement CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens, bool isPrimarySignature); protected abstract ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier); protected abstract ISignatureValueSecurityElement CreateSupportingSignature(SecurityToken token, SecurityKeyIdentifier identifier, ISecurityElement primarySignature); private void SignWithSupportingToken(SecurityToken token, SecurityKeyIdentifierClause identifierClause) { if (token == null) { throw TraceUtility.ThrowHelperArgumentNull(nameof(token), Message); } if (identifierClause == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.TokenManagerCannotCreateTokenReference), Message); } if (!RequireMessageProtection) { if (ElementContainer.Timestamp == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException( SR.SigningWithoutPrimarySignatureRequiresTimestamp), Message); } } else { if (!_primarySignatureDone) { throw TraceUtility.ThrowHelperError(new InvalidOperationException( SR.PrimarySignatureMustBeComputedBeforeSupportingTokenSignatures), Message); } if (ElementContainer.PrimarySignature.Item == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException( SR.SupportingTokenSignaturesNotExpected), Message); } } SecurityKeyIdentifier identifier = new SecurityKeyIdentifier(identifierClause); ISignatureValueSecurityElement supportingSignature; if (!RequireMessageProtection) { supportingSignature = CreateSupportingSignature(token, identifier); } else { supportingSignature = CreateSupportingSignature(token, identifier, ElementContainer.PrimarySignature.Item); } AddGeneratedSignatureValue(supportingSignature.GetSignatureValue(), _encryptSignature); SendSecurityHeaderElement supportingSignatureElement = new SendSecurityHeaderElement(supportingSignature.Id, supportingSignature); supportingSignatureElement.MarkedForEncryption = _encryptSignature; ElementContainer.AddEndorsingSignature(supportingSignatureElement); } private void SignWithSupportingTokens() { SecurityToken[] endorsingTokens = ElementContainer.GetEndorsingSupportingTokens(); if (endorsingTokens != null) { for (int i = 0; i < endorsingTokens.Length; ++i) { SecurityToken source = endorsingTokens[i]; SecurityKeyIdentifierClause sourceKeyClause = _endorsingTokenParameters[i].CreateKeyIdentifierClause(source, GetTokenReferenceStyle(_endorsingTokenParameters[i])); if (sourceKeyClause == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.TokenManagerCannotCreateTokenReference), Message); } SecurityToken signingToken; SecurityKeyIdentifierClause signingKeyClause; if (_endorsingTokenParameters[i].RequireDerivedKeys && !_endorsingTokenParameters[i].HasAsymmetricKey) { throw ExceptionHelper.PlatformNotSupported(); } else { signingToken = source; signingKeyClause = sourceKeyClause; } SignWithSupportingToken(signingToken, signingKeyClause); } } SecurityToken[] signedEndorsingSupportingTokens = ElementContainer.GetSignedEndorsingSupportingTokens(); if (signedEndorsingSupportingTokens != null) { for (int i = 0; i < signedEndorsingSupportingTokens.Length; ++i) { SecurityToken source = signedEndorsingSupportingTokens[i]; SecurityKeyIdentifierClause sourceKeyClause = _signedEndorsingTokenParameters[i].CreateKeyIdentifierClause(source, GetTokenReferenceStyle(_signedEndorsingTokenParameters[i])); if (sourceKeyClause == null) { throw TraceUtility.ThrowHelperError(new MessageSecurityException(SR.TokenManagerCannotCreateTokenReference), Message); } SecurityToken signingToken; SecurityKeyIdentifierClause signingKeyClause; if (_signedEndorsingTokenParameters[i].RequireDerivedKeys && !_signedEndorsingTokenParameters[i].HasAsymmetricKey) { throw ExceptionHelper.PlatformNotSupported(); // Derived keys not supported initially } else { signingToken = source; signingKeyClause = sourceKeyClause; } SignWithSupportingToken(signingToken, signingKeyClause); } } } private void AddGeneratedSignatureValue(byte[] signatureValue, bool wasEncrypted) { // cache outgoing signatures only on the client side if (MaintainSignatureConfirmationState && (_signatureConfirmationsToSend == null)) { if (_signatureValuesGenerated == null) { _signatureValuesGenerated = new SignatureConfirmations(); } _signatureValuesGenerated.AddConfirmation(signatureValue, wasEncrypted); } } } internal class TokenElement : ISecurityElement { private SecurityStandardsManager _standardsManager; public TokenElement(SecurityToken token, SecurityStandardsManager standardsManager) { Token = token; _standardsManager = standardsManager; } public override bool Equals(object item) { TokenElement element = item as TokenElement; return (element != null && Token == element.Token && _standardsManager == element._standardsManager); } public override int GetHashCode() { return Token.GetHashCode() ^ _standardsManager.GetHashCode(); } public bool HasId { get { return true; } } public string Id { get { return Token.Id; } } public SecurityToken Token { get; } public void WriteTo(XmlDictionaryWriter writer, DictionaryManager dictionaryManager) { _standardsManager.SecurityTokenSerializer.WriteToken(writer, Token); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using FluentNHibernate.Automapping.TestFixtures; using FluentNHibernate.Conventions.Helpers.Builders; using FluentNHibernate.Conventions.Instances; using FluentNHibernate.Mapping; using FluentNHibernate.MappingModel.Collections; using FluentNHibernate.Testing.FluentInterfaceTests; using NUnit.Framework; namespace FluentNHibernate.Testing.ConventionsTests.OverridingFluentInterface { [TestFixture] public class HasManyToManyCollectionConventionTests { private PersistenceModel model; private IMappingProvider mapping; private Type mappingType; [SetUp] public void CreatePersistenceModel() { model = new PersistenceModel(); } [Test] public void AccessShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Access.Field()); Convention(x => x.Access.Property()); VerifyModel(x => x.Access.ShouldEqual("field")); } [Test] public void BatchSizeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.BatchSize(10)); Convention(x => x.BatchSize(100)); VerifyModel(x => x.BatchSize.ShouldEqual(10)); } [Test] public void CacheShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Cache.ReadOnly()); Convention(x => x.Cache.ReadWrite()); VerifyModel(x => x.Cache.Usage.ShouldEqual("read-only")); } [Test] public void CascadeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Cascade.All()); Convention(x => x.Cascade.None()); VerifyModel(x => x.Cascade.ShouldEqual("all")); } [Test] public void CheckConstraintShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Check("constraint = 1")); Convention(x => x.Check("constraint = 0")); VerifyModel(x => x.Check.ShouldEqual("constraint = 1")); } [Test] public void CollectionTypeShouldntBeOverwritten() { Mapping(x => x.Children, x => x.CollectionType<int>()); Convention(x => x.CollectionType<string>()); VerifyModel(x => x.CollectionType.GetUnderlyingSystemType().ShouldEqual(typeof(int))); } [Test] public void FetchShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Fetch.Join()); Convention(x => x.Fetch.Select()); VerifyModel(x => x.Fetch.ShouldEqual("join")); } [Test] public void GenericShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Generic()); Convention(x => x.Not.Generic()); VerifyModel(x => x.Generic.ShouldBeTrue()); } [Test] public void InverseShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Inverse()); Convention(x => x.Not.Inverse()); VerifyModel(x => x.Inverse.ShouldBeTrue()); } [Test] public void ParentKeyColumnNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.ParentKeyColumn("name")); Convention(x => x.Key.Column("xxx")); VerifyModel(x => x.Key.Columns.First().Name.ShouldEqual("name")); } [Test] public void ElementColumnNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Element("name")); Convention(x => x.Element.Column("xxx")); VerifyModel(x => x.Element.Columns.First().Name.ShouldEqual("name")); } [Test] public void ElementTypeShouldntBeOverwrittenUsingGeneric() { Mapping(x => x.Children, x => x.Element("xxx", e => e.Type<string>())); Convention(x => x.Element.Type<int>()); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ElementTypeShouldntBeOverwrittenUsingTypeOf() { Mapping(x => x.Children, x => x.Element("xxx", e => e.Type<string>())); Convention(x => x.Element.Type(typeof(int))); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void ElementTypeShouldntBeOverwrittenUsingString() { Mapping(x => x.Children, x => x.Element("xxx", e => e.Type<string>())); Convention(x => x.Element.Type(typeof(int).AssemblyQualifiedName)); VerifyModel(x => x.Element.Type.GetUnderlyingSystemType().ShouldEqual(typeof(string))); } [Test] public void LazyShouldntBeOverwritten() { Mapping(x => x.Children, x => x.LazyLoad()); Convention(x => x.Not.LazyLoad()); VerifyModel(x => x.Lazy.ShouldEqual(Lazy.True)); } [Test] public void OptimisticLockShouldntBeOverwritten() { Mapping(x => x.Children, x => x.OptimisticLock()); Convention(x => x.Not.OptimisticLock()); VerifyModel(x => x.OptimisticLock.ShouldEqual(true)); } [Test] public void PersisterShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Persister<CustomPersister>()); Convention(x => x.Persister<SecondCustomPersister>()); VerifyModel(x => x.Persister.GetUnderlyingSystemType().ShouldEqual(typeof(CustomPersister))); } [Test] public void SchemaShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Schema("dbo")); Convention(x => x.Schema("test")); VerifyModel(x => x.Schema.ShouldEqual("dbo")); } [Test] public void WhereShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Where("x = 1")); Convention(x => x.Where("y = 2")); VerifyModel(x => x.Where.ShouldEqual("x = 1")); } [Test] public void TableNameShouldntBeOverwritten() { Mapping(x => x.Children, x => x.Table("table")); Convention(x => x.Table("xxx")); VerifyModel(x => x.TableName.ShouldEqual("table")); } #region Helpers private void Convention(Action<ICollectionInstance> convention) { model.Conventions.Add(new CollectionConventionBuilder().Always(convention)); } private void Mapping<TChild>(Expression<Func<ExampleInheritedClass, IEnumerable<TChild>>> property, Action<ManyToManyPart<TChild>> mappingDefinition) { var classMap = new ClassMap<ExampleInheritedClass>(); classMap.Id(x => x.Id); var map = classMap.HasManyToMany(property); mappingDefinition(map); mapping = classMap; mappingType = typeof(ExampleInheritedClass); } private void VerifyModel(Action<CollectionMapping> modelVerification) { model.Add(mapping); var generatedModels = model.BuildMappings(); var modelInstance = generatedModels .First(x => x.Classes.FirstOrDefault(c => c.Type == mappingType) != null) .Classes.First() .Collections.First(); modelVerification(modelInstance); } #endregion } }
#region License //----------------------------------------------------------------------- // <copyright> // The MIT License (MIT) // // Copyright (c) 2014 Kirk S Woll // // 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> //----------------------------------------------------------------------- #endregion using System.Collections.Generic; namespace System.Linq.Expressions { public class ExpressionVisitor { protected ExpressionVisitor() { } public virtual Expression Visit(Expression node) { if (node != null) { return node.Accept(this); } return null; } public List<Expression> Visit(List<Expression> nodes) { Expression[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { Expression node = Visit(nodes[i]); if (newNodes != null) { newNodes[i] = node; } else if (!ReferenceEquals(node, nodes[i])) { newNodes = new Expression[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new List<Expression>(newNodes); } internal Expression[] VisitArguments(IArgumentProvider nodes) { Expression[] newNodes = null; for (int i = 0, n = nodes.Arguments.Count; i < n; i++) { Expression curNode = nodes.Arguments[i]; Expression node = Visit(curNode); if (newNodes != null) { newNodes[i] = node; } else if (!ReferenceEquals(node, curNode)) { newNodes = new Expression[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes.Arguments[j]; } newNodes[i] = node; } } return newNodes; } public static List<T> Visit<T>(List<T> nodes, Func<T, T> elementVisitor) { T[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { T node = elementVisitor(nodes[i]); if (newNodes != null) { newNodes[i] = node; } else if (!ReferenceEquals(node, nodes[i])) { newNodes = new T[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new List<T>(newNodes); } public T VisitAndConvert<T>(T node, string callerName) where T : Expression { if (node == null) { return null; } node = Visit(node) as T; if (node == null) { throw new Exception("MustRewriteToSameNode"); } return node; } public List<T> VisitAndConvert<T>(List<T> nodes, string callerName) where T : Expression { T[] newNodes = null; for (int i = 0, n = nodes.Count; i < n; i++) { var node = Visit(nodes[i]) as T; if (node == null) { throw new Exception("MustRewriteToSameNode"); } if (newNodes != null) { newNodes[i] = node; } else if (!ReferenceEquals(node, nodes[i])) { newNodes = new T[n]; for (int j = 0; j < i; j++) { newNodes[j] = nodes[j]; } newNodes[i] = node; } } if (newNodes == null) { return nodes; } return new List<T>(newNodes); } protected internal virtual Expression VisitBinary(BinaryExpression node) { // Walk children in evaluation order: left, conversion, right return ValidateBinary( node, node.Update( Visit(node.Left), VisitAndConvert(node.Conversion, "VisitBinary"), Visit(node.Right) ) ); } protected internal virtual Expression VisitConditional(ConditionalExpression node) { return node.Update(Visit(node.Test), Visit(node.IfTrue), Visit(node.IfFalse)); } protected internal virtual Expression VisitConstant(ConstantExpression node) { return node; } protected internal virtual Expression VisitDefault(DefaultExpression node) { return node; } protected internal virtual Expression VisitInvocation(InvocationExpression node) { Expression e = Visit(node.Expression); Expression[] a = VisitArguments(node); if (e == node.Expression && a == null) { return node; } return node.Rewrite(e, a); } protected internal virtual Expression VisitLambda<T>(Expression<T> node) { return node.Update(Visit(node.Body), VisitAndConvert(node.Parameters, "VisitLambda")); } protected internal virtual Expression VisitMember(MemberExpression node) { return node.Update(Visit(node.Expression)); } protected internal virtual Expression VisitIndex(IndexExpression node) { Expression o = Visit(node.Object); Expression[] a = VisitArguments(node); if (o == node.Object && a == null) { return node; } return node;//node.Rewrite(o, a); } protected internal virtual Expression VisitMethodCall(MethodCallExpression node) { Expression o = Visit(node.Object); Expression[] a = VisitArguments(node); if (o == node.Object && a == null) { return node; } return node;//node.Rewrite(o, a); } protected internal virtual Expression VisitNewArray(NewArrayExpression node) { return node.Update(Visit(node.Expressions)); } protected internal virtual Expression VisitNew(NewExpression node) { return node.Update(Visit(node.Arguments)); } protected internal virtual Expression VisitParameter(ParameterExpression node) { return node; } protected internal virtual Expression VisitTypeBinary(TypeBinaryExpression node) { return node.Update(Visit(node.Expression)); } protected internal virtual Expression VisitUnary(UnaryExpression node) { return ValidateUnary(node, node.Update(Visit(node.Operand))); } protected internal virtual Expression VisitMemberInit(MemberInitExpression node) { return node.Update ( VisitAndConvert(node.NewExpression, "VisitMemberInit"), Visit(node.Bindings, VisitMemberBinding) ); } protected internal virtual Expression VisitListInit(ListInitExpression node) { return node.Update ( VisitAndConvert(node.NewExpression, "VisitListInit"), Visit(node.Initializers, VisitElementInit) ); } protected virtual ElementInit VisitElementInit(ElementInit node) { return node.Update(Visit(node.Arguments)); } protected virtual MemberBinding VisitMemberBinding(MemberBinding node) { switch (node.BindingType) { case MemberBindingType.Assignment: return VisitMemberAssignment((MemberAssignment)node); case MemberBindingType.MemberBinding: return VisitMemberMemberBinding((MemberMemberBinding)node); case MemberBindingType.ListBinding: return VisitMemberListBinding((MemberListBinding)node); default: throw new Exception("UnhandledBindingType"); } } protected virtual MemberAssignment VisitMemberAssignment(MemberAssignment node) { return node.Update(Visit(node.Expression)); } protected virtual MemberMemberBinding VisitMemberMemberBinding(MemberMemberBinding node) { return node.Update(Visit(node.Bindings, VisitMemberBinding)); } protected virtual MemberListBinding VisitMemberListBinding(MemberListBinding node) { return node.Update(Visit(node.Initializers, VisitElementInit)); } private static UnaryExpression ValidateUnary(UnaryExpression before, UnaryExpression after) { if (before != after && before.Method == null) { if (after.Method != null) { throw new Exception("MustRewriteWithoutMethod"); } // rethrow has null operand if (before.Operand != null && after.Operand != null) { ValidateChildType(before.Operand.Type, after.Operand.Type, "VisitUnary"); } } return after; } private static BinaryExpression ValidateBinary(BinaryExpression before, BinaryExpression after) { if (before != after && before.Method == null) { if (after.Method != null) { throw new Exception("MustRewriteWithoutMethod"); } ValidateChildType(before.Left.Type, after.Left.Type, "VisitBinary"); ValidateChildType(before.Right.Type, after.Right.Type, "VisitBinary"); } return after; } private static void ValidateChildType(Type before, Type after, string methodName) { if (before.IsValueType) { if (before == after) { // types are the same value type return; } } else if (!after.IsValueType) { // both are reference types return; } // Otherwise, it's an invalid type change. throw new Exception("MustRewriteChildToSameType"); } /* private static SwitchExpression ValidateSwitch(SwitchExpression before, SwitchExpression after) { // If we did not have a method, we don't want to bind to one, // it might not be the right thing. if (before.Comparison == null && after.Comparison != null) { throw Error.MustRewriteWithoutMethod(after.Comparison, "VisitSwitch"); } return after; } protected internal virtual Expression VisitBlock(BlockExpression node) { int count = node.ExpressionCount; Expression[] nodes = null; for (int i = 0; i < count; i++) { Expression oldNode = node.GetExpression(i); Expression newNode = Visit(oldNode); if (oldNode != newNode) { if (nodes == null) { nodes = new Expression[count]; } nodes[i] = newNode; } } var v = VisitAndConvert(node.Variables, "VisitBlock"); if (v == node.Variables && nodes == null) { return node; } else { for (int i = 0; i < count; i++) { if (nodes[i] == null) { nodes[i] = node.GetExpression(i); } } } return node.Rewrite(v, nodes); } protected internal virtual Expression VisitDynamic(DynamicExpression node) { Expression[] a = VisitArguments((IArgumentProvider)node); if (a == null) { return node; } return node.Rewrite(a); } protected internal virtual Expression VisitDebugInfo(DebugInfoExpression node) { return node; } * protected internal virtual Expression VisitExtension(Expression node) { return node.VisitChildren(this); } protected internal virtual Expression VisitGoto(GotoExpression node) { return node.Update(VisitLabelTarget(node.Target), Visit(node.Value)); } protected virtual LabelTarget VisitLabelTarget(LabelTarget node) { return node; } protected internal virtual Expression VisitLabel(LabelExpression node) { return node.Update(VisitLabelTarget(node.Target), Visit(node.DefaultValue)); } protected internal virtual Expression VisitLoop(LoopExpression node) { return node.Update(VisitLabelTarget(node.BreakLabel), VisitLabelTarget(node.ContinueLabel), Visit(node.Body)); } protected internal virtual Expression VisitRuntimeVariables(RuntimeVariablesExpression node) { return node.Update(VisitAndConvert(node.Variables, "VisitRuntimeVariables")); } protected virtual SwitchCase VisitSwitchCase(SwitchCase node) { return node.Update(Visit(node.TestValues), Visit(node.Body)); } protected internal virtual Expression VisitSwitch(SwitchExpression node) { return ValidateSwitch( node, node.Update( Visit(node.SwitchValue), Visit(node.Cases, VisitSwitchCase), Visit(node.DefaultBody) ) ); } protected virtual CatchBlock VisitCatchBlock(CatchBlock node) { return node.Update(VisitAndConvert(node.Variable, "VisitCatchBlock"), Visit(node.Filter), Visit(node.Body)); } protected internal virtual Expression VisitTry(TryExpression node) { return node.Update( Visit(node.Body), Visit(node.Handlers, VisitCatchBlock), Visit(node.Finally), Visit(node.Fault) ); } */ } }
/* * 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 log4net; using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using Nini.Config; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.ServiceAuth; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenMetaverse; using OpenMetaverse.StructuredData; namespace OpenSim.Services.Connectors { public class MapImageServicesConnector : BaseServiceConnector, IMapImageService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private string m_ServerURI = String.Empty; public MapImageServicesConnector() { } public MapImageServicesConnector(string serverURI) { m_ServerURI = serverURI.TrimEnd('/'); } public MapImageServicesConnector(IConfigSource source) { Initialise(source); } public virtual void Initialise(IConfigSource source) { IConfig config = source.Configs["MapImageService"]; if (config == null) { m_log.Error("[MAP IMAGE CONNECTOR]: MapImageService missing"); throw new Exception("MapImage connector init error"); } string serviceURI = config.GetString("MapImageServerURI", String.Empty); if (serviceURI == String.Empty) { m_log.Error("[MAP IMAGE CONNECTOR]: No Server URI named in section MapImageService"); throw new Exception("MapImage connector init error"); } m_ServerURI = serviceURI; m_ServerURI = serviceURI.TrimEnd('/'); base.Initialise(source, "MapImageService"); } public bool RemoveMapTile(int x, int y, out string reason) { reason = string.Empty; int tickstart = Util.EnvironmentTickCount(); Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["X"] = x.ToString(); sendData["Y"] = y.ToString(); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/removemap"; try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success")) { return true; } else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure")) { m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Delete failed: {0}", replyData["Message"].ToString()); reason = replyData["Message"].ToString(); return false; } else if (!replyData.ContainsKey("Result")) { m_log.DebugFormat("[MAP IMAGE CONNECTOR]: reply data does not contain result field"); } else { m_log.DebugFormat("[MAP IMAGE CONNECTOR]: unexpected result {0}", replyData["Result"].ToString()); reason = "Unexpected result " + replyData["Result"].ToString(); } } else { m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Map post received null reply"); } } catch (Exception e) { m_log.DebugFormat("[MAP IMAGE CONNECTOR]: Exception when contacting map server at {0}: {1}", uri, e.Message); } finally { // This just dumps a warning for any operation that takes more than 100 ms int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); m_log.DebugFormat("[MAP IMAGE CONNECTOR]: map tile deleted in {0}ms", tickdiff); } return false; } public bool AddMapTile(int x, int y, byte[] jpgData, out string reason) { reason = string.Empty; int tickstart = Util.EnvironmentTickCount(); Dictionary<string, object> sendData = new Dictionary<string, object>(); sendData["X"] = x.ToString(); sendData["Y"] = y.ToString(); sendData["TYPE"] = "image/jpeg"; sendData["DATA"] = Convert.ToBase64String(jpgData); string reqString = ServerUtils.BuildQueryString(sendData); string uri = m_ServerURI + "/map"; try { string reply = SynchronousRestFormsRequester.MakeRequest("POST", uri, reqString, m_Auth); if (reply != string.Empty) { Dictionary<string, object> replyData = ServerUtils.ParseXmlResponse(reply); if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "success")) { return true; } else if (replyData.ContainsKey("Result") && (replyData["Result"].ToString().ToLower() == "failure")) { reason = string.Format("Map post to {0} failed: {1}", uri, replyData["Message"].ToString()); m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); return false; } else if (!replyData.ContainsKey("Result")) { reason = string.Format("Reply data from {0} does not contain result field", uri); m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); } else { reason = string.Format("Unexpected result {0} from {1}" + replyData["Result"].ToString(), uri); m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); } } else { reason = string.Format("Map post received null reply from {0}", uri); m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); } } catch (Exception e) { reason = string.Format("Exception when posting to map server at {0}: {1}", uri, e.Message); m_log.WarnFormat("[MAP IMAGE CONNECTOR]: {0}", reason); } finally { // This just dumps a warning for any operation that takes more than 100 ms int tickdiff = Util.EnvironmentTickCountSubtract(tickstart); m_log.DebugFormat("[MAP IMAGE CONNECTOR]: map tile uploaded in {0}ms", tickdiff); } return false; } public byte[] GetMapTile(string fileName, out string format) { format = string.Empty; new Exception("GetMapTile method not Implemented"); return null; } } }
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.OperationalInsights { using System.Threading.Tasks; using Microsoft.Rest.Azure; using Models; /// <summary> /// Extension methods for SavedSearchesOperations. /// </summary> public static partial class SavedSearchesOperationsExtensions { /// <summary> /// Deletes the specified saved search in a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// Name of the saved search. /// </param> public static void Delete(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName) { System.Threading.Tasks.Task.Factory.StartNew(s => ((ISavedSearchesOperations)s).DeleteAsync(resourceGroupName, workspaceName, savedSearchName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Deletes the specified saved search in a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// Name of the saved search. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task DeleteAsync(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await operations.DeleteWithHttpMessagesAsync(resourceGroupName, workspaceName, savedSearchName, null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// The id of the saved search. /// </param> /// <param name='parameters'> /// The parameters required to save a search. /// </param> public static SavedSearch CreateOrUpdate(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName, SavedSearch parameters) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISavedSearchesOperations)s).CreateOrUpdateAsync(resourceGroupName, workspaceName, savedSearchName, parameters), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Creates or updates a saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// The id of the saved search. /// </param> /// <param name='parameters'> /// The parameters required to save a search. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SavedSearch> CreateOrUpdateAsync(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName, SavedSearch parameters, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, savedSearchName, parameters, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the specified saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// The id of the saved search. /// </param> public static SavedSearch Get(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISavedSearchesOperations)s).GetAsync(resourceGroupName, workspaceName, savedSearchName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the specified saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// The id of the saved search. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SavedSearch> GetAsync(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, workspaceName, savedSearchName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the saved searches for a given Log Analytics Workspace /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> public static SavedSearchesListResult ListByWorkspace(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISavedSearchesOperations)s).ListByWorkspaceAsync(resourceGroupName, workspaceName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the saved searches for a given Log Analytics Workspace /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SavedSearchesListResult> ListByWorkspaceAsync(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ListByWorkspaceWithHttpMessagesAsync(resourceGroupName, workspaceName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the results from a saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// The name of the saved search. /// </param> public static SearchResultsResponse GetResults(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName) { return System.Threading.Tasks.Task.Factory.StartNew(s => ((ISavedSearchesOperations)s).GetResultsAsync(resourceGroupName, workspaceName, savedSearchName), operations, System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <summary> /// Gets the results from a saved search for a given workspace. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group to get. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// Log Analytics workspace name /// </param> /// <param name='savedSearchName'> /// The name of the saved search. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async System.Threading.Tasks.Task<SearchResultsResponse> GetResultsAsync(this ISavedSearchesOperations operations, string resourceGroupName, string workspaceName, string savedSearchName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.GetResultsWithHttpMessagesAsync(resourceGroupName, workspaceName, savedSearchName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System; using System.Collections.Generic; using System.Text; namespace Facebook.CSSLayout { /** * Should measure the given node and put the result in the given MeasureOutput. */ public delegate MeasureOutput MeasureFunction(CSSNode node, float width, CSSMeasureMode widthMode, float height, CSSMeasureMode heightMode); /** * A CSS Node. It has a style object you can manipulate at {@link #style}. After calling * {@link #calculateLayout()}, {@link #layout} will be filled with the results of the layout. */ public class CSSNode { const int POSITION_LEFT = CSSLayout.POSITION_LEFT; const int POSITION_TOP = CSSLayout.POSITION_TOP; const int POSITION_RIGHT = CSSLayout.POSITION_RIGHT; const int POSITION_BOTTOM = CSSLayout.POSITION_BOTTOM; const int DIMENSION_WIDTH = CSSLayout.DIMENSION_WIDTH; const int DIMENSION_HEIGHT = CSSLayout.DIMENSION_HEIGHT; enum LayoutState { /** * Some property of this node or its children has changes and the current values in * {@link #layout} are not valid. */ DIRTY, /** * This node has a new layout relative to the last time {@link #MarkLayoutSeen()} was called. */ HAS_NEW_LAYOUT, /** * {@link #layout} is valid for the node's properties and this layout has been marked as * having been seen. */ UP_TO_DATE, } internal readonly CSSStyle style = new CSSStyle(); internal readonly CSSLayout layout = new CSSLayout(); internal readonly CachedCSSLayout lastLayout = new CachedCSSLayout(); internal int lineIndex = 0; internal /*package*/ CSSNode nextChild; // 4 is kinda arbitrary, but the default of 10 seems really high for an average View. readonly List<CSSNode> mChildren = new List<CSSNode>(4); [Nullable] CSSNode mParent; [Nullable] MeasureFunction mMeasureFunction = null; LayoutState mLayoutState = LayoutState.DIRTY; public int ChildCount { get { return mChildren.Count; } } public CSSNode this[int i] { get { return mChildren[i]; } } public IEnumerable<CSSNode> Children { get { return mChildren; } } public void AddChild(CSSNode child) { InsertChild(ChildCount, child); } public void InsertChild(int i, CSSNode child) { if (child.mParent != null) { throw new InvalidOperationException("Child already has a parent, it must be removed first."); } mChildren.Insert(i, child); child.mParent = this; dirty(); } public void RemoveChildAt(int i) { mChildren[i].mParent = null; mChildren.RemoveAt(i); dirty(); } public CSSNode Parent { [return: Nullable] get { return mParent; } } /** * @return the index of the given child, or -1 if the child doesn't exist in this node. */ public int IndexOf(CSSNode child) { return mChildren.IndexOf(child); } public MeasureFunction MeasureFunction { get { return mMeasureFunction; } set { if (!valuesEqual(mMeasureFunction, value)) { mMeasureFunction = value; dirty(); } } } public bool IsMeasureDefined { get { return mMeasureFunction != null; } } internal MeasureOutput measure(MeasureOutput measureOutput, float width, CSSMeasureMode widthMode, float height, CSSMeasureMode heightMode) { if (!IsMeasureDefined) { throw new Exception("Measure function isn't defined!"); } return Assertions.assertNotNull(mMeasureFunction)(this, width, widthMode, height, heightMode); } /** * Performs the actual layout and saves the results in {@link #layout} */ public void CalculateLayout() { LayoutEngine.layoutNode(DummyLayoutContext, this, CSSConstants.Undefined, CSSConstants.Undefined, null); } static readonly CSSLayoutContext DummyLayoutContext = new CSSLayoutContext(); /** * See {@link LayoutState#DIRTY}. */ public bool IsDirty { get { return mLayoutState == LayoutState.DIRTY; } } /** * See {@link LayoutState#HAS_NEW_LAYOUT}. */ public bool HasNewLayout { get { return mLayoutState == LayoutState.HAS_NEW_LAYOUT; } } internal protected virtual void dirty() { if (mLayoutState == LayoutState.DIRTY) { return; } else if (mLayoutState == LayoutState.HAS_NEW_LAYOUT) { throw new InvalidOperationException("Previous layout was ignored! MarkLayoutSeen() never called"); } mLayoutState = LayoutState.DIRTY; if (mParent != null) { mParent.dirty(); } } internal void markHasNewLayout() { mLayoutState = LayoutState.HAS_NEW_LAYOUT; } /** * Tells the node that the current values in {@link #layout} have been seen. Subsequent calls * to {@link #hasNewLayout()} will return false until this node is laid out with new parameters. * You must call this each time the layout is generated if the node has a new layout. */ public void MarkLayoutSeen() { if (!HasNewLayout) { throw new InvalidOperationException("Expected node to have a new layout to be seen!"); } mLayoutState = LayoutState.UP_TO_DATE; } void toStringWithIndentation(StringBuilder result, int level) { // Spaces and tabs are dropped by IntelliJ logcat integration, so rely on __ instead. StringBuilder indentation = new StringBuilder(); for (int i = 0; i < level; ++i) { indentation.Append("__"); } result.Append(indentation.ToString()); result.Append(layout.ToString()); if (ChildCount == 0) { return; } result.Append(", children: [\n"); for (var i = 0; i < ChildCount; i++) { this[i].toStringWithIndentation(result, level + 1); result.Append("\n"); } result.Append(indentation + "]"); } public override string ToString() { StringBuilder sb = new StringBuilder(); this.toStringWithIndentation(sb, 0); return sb.ToString(); } protected bool valuesEqual(float f1, float f2) { return FloatUtil.floatsEqual(f1, f2); } protected bool valuesEqual<T>([Nullable] T o1, [Nullable] T o2) { if (o1 == null) { return o2 == null; } return o1.Equals(o2); } public CSSDirection Direction { get { return style.direction; } set { updateDiscreteValue(ref style.direction, value); } } public CSSFlexDirection FlexDirection { get { return style.flexDirection; } set { updateDiscreteValue(ref style.flexDirection, value); } } public CSSJustify JustifyContent { get { return style.justifyContent; } set { updateDiscreteValue(ref style.justifyContent, value); } } public CSSAlign AlignContent { get { return style.alignContent; } set { updateDiscreteValue(ref style.alignContent, value); } } public CSSAlign AlignItems { get { return style.alignItems; } set { updateDiscreteValue(ref style.alignItems, value); } } public CSSAlign AlignSelf { get { return style.alignSelf; } set { updateDiscreteValue(ref style.alignSelf, value); } } public CSSPositionType PositionType { get { return style.positionType; } set { updateDiscreteValue(ref style.positionType, value); } } public CSSWrap Wrap { get { return style.flexWrap; } set { updateDiscreteValue(ref style.flexWrap, value); } } public float Flex { get { return style.flex; } set { updateFloatValue(ref style.flex, value); } } public CSSOverflow Overflow { get { return style.overflow; } set { updateDiscreteValue(ref style.overflow, value); } } public void SetMargin(CSSSpacingType spacingType, float margin) { if (style.margin.set((int)spacingType, margin)) dirty(); } public float GetMargin(CSSSpacingType spacingType) { return style.margin.getRaw((int)spacingType); } public void SetPadding(CSSSpacingType spacingType, float padding) { if (style.padding.set((int)spacingType, padding)) dirty(); } public float GetPadding(CSSSpacingType spacingType) { return style.padding.getRaw((int)spacingType); } public void SetBorder(CSSSpacingType spacingType, float border) { if (style.border.set((int)spacingType, border)) dirty(); } public float GetBorder(CSSSpacingType spacingType) { return style.border.getRaw((int)spacingType); } public float PositionTop { get { return style.position[POSITION_TOP]; } set { updateFloatValue(ref style.position[POSITION_TOP], value); } } public float PositionBottom { get { return style.position[POSITION_BOTTOM]; } set { updateFloatValue(ref style.position[POSITION_BOTTOM], value); } } public float PositionLeft { get { return style.position[POSITION_LEFT]; } set { updateFloatValue(ref style.position[POSITION_LEFT], value); } } public float PositionRight { get { return style.position[POSITION_RIGHT]; } set { updateFloatValue(ref style.position[POSITION_RIGHT], value); } } public float Width { get { return style.dimensions[DIMENSION_WIDTH]; } set { updateFloatValue(ref style.dimensions[DIMENSION_WIDTH], value); } } public float Height { get { return style.dimensions[DIMENSION_HEIGHT]; } set { updateFloatValue(ref style.dimensions[DIMENSION_HEIGHT], value); } } public float MinWidth { get { return style.minWidth; } set { updateFloatValue(ref style.minWidth, value); } } public float MinHeight { get { return style.minHeight; } set { updateFloatValue(ref style.minHeight, value); } } public float MaxWidth { get { return style.maxWidth; } set { updateFloatValue(ref style.maxWidth, value); } } public float MaxHeight { get { return style.maxHeight; } set { updateFloatValue(ref style.maxHeight, value); } } public float LayoutX { get { return layout.position[POSITION_LEFT]; } } public float LayoutY { get { return layout.position[POSITION_TOP]; } } public float LayoutWidth { get { return layout.dimensions[DIMENSION_WIDTH]; } } public float LayoutHeight { get { return layout.dimensions[DIMENSION_HEIGHT]; } } public CSSDirection LayoutDirection { get { return layout.direction; } } /** * Set a default padding (left/top/right/bottom) for this node. */ public void SetDefaultPadding(CSSSpacingType spacingType, float padding) { if (style.padding.setDefault((int)spacingType, padding)) dirty(); } void updateDiscreteValue<ValueT>(ref ValueT valueRef, ValueT newValue) { if (valuesEqual(valueRef, newValue)) return; valueRef = newValue; dirty(); } void updateFloatValue(ref float valueRef, float newValue) { if (valuesEqual(valueRef, newValue)) return; valueRef = newValue; dirty(); } } public static class CSSNodeExtensions { /* Explicitly mark this node as dirty. Calling this function is required when the measure function points to the same instance, but changes its behavior. For all other property changes, the node is automatically marked dirty. */ public static void MarkDirty(this CSSNode node) { node.dirty(); } } internal static class CSSNodeExtensionsInternal { public static CSSNode getParent(this CSSNode node) { return node.Parent; } public static int getChildCount(this CSSNode node) { return node.ChildCount; } public static CSSNode getChildAt(this CSSNode node, int i) { return node[i]; } public static void addChildAt(this CSSNode node, CSSNode child, int i) { node.InsertChild(i, child); } public static void removeChildAt(this CSSNode node, int i) { node.RemoveChildAt(i); } public static void setMeasureFunction(this CSSNode node, MeasureFunction measureFunction) { node.MeasureFunction = measureFunction; } public static void calculateLayout(this CSSNode node) { node.CalculateLayout(); } public static bool isDirty(this CSSNode node) { return node.IsDirty; } public static void setMargin(this CSSNode node, int spacingType, float margin) { node.SetMargin((CSSSpacingType)spacingType, margin); } public static void setPadding(this CSSNode node, int spacingType, float padding) { node.SetPadding((CSSSpacingType)spacingType, padding); } public static void setBorder(this CSSNode node, int spacingType, float border) { node.SetBorder((CSSSpacingType)spacingType, border); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Text; using SubSonic.DataProviders; using SubSonic.Extensions; using System.Linq.Expressions; using SubSonic.Schema; using SubSonic.Repository; using System.Data.Common; using SubSonic.SqlGeneration.Schema; namespace Solution.DataAccess.DataModel { /// <summary> /// A class which represents the Rules table in the HKHR Database. /// </summary> public partial class Rules: IActiveRecord { #region Built-in testing static TestRepository<Rules> _testRepo; static void SetTestRepo(){ _testRepo = _testRepo ?? new TestRepository<Rules>(new Solution.DataAccess.DataModel.HKHRDB()); } public static void ResetTestRepo(){ _testRepo = null; SetTestRepo(); } public static void Setup(List<Rules> testlist){ SetTestRepo(); foreach (var item in testlist) { _testRepo._items.Add(item); } } public static void Setup(Rules item) { SetTestRepo(); _testRepo._items.Add(item); } public static void Setup(int testItems) { SetTestRepo(); for(int i=0;i<testItems;i++){ Rules item=new Rules(); _testRepo._items.Add(item); } } public bool TestMode = false; #endregion IRepository<Rules> _repo; ITable tbl; bool _isNew; public bool IsNew(){ return _isNew; } public void SetIsLoaded(bool isLoaded){ _isLoaded=isLoaded; if(isLoaded) OnLoaded(); } public void SetIsNew(bool isNew){ _isNew=isNew; } bool _isLoaded; public bool IsLoaded(){ return _isLoaded; } List<IColumn> _dirtyColumns; public bool IsDirty(){ return _dirtyColumns.Count>0; } public List<IColumn> GetDirtyColumns (){ return _dirtyColumns; } Solution.DataAccess.DataModel.HKHRDB _db; public Rules(string connectionString, string providerName) { _db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); Init(); } void Init(){ TestMode=this._db.DataProvider.ConnectionString.Equals("test", StringComparison.InvariantCultureIgnoreCase); _dirtyColumns=new List<IColumn>(); if(TestMode){ Rules.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<Rules>(_db); } tbl=_repo.GetTable(); SetIsNew(true); OnCreated(); } public Rules(){ _db=new Solution.DataAccess.DataModel.HKHRDB(); Init(); } public void ORMapping(IDataRecord dataRecord) { IReadRecord readRecord = SqlReadRecord.GetIReadRecord(); readRecord.DataRecord = dataRecord; Id = readRecord.get_int("Id",null); rule_id = readRecord.get_string("rule_id",null); rule_name = readRecord.get_string("rule_name",null); rules = readRecord.get_string("rules",null); daysinmonth = readRecord.get_decimal("daysinmonth",null); hoursinday = readRecord.get_decimal("hoursinday",null); ot_rate = readRecord.get_decimal("ot_rate",null); sun_rate = readRecord.get_decimal("sun_rate",null); hd_rate = readRecord.get_decimal("hd_rate",null); restdatemethod = readRecord.get_short("restdatemethod",null); sun = readRecord.get_short("sun",null); sunbegin = readRecord.get_datetime("sunbegin",null); sunend = readRecord.get_datetime("sunend",null); sat = readRecord.get_short("sat",null); satbegin = readRecord.get_datetime("satbegin",null); satend = readRecord.get_datetime("satend",null); vrestdate = readRecord.get_string("vrestdate",null); vrestbegtime = readRecord.get_datetime("vrestbegtime",null); vrestendtime = readRecord.get_datetime("vrestendtime",null); memo = readRecord.get_string("memo",null); IsAllowances = readRecord.get_byte("IsAllowances",null); SatOutTime = readRecord.get_datetime("SatOutTime",null); MonInTime = readRecord.get_datetime("MonInTime",null); FriOutTime = readRecord.get_datetime("FriOutTime",null); HolInTime = readRecord.get_datetime("HolInTime",null); HolOutTime = readRecord.get_datetime("HolOutTime",null); } partial void OnCreated(); partial void OnLoaded(); partial void OnSaved(); partial void OnChanged(); public IList<IColumn> Columns{ get{ return tbl.Columns; } } public Rules(Expression<Func<Rules, bool>> expression):this() { SetIsLoaded(_repo.Load(this,expression)); } internal static IRepository<Rules> GetRepo(string connectionString, string providerName){ Solution.DataAccess.DataModel.HKHRDB db; if(String.IsNullOrEmpty(connectionString)){ db=new Solution.DataAccess.DataModel.HKHRDB(); }else{ db=new Solution.DataAccess.DataModel.HKHRDB(connectionString, providerName); } IRepository<Rules> _repo; if(db.TestMode){ Rules.SetTestRepo(); _repo=_testRepo; }else{ _repo = new SubSonicRepository<Rules>(db); } return _repo; } internal static IRepository<Rules> GetRepo(){ return GetRepo("",""); } public static Rules SingleOrDefault(Expression<Func<Rules, bool>> expression) { var repo = GetRepo(); var results=repo.Find(expression); Rules single=null; if(results.Count() > 0){ single=results.ToList()[0]; single.OnLoaded(); single.SetIsLoaded(true); single.SetIsNew(false); } return single; } public static Rules SingleOrDefault(Expression<Func<Rules, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); var results=repo.Find(expression); Rules single=null; if(results.Count() > 0){ single=results.ToList()[0]; } return single; } public static bool Exists(Expression<Func<Rules, bool>> expression,string connectionString, string providerName) { return All(connectionString,providerName).Any(expression); } public static bool Exists(Expression<Func<Rules, bool>> expression) { return All().Any(expression); } public static IList<Rules> Find(Expression<Func<Rules, bool>> expression) { var repo = GetRepo(); return repo.Find(expression).ToList(); } public static IList<Rules> Find(Expression<Func<Rules, bool>> expression,string connectionString, string providerName) { var repo = GetRepo(connectionString,providerName); return repo.Find(expression).ToList(); } public static IQueryable<Rules> All(string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetAll(); } public static IQueryable<Rules> All() { return GetRepo().GetAll(); } public static PagedList<Rules> GetPaged(string sortBy, int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<Rules> GetPaged(string sortBy, int pageIndex, int pageSize) { return GetRepo().GetPaged(sortBy, pageIndex, pageSize); } public static PagedList<Rules> GetPaged(int pageIndex, int pageSize,string connectionString, string providerName) { return GetRepo(connectionString,providerName).GetPaged(pageIndex, pageSize); } public static PagedList<Rules> GetPaged(int pageIndex, int pageSize) { return GetRepo().GetPaged(pageIndex, pageSize); } public string KeyName() { return "rule_id"; } public object KeyValue() { return this.rule_id; } public void SetKeyValue(object value) { if (value != null && value!=DBNull.Value) { var settable = value.ChangeTypeTo<string>(); this.GetType().GetProperty(this.KeyName()).SetValue(this, settable, null); } } public override string ToString(){ var sb = new StringBuilder(); sb.Append("Id=" + Id + "; "); sb.Append("rule_id=" + rule_id + "; "); sb.Append("rule_name=" + rule_name + "; "); sb.Append("rules=" + rules + "; "); sb.Append("daysinmonth=" + daysinmonth + "; "); sb.Append("hoursinday=" + hoursinday + "; "); sb.Append("ot_rate=" + ot_rate + "; "); sb.Append("sun_rate=" + sun_rate + "; "); sb.Append("hd_rate=" + hd_rate + "; "); sb.Append("restdatemethod=" + restdatemethod + "; "); sb.Append("sun=" + sun + "; "); sb.Append("sunbegin=" + sunbegin + "; "); sb.Append("sunend=" + sunend + "; "); sb.Append("sat=" + sat + "; "); sb.Append("satbegin=" + satbegin + "; "); sb.Append("satend=" + satend + "; "); sb.Append("vrestdate=" + vrestdate + "; "); sb.Append("vrestbegtime=" + vrestbegtime + "; "); sb.Append("vrestendtime=" + vrestendtime + "; "); sb.Append("memo=" + memo + "; "); sb.Append("IsAllowances=" + IsAllowances + "; "); sb.Append("SatOutTime=" + SatOutTime + "; "); sb.Append("MonInTime=" + MonInTime + "; "); sb.Append("FriOutTime=" + FriOutTime + "; "); sb.Append("HolInTime=" + HolInTime + "; "); sb.Append("HolOutTime=" + HolOutTime + "; "); return sb.ToString(); } public override bool Equals(object obj){ if(obj.GetType()==typeof(Rules)){ Rules compare=(Rules)obj; return compare.KeyValue()==this.KeyValue(); }else{ return base.Equals(obj); } } public string DescriptorValue() { return this.rule_id.ToString(); } public string DescriptorColumn() { return "rule_id"; } public static string GetKeyColumn() { return "rule_id"; } public static string GetDescriptorColumn() { return "rule_id"; } #region ' Foreign Keys ' #endregion int _Id; /// <summary> /// /// </summary> public int Id { get { return _Id; } set { if(_Id!=value || _isLoaded){ _Id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="Id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _rule_id; /// <summary> /// /// </summary> [SubSonicPrimaryKey] public string rule_id { get { return _rule_id; } set { if(_rule_id!=value || _isLoaded){ _rule_id=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="rule_id"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _rule_name; /// <summary> /// /// </summary> public string rule_name { get { return _rule_name; } set { if(_rule_name!=value || _isLoaded){ _rule_name=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="rule_name"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _rules; /// <summary> /// /// </summary> public string rules { get { return _rules; } set { if(_rules!=value || _isLoaded){ _rules=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="rules"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal _daysinmonth; /// <summary> /// /// </summary> public decimal daysinmonth { get { return _daysinmonth; } set { if(_daysinmonth!=value || _isLoaded){ _daysinmonth=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="daysinmonth"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal _hoursinday; /// <summary> /// /// </summary> public decimal hoursinday { get { return _hoursinday; } set { if(_hoursinday!=value || _isLoaded){ _hoursinday=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hoursinday"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _ot_rate; /// <summary> /// /// </summary> public decimal? ot_rate { get { return _ot_rate; } set { if(_ot_rate!=value || _isLoaded){ _ot_rate=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="ot_rate"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _sun_rate; /// <summary> /// /// </summary> public decimal? sun_rate { get { return _sun_rate; } set { if(_sun_rate!=value || _isLoaded){ _sun_rate=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="sun_rate"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } decimal? _hd_rate; /// <summary> /// /// </summary> public decimal? hd_rate { get { return _hd_rate; } set { if(_hd_rate!=value || _isLoaded){ _hd_rate=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="hd_rate"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short _restdatemethod; /// <summary> /// /// </summary> public short restdatemethod { get { return _restdatemethod; } set { if(_restdatemethod!=value || _isLoaded){ _restdatemethod=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="restdatemethod"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _sun; /// <summary> /// /// </summary> public short? sun { get { return _sun; } set { if(_sun!=value || _isLoaded){ _sun=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="sun"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _sunbegin; /// <summary> /// /// </summary> public DateTime? sunbegin { get { return _sunbegin; } set { if(_sunbegin!=value || _isLoaded){ _sunbegin=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="sunbegin"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _sunend; /// <summary> /// /// </summary> public DateTime? sunend { get { return _sunend; } set { if(_sunend!=value || _isLoaded){ _sunend=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="sunend"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } short? _sat; /// <summary> /// /// </summary> public short? sat { get { return _sat; } set { if(_sat!=value || _isLoaded){ _sat=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="sat"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _satbegin; /// <summary> /// /// </summary> public DateTime? satbegin { get { return _satbegin; } set { if(_satbegin!=value || _isLoaded){ _satbegin=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="satbegin"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _satend; /// <summary> /// /// </summary> public DateTime? satend { get { return _satend; } set { if(_satend!=value || _isLoaded){ _satend=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="satend"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _vrestdate; /// <summary> /// /// </summary> public string vrestdate { get { return _vrestdate; } set { if(_vrestdate!=value || _isLoaded){ _vrestdate=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="vrestdate"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _vrestbegtime; /// <summary> /// /// </summary> public DateTime? vrestbegtime { get { return _vrestbegtime; } set { if(_vrestbegtime!=value || _isLoaded){ _vrestbegtime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="vrestbegtime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _vrestendtime; /// <summary> /// /// </summary> public DateTime? vrestendtime { get { return _vrestendtime; } set { if(_vrestendtime!=value || _isLoaded){ _vrestendtime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="vrestendtime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } string _memo; /// <summary> /// /// </summary> public string memo { get { return _memo; } set { if(_memo!=value || _isLoaded){ _memo=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="memo"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } byte _IsAllowances; /// <summary> /// /// </summary> public byte IsAllowances { get { return _IsAllowances; } set { if(_IsAllowances!=value || _isLoaded){ _IsAllowances=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="IsAllowances"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _SatOutTime; /// <summary> /// /// </summary> public DateTime? SatOutTime { get { return _SatOutTime; } set { if(_SatOutTime!=value || _isLoaded){ _SatOutTime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="SatOutTime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _MonInTime; /// <summary> /// /// </summary> public DateTime? MonInTime { get { return _MonInTime; } set { if(_MonInTime!=value || _isLoaded){ _MonInTime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="MonInTime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _FriOutTime; /// <summary> /// /// </summary> public DateTime? FriOutTime { get { return _FriOutTime; } set { if(_FriOutTime!=value || _isLoaded){ _FriOutTime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="FriOutTime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _HolInTime; /// <summary> /// /// </summary> public DateTime? HolInTime { get { return _HolInTime; } set { if(_HolInTime!=value || _isLoaded){ _HolInTime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="HolInTime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } DateTime? _HolOutTime; /// <summary> /// /// </summary> public DateTime? HolOutTime { get { return _HolOutTime; } set { if(_HolOutTime!=value || _isLoaded){ _HolOutTime=value; var col=tbl.Columns.SingleOrDefault(x=>x.Name=="HolOutTime"); if(col!=null){ if(!_dirtyColumns.Any(x=>x.Name==col.Name) && _isLoaded){ _dirtyColumns.Add(col); } } OnChanged(); } } } public DbCommand GetUpdateCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToUpdateQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetInsertCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToInsertQuery(_db.Provider).GetCommand().ToDbCommand(); } public DbCommand GetDeleteCommand() { if(TestMode) return _db.DataProvider.CreateCommand(); else return this.ToDeleteQuery(_db.Provider).GetCommand().ToDbCommand(); } public void Update(){ Update(_db.DataProvider); } public void Update(IDataProvider provider){ if(this._dirtyColumns.Count>0){ _repo.Update(this,provider); _dirtyColumns.Clear(); } OnSaved(); } public void Add(){ Add(_db.DataProvider); } public void Add(IDataProvider provider){ var key=KeyValue(); if(key==null){ var newKey=_repo.Add(this,provider); this.SetKeyValue(newKey); }else{ _repo.Add(this,provider); } SetIsNew(false); OnSaved(); } public void Save() { Save(_db.DataProvider); } public void Save(IDataProvider provider) { if (_isNew) { Add(provider); } else { Update(provider); } } public void Delete(IDataProvider provider) { _repo.Delete(KeyValue()); } public void Delete() { Delete(_db.DataProvider); } public static void Delete(Expression<Func<Rules, bool>> expression) { var repo = GetRepo(); repo.DeleteMany(expression); } public void Load(IDataReader rdr) { Load(rdr, true); } public void Load(IDataReader rdr, bool closeReader) { if (rdr.Read()) { try { rdr.Load(this); SetIsNew(false); SetIsLoaded(true); } catch { SetIsLoaded(false); throw; } }else{ SetIsLoaded(false); } if (closeReader) rdr.Dispose(); } } }
using System; using System.Linq; using Eto.Drawing; using Eto.Forms; using swi = System.Windows.Input; using swm = System.Windows.Media; using sw = System.Windows; using sp = System.Printing; using swc = System.Windows.Controls; using swmi = System.Windows.Media.Imaging; using swd = System.Windows.Documents; using Eto.Wpf.Drawing; namespace Eto.Wpf { public static class WpfConversions { public const float WheelDelta = 120f; public static readonly sw.Size PositiveInfinitySize = new sw.Size(double.PositiveInfinity, double.PositiveInfinity); public static readonly sw.Size ZeroSize = new sw.Size(0, 0); public static swm.Color ToWpf(this Color value) { return swm.Color.FromArgb((byte)(value.A * byte.MaxValue), (byte)(value.R * byte.MaxValue), (byte)(value.G * byte.MaxValue), (byte)(value.B * byte.MaxValue)); } public static swm.Brush ToWpfBrush(this Color value, swm.Brush brush = null) { var solidBrush = brush as swm.SolidColorBrush; if (solidBrush == null || solidBrush.IsSealed) { solidBrush = new swm.SolidColorBrush(); } solidBrush.Color = value.ToWpf(); return solidBrush; } public static Color ToEto(this swm.Color value) { return new Color { A = value.A / 255f, R = value.R / 255f, G = value.G / 255f, B = value.B / 255f }; } public static Color ToEtoColor(this swm.Brush brush) { var solidBrush = brush as swm.SolidColorBrush; if (solidBrush != null) return solidBrush.Color.ToEto(); return Colors.Transparent; } public static Padding ToEto(this sw.Thickness value) { return new Padding((int)value.Left, (int)value.Top, (int)value.Right, (int)value.Bottom); } public static sw.Thickness ToWpf(this Padding value) { return new sw.Thickness(value.Left, value.Top, value.Right, value.Bottom); } public static Rectangle ToEto(this sw.Rect value) { if (value.IsEmpty) return Rectangle.Empty; return new Rectangle((int)value.X, (int)value.Y, (int)value.Width, (int)value.Height); } public static RectangleF ToEtoF(this sw.Rect value) { if (value.IsEmpty) return RectangleF.Empty; return new RectangleF((float)value.X, (float)value.Y, (float)value.Width, (float)value.Height); } public static sw.Rect ToWpf(this Rectangle value) { return new sw.Rect(value.X, value.Y, value.Width, value.Height); } public static sw.Int32Rect ToWpfInt32(this Rectangle value) { return new sw.Int32Rect(value.X, value.Y, value.Width, value.Height); } public static sw.Rect ToWpf(this RectangleF value) { return new sw.Rect(value.X, value.Y, value.Width, value.Height); } public static SizeF ToEto(this sw.Size value) { return new SizeF((float)value.Width, (float)value.Height); } public static Size ToEtoSize(this sw.Size value) { return new Size((int)(double.IsNaN(value.Width) ? -1 : value.Width), (int)(double.IsNaN(value.Height) ? -1 : value.Height)); } public static sw.Size ToWpf(this Size value) { return new sw.Size(value.Width == -1 ? double.NaN : value.Width, value.Height == -1 ? double.NaN : value.Height); } public static sw.Size ToWpf(this SizeF value) { return new sw.Size(value.Width, value.Height); } public static PointF ToEto(this sw.Point value) { return new PointF((float)value.X, (float)value.Y); } public static Point ToEtoPoint(this sw.Point value) { return new Point((int)value.X, (int)value.Y); } public static sw.Point ToWpf(this Point value) { return new sw.Point(value.X, value.Y); } public static sw.Point ToWpf(this PointF value) { return new sw.Point(value.X, value.Y); } public static KeyEventArgs ToEto(this swi.KeyEventArgs e, KeyEventType keyType) { var key = e.Key.ToEtoWithModifier(swi.Keyboard.Modifiers); return new KeyEventArgs(key, keyType) { Handled = e.Handled }; } public static MouseEventArgs ToEto(this swi.MouseButtonEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.ChangedButton == swi.MouseButton.Left && e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.ChangedButton == swi.MouseButton.Right && e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.ChangedButton == swi.MouseButton.Middle && e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = swi.Keyboard.Modifiers.ToEto(); var location = e.GetPosition(control).ToEto(); return new MouseEventArgs(buttons, modifiers, location); } public static MouseEventArgs ToEto(this swi.MouseEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = swi.Keyboard.Modifiers.ToEto(); var location = e.GetPosition(control).ToEto(); return new MouseEventArgs(buttons, modifiers, location); } public static MouseEventArgs ToEto(this swi.MouseWheelEventArgs e, sw.IInputElement control, swi.MouseButtonState buttonState = swi.MouseButtonState.Pressed) { var buttons = MouseButtons.None; if (e.LeftButton == buttonState) buttons |= MouseButtons.Primary; if (e.RightButton == buttonState) buttons |= MouseButtons.Alternate; if (e.MiddleButton == buttonState) buttons |= MouseButtons.Middle; var modifiers = swi.Keyboard.Modifiers.ToEto(); var location = e.GetPosition(control).ToEto(); var delta = new SizeF(0, (float)e.Delta / WheelDelta); return new MouseEventArgs(buttons, modifiers, location, delta); } public static swm.BitmapScalingMode ToWpf(this ImageInterpolation value) { switch (value) { case ImageInterpolation.Default: return swm.BitmapScalingMode.Unspecified; case ImageInterpolation.None: return swm.BitmapScalingMode.NearestNeighbor; case ImageInterpolation.Low: return swm.BitmapScalingMode.LowQuality; case ImageInterpolation.Medium: return swm.BitmapScalingMode.HighQuality; case ImageInterpolation.High: return swm.BitmapScalingMode.HighQuality; default: throw new NotSupportedException(); } } public static ImageInterpolation ToEto(this swm.BitmapScalingMode value) { switch (value) { case swm.BitmapScalingMode.HighQuality: return ImageInterpolation.High; case swm.BitmapScalingMode.LowQuality: return ImageInterpolation.Low; case swm.BitmapScalingMode.NearestNeighbor: return ImageInterpolation.None; case swm.BitmapScalingMode.Unspecified: return ImageInterpolation.Default; default: throw new NotSupportedException(); } } public static sp.PageOrientation ToSP(this PageOrientation value) { switch (value) { case PageOrientation.Portrait: return sp.PageOrientation.Portrait; case PageOrientation.Landscape: return sp.PageOrientation.Landscape; default: throw new NotSupportedException(); } } public static PageOrientation ToEto(this sp.PageOrientation? value) { if (value == null) return PageOrientation.Portrait; switch (value.Value) { case sp.PageOrientation.Landscape: return PageOrientation.Landscape; case sp.PageOrientation.Portrait: return PageOrientation.Portrait; default: throw new NotSupportedException(); } } public static swc.PageRange ToPageRange(this Range<int> range) { return new swc.PageRange(range.Start, range.End); } public static Range<int> ToEto(this swc.PageRange range) { return new Range<int>(range.PageFrom, range.PageTo); } public static swc.PageRangeSelection ToSWC(this PrintSelection value) { switch (value) { case PrintSelection.AllPages: return swc.PageRangeSelection.AllPages; case PrintSelection.SelectedPages: return swc.PageRangeSelection.UserPages; default: throw new NotSupportedException(); } } public static PrintSelection ToEto(this swc.PageRangeSelection value) { switch (value) { case swc.PageRangeSelection.AllPages: return PrintSelection.AllPages; case swc.PageRangeSelection.UserPages: return PrintSelection.SelectedPages; default: throw new NotSupportedException(); } } public static Size GetSize(this sw.FrameworkElement element) { if (!double.IsNaN(element.ActualWidth) && !double.IsNaN(element.ActualHeight)) return new Size((int)element.ActualWidth, (int)element.ActualHeight); return new Size((int)(double.IsNaN(element.Width) ? -1 : element.Width), (int)(double.IsNaN(element.Height) ? -1 : element.Height)); } public static void SetSize(this sw.FrameworkElement element, Size size) { element.Width = size.Width == -1 ? double.NaN : size.Width; element.Height = size.Height == -1 ? double.NaN : size.Height; } public static void SetSize(this sw.FrameworkElement element, sw.Size size) { element.Width = size.Width; element.Height = size.Height; } public static FontStyle Convert(sw.FontStyle fontStyle, sw.FontWeight fontWeight) { var style = FontStyle.None; if (fontStyle == sw.FontStyles.Italic) style |= FontStyle.Italic; if (fontStyle == sw.FontStyles.Oblique) style |= FontStyle.Italic; if (fontWeight == sw.FontWeights.Bold) style |= FontStyle.Bold; return style; } public static FontDecoration Convert(sw.TextDecorationCollection decorations) { var decoration = FontDecoration.None; if (decorations != null) { if (sw.TextDecorations.Underline.All(decorations.Contains)) decoration |= FontDecoration.Underline; if (sw.TextDecorations.Strikethrough.All(decorations.Contains)) decoration |= FontDecoration.Strikethrough; } return decoration; } public static Bitmap ToEto(this swmi.BitmapSource bitmap) { return new Bitmap(new BitmapHandler(bitmap)); } public static swmi.BitmapSource ToWpf(this Image image, int? size = null) { if (image == null) return null; var imageHandler = image.Handler as IWpfImage; if (imageHandler != null) return imageHandler.GetImageClosestToSize(size); return image.ControlObject as swmi.BitmapSource; } public static swc.Image ToWpfImage(this Image image, int? size = null) { var source = image.ToWpf(size); if (source == null) return null; var swcImage = new swc.Image { Source = source }; if (size != null) { swcImage.MaxWidth = size.Value; swcImage.MaxHeight = size.Value; } return swcImage; } public static swm.Pen ToWpf(this Pen pen, bool clone = false) { var p = (swm.Pen)pen.ControlObject; if (clone) p = p.Clone(); return p; } public static swm.PenLineJoin ToWpf(this PenLineJoin value) { switch (value) { case PenLineJoin.Miter: return swm.PenLineJoin.Miter; case PenLineJoin.Bevel: return swm.PenLineJoin.Bevel; case PenLineJoin.Round: return swm.PenLineJoin.Round; default: throw new NotSupportedException(); } } public static PenLineJoin ToEto(this swm.PenLineJoin value) { switch (value) { case swm.PenLineJoin.Bevel: return PenLineJoin.Bevel; case swm.PenLineJoin.Miter: return PenLineJoin.Miter; case swm.PenLineJoin.Round: return PenLineJoin.Round; default: throw new NotSupportedException(); } } public static swm.PenLineCap ToWpf(this PenLineCap value) { switch (value) { case PenLineCap.Butt: return swm.PenLineCap.Flat; case PenLineCap.Round: return swm.PenLineCap.Round; case PenLineCap.Square: return swm.PenLineCap.Square; default: throw new NotSupportedException(); } } public static PenLineCap ToEto(this swm.PenLineCap value) { switch (value) { case swm.PenLineCap.Flat: return PenLineCap.Butt; case swm.PenLineCap.Round: return PenLineCap.Round; case swm.PenLineCap.Square: return PenLineCap.Square; default: throw new NotSupportedException(); } } public static swm.Brush ToWpf(this Brush brush, bool clone = false) { var b = (swm.Brush)brush.ControlObject; if (clone) b = b.Clone(); return b; } public static swm.Matrix ToWpf(this IMatrix matrix) { return (swm.Matrix)matrix.ControlObject; } public static swm.Transform ToWpfTransform(this IMatrix matrix) { return new swm.MatrixTransform(matrix.ToWpf()); } public static IMatrix ToEtoMatrix(this swm.Transform transform) { return new MatrixHandler(transform.Value); } public static swm.PathGeometry ToWpf(this IGraphicsPath path) { return (swm.PathGeometry)path.ControlObject; } public static swm.GradientSpreadMethod ToWpf(this GradientWrapMode wrap) { switch (wrap) { case GradientWrapMode.Reflect: return swm.GradientSpreadMethod.Reflect; case GradientWrapMode.Repeat: return swm.GradientSpreadMethod.Repeat; case GradientWrapMode.Pad: return swm.GradientSpreadMethod.Pad; default: throw new NotSupportedException(); } } public static GradientWrapMode ToEto(this swm.GradientSpreadMethod spread) { switch (spread) { case swm.GradientSpreadMethod.Reflect: return GradientWrapMode.Reflect; case swm.GradientSpreadMethod.Repeat: return GradientWrapMode.Repeat; case swm.GradientSpreadMethod.Pad: return GradientWrapMode.Pad; default: throw new NotSupportedException(); } } public static WindowStyle ToEto(this sw.WindowStyle style) { switch (style) { case sw.WindowStyle.None: return WindowStyle.None; case sw.WindowStyle.ThreeDBorderWindow: return WindowStyle.Default; default: throw new NotSupportedException(); } } public static sw.WindowStyle ToWpf(this WindowStyle style) { switch (style) { case WindowStyle.None: return sw.WindowStyle.None; case WindowStyle.Default: return sw.WindowStyle.ThreeDBorderWindow; default: throw new NotSupportedException(); } } public static CalendarMode ToEto(this swc.CalendarSelectionMode mode) { switch (mode) { case System.Windows.Controls.CalendarSelectionMode.SingleDate: return CalendarMode.Single; case System.Windows.Controls.CalendarSelectionMode.SingleRange: return CalendarMode.Range; case System.Windows.Controls.CalendarSelectionMode.MultipleRange: case System.Windows.Controls.CalendarSelectionMode.None: default: throw new NotSupportedException(); } } public static swc.CalendarSelectionMode ToWpf(this CalendarMode mode) { switch (mode) { case CalendarMode.Single: return swc.CalendarSelectionMode.SingleDate; case CalendarMode.Range: return swc.CalendarSelectionMode.SingleRange; default: throw new NotSupportedException(); } } public static TextAlignment ToEto(this sw.HorizontalAlignment align) { switch (align) { case sw.HorizontalAlignment.Left: return TextAlignment.Left; case sw.HorizontalAlignment.Right: return TextAlignment.Right; case sw.HorizontalAlignment.Center: return TextAlignment.Center; default: throw new NotSupportedException(); } } public static sw.HorizontalAlignment ToWpf(this TextAlignment align) { switch (align) { case TextAlignment.Center: return sw.HorizontalAlignment.Center; case TextAlignment.Left: return sw.HorizontalAlignment.Left; case TextAlignment.Right: return sw.HorizontalAlignment.Right; default: throw new NotSupportedException(); } } public static sw.TextAlignment ToWpfTextAlignment(this TextAlignment align) { switch (align) { case TextAlignment.Center: return sw.TextAlignment.Center; case TextAlignment.Left: return sw.TextAlignment.Left; case TextAlignment.Right: return sw.TextAlignment.Right; default: throw new NotSupportedException(); } } public static VerticalAlignment ToEto(this sw.VerticalAlignment align) { switch (align) { case sw.VerticalAlignment.Top: return VerticalAlignment.Top; case sw.VerticalAlignment.Bottom: return VerticalAlignment.Bottom; case sw.VerticalAlignment.Center: return VerticalAlignment.Center; case sw.VerticalAlignment.Stretch: return VerticalAlignment.Stretch; default: throw new NotSupportedException(); } } public static sw.VerticalAlignment ToWpf(this VerticalAlignment align) { switch (align) { case VerticalAlignment.Top: return sw.VerticalAlignment.Top; case VerticalAlignment.Bottom: return sw.VerticalAlignment.Bottom; case VerticalAlignment.Center: return sw.VerticalAlignment.Center; case VerticalAlignment.Stretch: return sw.VerticalAlignment.Stretch; default: throw new NotSupportedException(); } } public static Font SetEtoFont(this swc.Control control, Font font, Action<sw.TextDecorationCollection> setDecorations = null) { if (control == null) return font; if (font != null) { ((FontHandler)font.Handler).Apply(control, setDecorations); } else { control.SetValue(swc.Control.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); } return font; } public static Font SetEtoFont(this swd.TextRange control, Font font) { if (control == null) return font; if (font != null) { ((FontHandler)font.Handler).Apply(control); } else { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.TextElement.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); control.ApplyPropertyValue(swd.Inline.TextDecorationsProperty, new sw.TextDecorationCollection()); } return font; } public static FontFamily SetEtoFamily(this swd.TextRange control, FontFamily fontFamily) { if (control == null) return fontFamily; if (fontFamily != null) { ((FontFamilyHandler)fontFamily.Handler).Apply(control); } else { control.ApplyPropertyValue(swd.TextElement.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); } return fontFamily; } public static Font SetEtoFont(this swc.TextBlock control, Font font, Action<sw.TextDecorationCollection> setDecorations = null) { if (control == null) return font; if (font != null) { ((FontHandler)font.Handler).Apply(control, setDecorations); } else { control.SetValue(swc.Control.FontFamilyProperty, swc.Control.FontFamilyProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontStyleProperty, swc.Control.FontStyleProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontWeightProperty, swc.Control.FontWeightProperty.DefaultMetadata.DefaultValue); control.SetValue(swc.Control.FontSizeProperty, swc.Control.FontSizeProperty.DefaultMetadata.DefaultValue); } return font; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; using System.Web.Http; using System.Web.Http.Description; using System.Xml.Serialization; using Newtonsoft.Json; namespace GuildfordBoroughCouncil.Address.Api.Areas.HelpPage.ModelDescriptions { /// <summary> /// Generates model descriptions for given types. /// </summary> public class ModelDescriptionGenerator { // Modify this to support more data annotation attributes. private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>> { { typeof(RequiredAttribute), a => "Required" }, { typeof(RangeAttribute), a => { RangeAttribute range = (RangeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum); } }, { typeof(MaxLengthAttribute), a => { MaxLengthAttribute maxLength = (MaxLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length); } }, { typeof(MinLengthAttribute), a => { MinLengthAttribute minLength = (MinLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length); } }, { typeof(StringLengthAttribute), a => { StringLengthAttribute strLength = (StringLengthAttribute)a; return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength); } }, { typeof(DataTypeAttribute), a => { DataTypeAttribute dataType = (DataTypeAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString()); } }, { typeof(RegularExpressionAttribute), a => { RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a; return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern); } }, }; // Modify this to add more default documentations. private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string> { { typeof(Int16), "integer" }, { typeof(Int32), "integer" }, { typeof(Int64), "integer" }, { typeof(UInt16), "unsigned integer" }, { typeof(UInt32), "unsigned integer" }, { typeof(UInt64), "unsigned integer" }, { typeof(Byte), "byte" }, { typeof(Char), "character" }, { typeof(SByte), "signed byte" }, { typeof(Uri), "URI" }, { typeof(Single), "decimal number" }, { typeof(Double), "decimal number" }, { typeof(Decimal), "decimal number" }, { typeof(String), "string" }, { typeof(Guid), "globally unique identifier" }, { typeof(TimeSpan), "time interval" }, { typeof(DateTime), "date" }, { typeof(DateTimeOffset), "date" }, { typeof(Boolean), "boolean" }, }; private Lazy<IModelDocumentationProvider> _documentationProvider; public ModelDescriptionGenerator(HttpConfiguration config) { if (config == null) { throw new ArgumentNullException("config"); } _documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider); GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase); } public Dictionary<string, ModelDescription> GeneratedModels { get; private set; } private IModelDocumentationProvider DocumentationProvider { get { return _documentationProvider.Value; } } public ModelDescription GetOrCreateModelDescription(Type modelType) { if (modelType == null) { throw new ArgumentNullException("modelType"); } Type underlyingType = Nullable.GetUnderlyingType(modelType); if (underlyingType != null) { modelType = underlyingType; } ModelDescription modelDescription; string modelName = ModelNameHelper.GetModelName(modelType); if (GeneratedModels.TryGetValue(modelName, out modelDescription)) { if (modelType != modelDescription.ModelType) { throw new InvalidOperationException( String.Format( CultureInfo.CurrentCulture, "A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " + "Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.", modelName, modelDescription.ModelType.FullName, modelType.FullName)); } return modelDescription; } if (DefaultTypeDocumentation.ContainsKey(modelType)) { return GenerateSimpleTypeModelDescription(modelType); } if (modelType.IsEnum) { return GenerateEnumTypeModelDescription(modelType); } if (modelType.IsGenericType) { Type[] genericArguments = modelType.GetGenericArguments(); if (genericArguments.Length == 1) { Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments); if (enumerableType.IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, genericArguments[0]); } } if (genericArguments.Length == 2) { Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments); if (dictionaryType.IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]); } Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments); if (keyValuePairType.IsAssignableFrom(modelType)) { return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]); } } } if (modelType.IsArray) { Type elementType = modelType.GetElementType(); return GenerateCollectionModelDescription(modelType, elementType); } if (modelType == typeof(NameValueCollection)) { return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string)); } if (typeof(IDictionary).IsAssignableFrom(modelType)) { return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object)); } if (typeof(IEnumerable).IsAssignableFrom(modelType)) { return GenerateCollectionModelDescription(modelType, typeof(object)); } return GenerateComplexTypeModelDescription(modelType); } // Change this to provide different name for the member. private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute) { JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>(); if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName)) { return jsonProperty.PropertyName; } if (hasDataContractAttribute) { DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>(); if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name)) { return dataMember.Name; } } return member.Name; } private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute) { JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>(); XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>(); IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>(); NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>(); ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>(); bool hasMemberAttribute = member.DeclaringType.IsEnum ? member.GetCustomAttribute<EnumMemberAttribute>() != null : member.GetCustomAttribute<DataMemberAttribute>() != null; // Display member only if all the followings are true: // no JsonIgnoreAttribute // no XmlIgnoreAttribute // no IgnoreDataMemberAttribute // no NonSerializedAttribute // no ApiExplorerSettingsAttribute with IgnoreApi set to true // no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute return jsonIgnore == null && xmlIgnore == null && ignoreDataMember == null && nonSerialized == null && (apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) && (!hasDataContractAttribute || hasMemberAttribute); } private string CreateDefaultDocumentation(Type type) { string documentation; if (DefaultTypeDocumentation.TryGetValue(type, out documentation)) { return documentation; } if (DocumentationProvider != null) { documentation = DocumentationProvider.GetDocumentation(type); } return documentation; } private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel) { List<ParameterAnnotation> annotations = new List<ParameterAnnotation>(); IEnumerable<Attribute> attributes = property.GetCustomAttributes(); foreach (Attribute attribute in attributes) { Func<object, string> textGenerator; if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator)) { annotations.Add( new ParameterAnnotation { AnnotationAttribute = attribute, Documentation = textGenerator(attribute) }); } } // Rearrange the annotations annotations.Sort((x, y) => { // Special-case RequiredAttribute so that it shows up on top if (x.AnnotationAttribute is RequiredAttribute) { return -1; } if (y.AnnotationAttribute is RequiredAttribute) { return 1; } // Sort the rest based on alphabetic order of the documentation return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase); }); foreach (ParameterAnnotation annotation in annotations) { propertyModel.Annotations.Add(annotation); } } private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType) { ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType); if (collectionModelDescription != null) { return new CollectionModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, ElementDescription = collectionModelDescription }; } return null; } private ModelDescription GenerateComplexTypeModelDescription(Type modelType) { ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(complexModelDescription.Name, complexModelDescription); bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (ShouldDisplayMember(property, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(property, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(property); } GenerateAnnotations(property, propertyModel); complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType); } } FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance); foreach (FieldInfo field in fields) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { ParameterDescription propertyModel = new ParameterDescription { Name = GetMemberName(field, hasDataContractAttribute) }; if (DocumentationProvider != null) { propertyModel.Documentation = DocumentationProvider.GetDocumentation(field); } complexModelDescription.Properties.Add(propertyModel); propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType); } } return complexModelDescription; } private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new DictionaryModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType) { EnumTypeModelDescription enumDescription = new EnumTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null; foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static)) { if (ShouldDisplayMember(field, hasDataContractAttribute)) { EnumValueDescription enumValue = new EnumValueDescription { Name = field.Name, Value = field.GetRawConstantValue().ToString() }; if (DocumentationProvider != null) { enumValue.Documentation = DocumentationProvider.GetDocumentation(field); } enumDescription.Values.Add(enumValue); } } GeneratedModels.Add(enumDescription.Name, enumDescription); return enumDescription; } private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType) { ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType); ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType); return new KeyValuePairModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, KeyModelDescription = keyModelDescription, ValueModelDescription = valueModelDescription }; } private ModelDescription GenerateSimpleTypeModelDescription(Type modelType) { SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription { Name = ModelNameHelper.GetModelName(modelType), ModelType = modelType, Documentation = CreateDefaultDocumentation(modelType) }; GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription); return simpleModelDescription; } } }
/* * ContextMenu.cs - Implementation of the * "System.Windows.Forms.ContextMenu" class. * * Copyright (C) 2004 Neil Cawse. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace System.Windows.Forms { using System.Drawing; using System.Windows.Forms.Themes; using System.ComponentModel; #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [DefaultEvent("Popup")] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public class ContextMenu : Menu { // Internal state. private RightToLeft rightToLeft; private Control sourceControl; private ContextMenu nextPopupMenu; internal PopupControl popupControl; private Control associatedControl; private int currentMouseItem; internal event MouseEventHandler MouseMove; internal event MouseEventHandler MouseDown; // Constructors. public ContextMenu() : base(null) { rightToLeft = RightToLeft.Inherit; } public ContextMenu(MenuItem[] items) : base(items) { rightToLeft = RightToLeft.Inherit; } // Get or set the right-to-left property. #if CONFIG_COMPONENT_MODEL [Localizable(true)] #endif // CONFIG_COMPONENT_MODEL public virtual RightToLeft RightToLeft { get { if(rightToLeft != RightToLeft.Inherit) { return rightToLeft; } else if(sourceControl != null) { return sourceControl.RightToLeft; } else { return RightToLeft.No; } } set { if(rightToLeft != value) { SuppressUpdates(); rightToLeft = value; AllowUpdates(); } } } // Get the control that owns this context menu. #if CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] #endif // CONFIG_COMPONENT_MODEL || CONFIG_EXTENDED_DIAGNOSTICS public Control SourceControl { get { return sourceControl; } } protected virtual void OnPopup(EventArgs e) { if (Popup != null) { this.Popup(this, e); } } // Show this context menu at the specified control-relative co-ordinates. public void Show(Control control, Point pos) { associatedControl = control; currentMouseItem = -1; // Not over anything popupControl = new PopupControl(); // We need the following events from popupControl. popupControl.MouseMove +=new MouseEventHandler(OnMouseMove); popupControl.MouseDown +=new MouseEventHandler(OnMouseDown); popupControl.Paint +=new PaintEventHandler(popupControl_Paint); OnPopup(EventArgs.Empty); // Figure out where we need to put the popup and its size. Point pt = control.PointToScreen(new Point(0,0)); Rectangle rcWork = Screen.PrimaryScreen.WorkingArea; using (Graphics g = popupControl.CreateGraphics()) { Size size = MeasureItemBounds(g); size.Height -= 1; //align it to control if (pt.X < rcWork.Left) { pt.X += size.Width; } if (pt.X > rcWork.Right - size.Width) { pt.X -= size.Width; } if (pt.Y < rcWork.Top) { pt.Y += size.Height; } if (pt.Y > rcWork.Bottom - size.Height) { pt.Y -= size.Height; } //add offset pos pt.X += pos.X; pt.Y += pos.Y; //ensure that it is completely visible on screen if (pt.X < rcWork.Left) { pt.X = rcWork.Left; } if (pt.X > rcWork.Right - size.Width) { pt.X = rcWork.Right - size.Width; } if (pt.Y < rcWork.Top) { pt.Y = rcWork.Top; } if (pt.Y > rcWork.Bottom + size.Height) { pt.Y = rcWork.Bottom - size.Height; } popupControl.Bounds = new Rectangle( pt, size); } popupControl.Show(); } private void popupControl_Paint(Object sender, PaintEventArgs e) { Graphics g = e.Graphics; Rectangle rect = popupControl.ClientRectangle; ThemeManager.MainPainter.DrawButton (g, rect.X, rect.Y, rect.Width, rect.Height, ButtonState.Normal, SystemColors.MenuText, SystemColors.Menu, false); // Draw the menu items. int count = MenuItems.Count; for (int i = 0; i < count; i++) { DrawMenuItem(g, i, false); } } private void OnMouseDown(Object s, MouseEventArgs e) { // What item are we over? int item = ItemFromPoint(new Point(e.X, e.Y)); if (item != -1) { MenuItem menuItem = ItemSelected(item); // If there were no sub items, then we need to "PerformClick". if (menuItem.MenuItems.Count == 0) { PopDown(); menuItem.PerformClick(); } else { return; } } // Do we need to pass the mouse down along? if (MouseDown != null) { // Convert the mouse co-ordinates relative to the associated control (form). MouseDown(this, CreateParentMouseArgs(e)); } } private MenuItem ItemSelected(int item) { MenuItem menuItem = MenuItems[item]; // Remove any currently "popped up" child menus. if (nextPopupMenu != null) { nextPopupMenu.PopDown(); nextPopupMenu = null; } // If there are sub menus then show the next child menu. if (menuItem.MenuItems.Count > 0) { nextPopupMenu = new ContextMenu(menuItem.itemList); Point location = new Point(itemBounds[item].Right + 1, itemBounds[item].Y - 1); location = popupControl.PointToScreen(location); location = associatedControl.PointToClient(location); nextPopupMenu.MouseMove +=new MouseEventHandler(nextPopupMenu_MouseMove); nextPopupMenu.MouseDown +=new MouseEventHandler(nextPopupMenu_MouseDown); nextPopupMenu.Show( associatedControl, location); } return menuItem; } protected internal override void ItemSelectTimerTick(object sender, EventArgs e) { base.ItemSelectTimerTick (sender, e); if(currentMouseItem != -1) { ItemSelected(currentMouseItem); } } private void OnMouseMove(Object s, MouseEventArgs e) { // What item are we over? int newMouseItem = ItemFromPoint(new Point(e.X, e.Y)); // Dont worry if the mouse is still on the same item. if (newMouseItem != currentMouseItem) { // Draw the menu by un-highlighting the old and highlighting the new. using (Graphics g = popupControl.CreateGraphics()) { if (currentMouseItem != -1) { DrawMenuItem(g, currentMouseItem, false); } if (newMouseItem != -1) { DrawMenuItem(g, newMouseItem, true); } } currentMouseItem = newMouseItem; StartTimer(newMouseItem); } // Do we need to pass the mouse move along? if (MouseMove != null) { // Convert the mouse co-ordinates relative to the associated control (form). MouseMove(this, CreateParentMouseArgs(e)); } } // Create the correct mouse args relative to our "associated control" ie the form. private MouseEventArgs CreateParentMouseArgs(MouseEventArgs e) { // Convert the mouse co-ordinates relative to the associated control (form). Point pt = associatedControl.PointToClient(popupControl.Location); pt.X += e.X; pt.Y += e.Y; return new MouseEventArgs(e.Button, e.Clicks, pt.X, pt.Y, e.Delta); } // Create the correct mouse args relative to this popup. private MouseEventArgs CreateLocalMouseArgs(MouseEventArgs e) { // Convert the associated control (the form) mouse position to be relative to this ContextMenu. Point pt = new Point(e.X, e.Y); pt = associatedControl.PointToScreen(pt); pt.X -= popupControl.Left; pt.Y -= popupControl.Top; return new MouseEventArgs(e.Button, e.Clicks, pt.X, pt.Y, e.Delta); } // The mouse move from our child. private void nextPopupMenu_MouseMove(Object sender, MouseEventArgs e) { OnMouseMove(sender, CreateLocalMouseArgs(e)); } // The mouse down from our child. private void nextPopupMenu_MouseDown(Object sender, MouseEventArgs e) { OnMouseDown(sender, CreateLocalMouseArgs(e)); } // Calculates the position of each MenuItem, // returns the bounds of all MenuItems. private Size MeasureItemBounds(Graphics g) { Size outside = Size.Empty; itemBounds = new Rectangle[MenuItems.Count]; int y = MenuPaddingOrigin.Y; for (int i = 0; i < MenuItems.Count; i++) { MenuItem item = MenuItems[i]; int width, height; if (item.Text == "-") { height = -1; width = 0; } else { if (item.OwnerDraw) { MeasureItemEventArgs measureItem = new MeasureItemEventArgs(g, i); item.OnMeasureItem(measureItem); width = measureItem.ItemWidth; height = measureItem.ItemHeight; } else { // Do the default handling SizeF size = g.MeasureString(item.Text, SystemInformation.MenuFont); width = Size.Truncate(size).Width; height = Size.Truncate(size).Height; } } width += ItemPaddingSize.Width; Rectangle bounds = new Rectangle(MenuPaddingOrigin.X, y, 0, height + ItemPaddingSize.Height); itemBounds[i] = bounds; y += bounds.Height; if (outside.Width < width) { outside.Width = width; } } if (outside.Width < MinimumItemWidth) { outside.Width = MinimumItemWidth; } for (int i = 0; i < MenuItems.Count; i++) { itemBounds[i].Width = outside.Width; } outside.Height = y + MenuPaddingSize.Height; outside.Width += MenuPaddingSize.Width; return outside; } protected int MinimumItemWidth { get { return 100; } } // Add this main menu to a control. internal void AddToControl(Control control) { sourceControl = control; } // Remove this main menu from its owning control. internal void RemoveFromControl() { sourceControl = null; } // Event that is emitted just before the menu pops up. public event EventHandler Popup; // Pop down this context menu and its children. internal void PopDown() { if (nextPopupMenu != null) { nextPopupMenu.PopDown(); nextPopupMenu = null; } popupControl.Hide(); } }; // class ContextMenu }; // namespace System.Windows.Forms
using System; using System.Text; using System.Diagnostics; namespace NamelessInteractive.Shared.Security { public static class Converters { public static byte[] ConvertToBytes(object a_in) { if (a_in is byte) return new byte[] { (byte)a_in }; else if (a_in is short) return BitConverter.GetBytes((short)a_in); else if (a_in is ushort) return BitConverter.GetBytes((ushort)a_in); else if (a_in is char) return BitConverter.GetBytes((char)a_in); else if (a_in is int) return BitConverter.GetBytes((int)a_in); else if (a_in is uint) return BitConverter.GetBytes((uint)a_in); else if (a_in is long) return BitConverter.GetBytes((long)a_in); else if (a_in is ulong) return BitConverter.GetBytes((ulong)a_in); else if (a_in is float) return BitConverter.GetBytes((float)a_in); else if (a_in is double) return BitConverter.GetBytes((double)a_in); else if (a_in is string) return ConvertStringToBytes((string)a_in); else if (a_in is byte[]) return (byte[])((byte[])a_in).Clone(); else if (a_in.GetType().IsArray && a_in.GetType().GetElementType() == typeof(short)) return ConvertShortsToBytes((short[])a_in); else if (a_in.GetType().IsArray && a_in.GetType().GetElementType() == typeof(ushort)) return ConvertUShortsToBytes((ushort[])a_in); else if (a_in is char[]) return ConvertCharsToBytes((char[])a_in); else if (a_in.GetType().IsArray && a_in.GetType().GetElementType() == typeof(int)) return ConvertIntsToBytes((int[])a_in); else if (a_in.GetType().IsArray && a_in.GetType().GetElementType() == typeof(uint)) return ConvertUIntsToBytes((uint[])a_in); else if (a_in.GetType().IsArray && a_in.GetType().GetElementType() == typeof(long)) return ConvertLongsToBytes((long[])a_in); else if (a_in.GetType().IsArray && a_in.GetType().GetElementType() == typeof(ulong)) return ConvertULongsToBytes((ulong[])a_in); else if (a_in is float[]) return ConvertFloatsToBytes((float[])a_in); else if (a_in is double[]) return ConvertDoublesToBytes((double[])a_in); else throw new ArgumentException(); } public static uint[] ConvertBytesToUInts(byte[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 1, 4, a_index, a_length); uint[] result = new uint[a_length / 4]; ConvertBytesToUInts(a_in, a_index, a_length, result); return result; } public static void ConvertBytesToUInts(byte[] a_in, int a_index, int a_length, uint[] a_out) { Check(a_in, 1, 4, a_index, a_length); Buffer.BlockCopy(a_in, a_index, a_out, 0, a_length); } public static ulong[] ConvertBytesToULongs(byte[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 1, 8, a_index, a_length); ulong[] result = new ulong[a_length / 8]; ConvertBytesToULongs(a_in, a_index, a_length, result, 0); return result; } public static void ConvertBytesToULongs(byte[] a_in, int a_index_in, int a_length, ulong[] a_out, int a_index_out) { Check(a_in, 1, a_out, 8, a_index_in, a_length, a_index_out); Buffer.BlockCopy(a_in, a_index_in, a_out, a_index_out * 8, a_length); } public static uint[] ConvertBytesToUIntsSwapOrder(byte[] a_in, int a_index, int a_length) { Check(a_in, 1, 4, a_index, a_length); uint[] result = new uint[a_length / 4]; ConvertBytesToUIntsSwapOrder(a_in, a_index, a_length, result, 0); return result; } public static void ConvertBytesToUIntsSwapOrder(byte[] a_in, int a_index, int a_length, uint[] a_result, int a_index_out) { Check(a_in, 1, a_result, 4, a_index, a_length, a_index_out); for (int i = a_index_out; a_length > 0; a_length -= 4) { a_result[i++] = ((uint)a_in[a_index++] << 24) | ((uint)a_in[a_index++] << 16) | ((uint)a_in[a_index++] << 8) | a_in[a_index++]; } } public static ulong ConvertBytesToULongSwapOrder(byte[] a_in, int a_index) { Debug.Assert(a_index >= 0); Debug.Assert(a_index + 8 <= a_in.Length); return ((ulong)a_in[a_index++] << 56) | ((ulong)a_in[a_index++] << 48) | ((ulong)a_in[a_index++] << 40) | ((ulong)a_in[a_index++] << 32) | ((ulong)a_in[a_index++] << 24) | ((ulong)a_in[a_index++] << 16) | ((ulong)a_in[a_index++] << 8) | a_in[a_index]; } public static ulong ConvertBytesToULong(byte[] a_in, int a_index) { Debug.Assert(a_index >= 0); Debug.Assert(a_index + 8 <= a_in.Length); return BitConverter.ToUInt64(a_in, a_index); } public static uint ConvertBytesToUIntSwapOrder(byte[] a_in, int a_index) { Debug.Assert(a_index >= 0); Debug.Assert(a_index + 4 <= a_in.Length); return ((uint)a_in[a_index++] << 24) | ((uint)a_in[a_index++] << 16) | ((uint)a_in[a_index++] << 8) | a_in[a_index]; } public static uint ConvertBytesToUInt(byte[] a_in, int a_index = 0) { Debug.Assert(a_index >= 0); Debug.Assert(a_index + 4 <= a_in.Length); return (uint)a_in[a_index++] | ((uint)a_in[a_index++] << 8) | ((uint)a_in[a_index++] << 16) | ((uint)a_in[a_index] << 24); } public static ulong[] ConvertBytesToULongsSwapOrder(byte[] a_in, int a_index, int a_length) { Check(a_in, 1, 8, a_index, a_length); ulong[] result = new ulong[a_length / 8]; ConvertBytesToULongsSwapOrder(a_in, a_index, a_length, result); return result; } public static void ConvertBytesToULongsSwapOrder(byte[] a_in, int a_index, int a_length, ulong[] a_out) { Check(a_in, 1, 8, a_index, a_length); for (int i = 0; a_length > 0; a_length -= 8) { a_out[i++] = (((ulong)a_in[a_index++] << 56) | ((ulong)a_in[a_index++] << 48) | ((ulong)a_in[a_index++] << 40) | ((ulong)a_in[a_index++] << 32) | ((ulong)a_in[a_index++] << 24) | ((ulong)a_in[a_index++] << 16) | ((ulong)a_in[a_index++] << 8) | ((ulong)a_in[a_index++])); } } public static byte[] ConvertUIntsToBytesSwapOrder(uint[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 4, 1, a_index, a_length); byte[] result = new byte[a_length * 4]; for (int j = 0; a_length > 0; a_length--, a_index++) { result[j++] = (byte)(a_in[a_index] >> 24); result[j++] = (byte)(a_in[a_index] >> 16); result[j++] = (byte)(a_in[a_index] >> 8); result[j++] = (byte)a_in[a_index]; } return result; } public static byte[] ConvertUIntsToBytes(uint[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 4, 1, a_index, a_length); byte[] result = new byte[a_length * 4]; Buffer.BlockCopy(a_in, a_index * 4, result, 0, a_length * 4); return result; } public static byte[] ConvertULongsToBytes(ulong[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 8, 1, a_index, a_length); byte[] result = new byte[a_length * 8]; Buffer.BlockCopy(a_in, a_index * 8, result, 0, a_length * 8); return result; } public static byte[] ConvertULongsToBytesSwapOrder(ulong[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 8, 1, a_index, a_length); byte[] result = new byte[a_length * 8]; for (int j = 0; a_length > 0; a_length--, a_index++) { result[j++] = (byte)(a_in[a_index] >> 56); result[j++] = (byte)(a_in[a_index] >> 48); result[j++] = (byte)(a_in[a_index] >> 40); result[j++] = (byte)(a_in[a_index] >> 32); result[j++] = (byte)(a_in[a_index] >> 24); result[j++] = (byte)(a_in[a_index] >> 16); result[j++] = (byte)(a_in[a_index] >> 8); result[j++] = (byte)a_in[a_index]; } return result; } public static byte[] ConvertUIntToBytes(uint a_in) { byte[] result = new byte[4]; ConvertUIntToBytes(a_in, result, 0); return result; } public static void ConvertUIntToBytes(ulong a_in, byte[] a_out, int a_index) { Debug.Assert(a_index + 4 <= a_out.Length); Array.Copy(BitConverter.GetBytes(a_in), 0, a_out, a_index, 4); } public static byte[] ConvertULongToBytes(ulong a_in) { byte[] result = new byte[8]; ConvertULongToBytes(a_in, result, 0); return result; } public static void ConvertULongToBytes(ulong a_in, byte[] a_out, int a_index) { Debug.Assert(a_index + 8 <= a_out.Length); Array.Copy(BitConverter.GetBytes(a_in), 0, a_out, a_index, 8); } public static void ConvertULongToBytesSwapOrder(ulong a_in, byte[] a_out, int a_index) { Debug.Assert(a_index + 8 <= a_out.Length); a_out[a_index++] = (byte)(a_in >> 56); a_out[a_index++] = (byte)(a_in >> 48); a_out[a_index++] = (byte)(a_in >> 40); a_out[a_index++] = (byte)(a_in >> 32); a_out[a_index++] = (byte)(a_in >> 24); a_out[a_index++] = (byte)(a_in >> 16); a_out[a_index++] = (byte)(a_in >> 8); a_out[a_index++] = (byte)a_in; } public static byte[] ConvertStringToBytes(string a_in) { byte[] bytes = new byte[a_in.Length * sizeof(char)]; System.Buffer.BlockCopy(a_in.ToCharArray(), 0, bytes, 0, bytes.Length); return bytes; } public static byte[] ConvertStringToBytes(string a_in, Encoding a_encoding) { return a_encoding.GetBytes(a_in); } public static byte[] ConvertCharsToBytes(char[] a_in) { Check(a_in, 2, 1); byte[] bytes = new byte[a_in.Length * sizeof(char)]; System.Buffer.BlockCopy(a_in, 0, bytes, 0, bytes.Length); return bytes; } public static byte[] ConvertShortsToBytes(short[] a_in) { Check(a_in, 2, 1); byte[] result = new byte[a_in.Length * 2]; Buffer.BlockCopy(a_in, 0, result, 0, result.Length); return result; } public static byte[] ConvertUShortsToBytes(ushort[] a_in) { Check(a_in, 2, 1); byte[] result = new byte[a_in.Length * 2]; Buffer.BlockCopy(a_in, 0, result, 0, result.Length); return result; } public static byte[] ConvertIntsToBytes(int[] a_in) { Check(a_in, 4, 1); byte[] result = new byte[a_in.Length * 4]; Buffer.BlockCopy(a_in, 0, result, 0, a_in.Length * 4); return result; } public static byte[] ConvertLongsToBytes(long[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 8, 1, a_index, a_length); byte[] result = new byte[a_length * 8]; Buffer.BlockCopy(a_in, a_index * 8, result, 0, a_length * 8); return result; } public static byte[] ConvertDoublesToBytes(double[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 8, 1, a_index, a_length); byte[] result = new byte[a_length * 8]; Buffer.BlockCopy(a_in, a_index * 8, result, 0, a_length * 8); return result; } public static byte[] ConvertFloatsToBytes(float[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, 4, 1, a_index, a_length); byte[] result = new byte[a_length * 4]; Buffer.BlockCopy(a_in, a_index * 4, result, 0, a_length * 4); return result; } public static ulong[] ConvertFloatsToULongs(float[] a_in, int a_index = 0, int a_length = -1) { if (a_length == -1) a_length = a_in.Length; Check(a_in, sizeof(float), sizeof(ulong), a_index, a_length); ulong[] result = new ulong[a_length / (sizeof(ulong) / sizeof(float))]; ConvertFloatsToULongs(a_in, a_index, a_length, result, 0); return result; } public static void ConvertFloatsToULongs(float[] a_in, int a_index_in, int a_length, ulong[] a_out, int a_index_out) { Check(a_in, sizeof(float), a_out, sizeof(ulong), a_index_in, a_length, a_index_out); Buffer.BlockCopy(a_in, a_index_in, a_out, a_index_out * sizeof(ulong), a_length * sizeof(float)); } public static byte[] ConvertHexStringToBytes(string a_in) { a_in = a_in.Replace("-", ""); Debug.Assert(a_in.Length % 2 == 0); byte[] result = new byte[a_in.Length / 2]; for (int i = 0; i < result.Length; i++) result[i] = Byte.Parse(a_in.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber); return result; } public static string ConvertBytesToHexString(byte[] a_in, bool a_group = true) { string hex = BitConverter.ToString(a_in).ToUpper(); if (a_group) { Check(a_in, 1, 4); string[] ar = BitConverter.ToString(a_in).ToUpper().Split(new char[] { '-' }); hex = ""; for (int i = 0; i < ar.Length / 4; i++) { if (i != 0) hex += "-"; hex += ar[i * 4] + ar[i * 4 + 1] + ar[i * 4 + 2] + ar[i * 4 + 3]; } } else hex = hex.Replace("-", ""); return hex; } [Conditional("DEBUG")] private static void Check<I>(I[] a_in, int a_in_size, int a_out_size) { Debug.Assert((a_in.Length * a_in_size % a_out_size) == 0); } [Conditional("DEBUG")] private static void Check<I>(I[] a_in, int a_in_size, int a_out_size, int a_index, int a_length) { Debug.Assert((a_length * a_in_size % a_out_size) == 0); if (a_out_size > a_in_size) Debug.Assert((a_length % (a_out_size / a_in_size)) == 0); else Debug.Assert(a_in_size % a_out_size == 0); Debug.Assert(a_index >= 0); if (a_length > 0) Debug.Assert(a_index < a_in.Length); Debug.Assert(a_length >= 0); Debug.Assert(a_index + a_length <= a_in.Length); Debug.Assert(a_index + a_length <= a_in.Length); } [Conditional("DEBUG")] private static void Check<I, O>(I[] a_in, int a_in_size, O[] a_result, int a_out_size, int a_index_in, int a_length, int a_index_out) { Debug.Assert((a_length * a_in_size % a_out_size) == 0); if (a_out_size > a_in_size) Debug.Assert((a_length % (a_out_size / a_in_size)) == 0); Debug.Assert(a_index_in >= 0); if (a_length > 0) Debug.Assert(a_index_in < a_in.Length); Debug.Assert(a_length >= 0); Debug.Assert(a_index_in + a_length <= a_in.Length); Debug.Assert(a_index_in + a_length <= a_in.Length); Debug.Assert(a_index_out + a_result.Length >= (a_length / a_out_size)); } } }
/* * 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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Xml; using Nini.Config; using log4net; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Data; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using OpenSim.Services.Connectors.Hypergrid; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenMetaverse; namespace OpenSim.Services.GridService { public class HypergridLinker { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private static uint m_autoMappingX = 0; private static uint m_autoMappingY = 0; private static bool m_enableAutoMapping = false; protected IRegionData m_Database; protected GridService m_GridService; protected IAssetService m_AssetService; protected GatekeeperServiceConnector m_GatekeeperConnector; protected UUID m_ScopeID = UUID.Zero; // protected bool m_Check4096 = true; protected string m_MapTileDirectory = string.Empty; protected string m_ThisGatekeeper = string.Empty; protected Uri m_ThisGatekeeperURI = null; // Hyperlink regions are hyperlinks on the map public readonly Dictionary<UUID, GridRegion> m_HyperlinkRegions = new Dictionary<UUID, GridRegion>(); protected Dictionary<UUID, ulong> m_HyperlinkHandles = new Dictionary<UUID, ulong>(); protected GridRegion m_DefaultRegion; protected GridRegion DefaultRegion { get { if (m_DefaultRegion == null) { List<GridRegion> defs = m_GridService.GetDefaultRegions(m_ScopeID); if (defs != null && defs.Count > 0) m_DefaultRegion = defs[0]; else { // Get any region defs = m_GridService.GetRegionsByName(m_ScopeID, "", 1); if (defs != null && defs.Count > 0) m_DefaultRegion = defs[0]; else { // This shouldn't happen m_DefaultRegion = new GridRegion(1000, 1000); m_log.Error("[HYPERGRID LINKER]: Something is wrong with this grid. It has no regions?"); } } } return m_DefaultRegion; } } public HypergridLinker(IConfigSource config, GridService gridService, IRegionData db) { IConfig gridConfig = config.Configs["GridService"]; if (gridConfig == null) return; if (!gridConfig.GetBoolean("HypergridLinker", false)) return; m_Database = db; m_GridService = gridService; m_log.DebugFormat("[HYPERGRID LINKER]: Starting with db {0}", db.GetType()); string assetService = gridConfig.GetString("AssetService", string.Empty); Object[] args = new Object[] { config }; if (assetService != string.Empty) m_AssetService = ServerUtils.LoadPlugin<IAssetService>(assetService, args); string scope = gridConfig.GetString("ScopeID", string.Empty); if (scope != string.Empty) UUID.TryParse(scope, out m_ScopeID); // m_Check4096 = gridConfig.GetBoolean("Check4096", true); m_MapTileDirectory = gridConfig.GetString("MapTileDirectory", "maptiles"); m_ThisGatekeeper = Util.GetConfigVarFromSections<string>(config, "GatekeeperURI", new string[] { "Startup", "Hypergrid", "GridService" }, String.Empty); // Legacy. Remove soon! m_ThisGatekeeper = gridConfig.GetString("Gatekeeper", m_ThisGatekeeper); try { m_ThisGatekeeperURI = new Uri(m_ThisGatekeeper); } catch { m_log.WarnFormat("[HYPERGRID LINKER]: Malformed URL in [GridService], variable Gatekeeper = {0}", m_ThisGatekeeper); } m_GatekeeperConnector = new GatekeeperServiceConnector(m_AssetService); m_log.Debug("[HYPERGRID LINKER]: Loaded all services..."); if (!string.IsNullOrEmpty(m_MapTileDirectory)) { try { Directory.CreateDirectory(m_MapTileDirectory); } catch (Exception e) { m_log.WarnFormat("[HYPERGRID LINKER]: Could not create map tile storage directory {0}: {1}", m_MapTileDirectory, e); m_MapTileDirectory = string.Empty; } } if (MainConsole.Instance != null) { MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-region", "link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]", "Link a HyperGrid Region. Examples for <ServerURI>: http://grid.net:8002/ or http://example.org/path/foo.php", RunCommand); MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-region", "link-region <Xloc> <Yloc> <RegionIP> <RegionPort> [<RemoteRegionName>]", "Link a hypergrid region (deprecated)", RunCommand); MainConsole.Instance.Commands.AddCommand("hypergrid", false, "unlink-region", "unlink-region <local name>", "Unlink a hypergrid region", RunCommand); MainConsole.Instance.Commands.AddCommand("hypergrid", false, "link-mapping", "link-mapping [<x> <y>]", "Set local coordinate to map HG regions to", RunCommand); MainConsole.Instance.Commands.AddCommand("hypergrid", false, "show hyperlinks", "show hyperlinks", "List the HG regions", HandleShow); } } #region Link Region // from map search public GridRegion LinkRegion(UUID scopeID, string regionDescriptor) { string reason = string.Empty; int xloc = random.Next(0, Int16.MaxValue) * (int)Constants.RegionSize; return TryLinkRegionToCoords(scopeID, regionDescriptor, xloc, 0, out reason); } private static Random random = new Random(); // From the command line link-region (obsolete) and the map public GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, out string reason) { return TryLinkRegionToCoords(scopeID, mapName, xloc, yloc, UUID.Zero, out reason); } public GridRegion TryLinkRegionToCoords(UUID scopeID, string mapName, int xloc, int yloc, UUID ownerID, out string reason) { reason = string.Empty; GridRegion regInfo = null; if (!mapName.StartsWith("http")) { string host = "127.0.0.1"; string portstr; string regionName = ""; uint port = 0; string[] parts = mapName.Split(new char[] { ':' }); if (parts.Length >= 1) { host = parts[0]; } if (parts.Length >= 2) { portstr = parts[1]; //m_log.Debug("-- port = " + portstr); if (!UInt32.TryParse(portstr, out port)) regionName = parts[1]; } // always take the last one if (parts.Length >= 3) { regionName = parts[2]; } bool success = TryCreateLink(scopeID, xloc, yloc, regionName, port, host, ownerID, out regInfo, out reason); if (success) { regInfo.RegionName = mapName; return regInfo; } } else { string[] parts = mapName.Split(new char[] {' '}); string regionName = String.Empty; if (parts.Length > 1) { regionName = mapName.Substring(parts[0].Length + 1); regionName = regionName.Trim(new char[] {'"'}); } if (TryCreateLink(scopeID, xloc, yloc, regionName, 0, null, parts[0], ownerID, out regInfo, out reason)) { regInfo.RegionName = mapName; return regInfo; } } return null; } public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, UUID ownerID, out GridRegion regInfo, out string reason) { return TryCreateLink(scopeID, xloc, yloc, remoteRegionName, externalPort, externalHostName, null, ownerID, out regInfo, out reason); } public bool TryCreateLink(UUID scopeID, int xloc, int yloc, string remoteRegionName, uint externalPort, string externalHostName, string serverURI, UUID ownerID, out GridRegion regInfo, out string reason) { m_log.DebugFormat("[HYPERGRID LINKER]: Link to {0} {1}, in {2}-{3}", ((serverURI == null) ? (externalHostName + ":" + externalPort) : serverURI), remoteRegionName, xloc / Constants.RegionSize, yloc / Constants.RegionSize); reason = string.Empty; Uri uri = null; regInfo = new GridRegion(); if ( externalPort > 0) regInfo.HttpPort = externalPort; else regInfo.HttpPort = 0; if ( externalHostName != null) regInfo.ExternalHostName = externalHostName; else regInfo.ExternalHostName = "0.0.0.0"; if ( serverURI != null) { regInfo.ServerURI = serverURI; try { uri = new Uri(serverURI); regInfo.ExternalHostName = uri.Host; regInfo.HttpPort = (uint)uri.Port; } catch {} } if ( remoteRegionName != string.Empty ) regInfo.RegionName = remoteRegionName; regInfo.RegionLocX = xloc; regInfo.RegionLocY = yloc; regInfo.ScopeID = scopeID; regInfo.EstateOwner = ownerID; // Make sure we're not hyperlinking to regions on this grid! if (m_ThisGatekeeperURI != null) { if (regInfo.ExternalHostName == m_ThisGatekeeperURI.Host && regInfo.HttpPort == m_ThisGatekeeperURI.Port) { reason = "Cannot hyperlink to regions on the same grid"; return false; } } else m_log.WarnFormat("[HYPERGRID LINKER]: Please set this grid's Gatekeeper's address in [GridService]!"); // Check for free coordinates GridRegion region = m_GridService.GetRegionByPosition(regInfo.ScopeID, regInfo.RegionLocX, regInfo.RegionLocY); if (region != null) { m_log.WarnFormat("[HYPERGRID LINKER]: Coordinates {0}-{1} are already occupied by region {2} with uuid {3}", regInfo.RegionLocX / Constants.RegionSize, regInfo.RegionLocY / Constants.RegionSize, region.RegionName, region.RegionID); reason = "Coordinates are already in use"; return false; } try { regInfo.InternalEndPoint = new IPEndPoint(IPAddress.Parse("0.0.0.0"), (int)0); } catch (Exception e) { m_log.Warn("[HYPERGRID LINKER]: Wrong format for link-region: " + e.Message); reason = "Internal error"; return false; } // Finally, link it ulong handle = 0; UUID regionID = UUID.Zero; string externalName = string.Empty; string imageURL = string.Empty; if (!m_GatekeeperConnector.LinkRegion(regInfo, out regionID, out handle, out externalName, out imageURL, out reason)) return false; if (regionID == UUID.Zero) { m_log.Warn("[HYPERGRID LINKER]: Unable to link region"); reason = "Remote region could not be found"; return false; } region = m_GridService.GetRegionByUUID(scopeID, regionID); if (region != null) { m_log.DebugFormat("[HYPERGRID LINKER]: Region already exists in coordinates {0} {1}", region.RegionLocX / Constants.RegionSize, region.RegionLocY / Constants.RegionSize); regInfo = region; return true; } // We are now performing this check for each individual teleport in the EntityTransferModule instead. This // allows us to give better feedback when teleports fail because of the distance reason (which can't be // done here) and it also hypergrid teleports that are within range (possibly because the source grid // itself has regions that are very far apart). // uint x, y; // if (m_Check4096 && !Check4096(handle, out x, out y)) // { // //RemoveHyperlinkRegion(regInfo.RegionID); // reason = "Region is too far (" + x + ", " + y + ")"; // m_log.Info("[HYPERGRID LINKER]: Unable to link, region is too far (" + x + ", " + y + ")"); // //return false; // } regInfo.RegionID = regionID; if (externalName == string.Empty) regInfo.RegionName = regInfo.ServerURI; else regInfo.RegionName = externalName; m_log.DebugFormat("[HYPERGRID LINKER]: naming linked region {0}, handle {1}", regInfo.RegionName, handle.ToString()); // Get the map image regInfo.TerrainImage = GetMapImage(regionID, imageURL); // Store the origin's coordinates somewhere regInfo.RegionSecret = handle.ToString(); AddHyperlinkRegion(regInfo, handle); m_log.InfoFormat("[HYPERGRID LINKER]: Successfully linked to region {0} with image {1}", regInfo.RegionName, regInfo.TerrainImage); return true; } public bool TryUnlinkRegion(string mapName) { m_log.DebugFormat("[HYPERGRID LINKER]: Request to unlink {0}", mapName); GridRegion regInfo = null; List<RegionData> regions = m_Database.Get(Util.EscapeForLike(mapName), m_ScopeID); if (regions != null && regions.Count > 0) { OpenSim.Framework.RegionFlags rflags = (OpenSim.Framework.RegionFlags)Convert.ToInt32(regions[0].Data["flags"]); if ((rflags & OpenSim.Framework.RegionFlags.Hyperlink) != 0) { regInfo = new GridRegion(); regInfo.RegionID = regions[0].RegionID; regInfo.ScopeID = m_ScopeID; } } if (regInfo != null) { RemoveHyperlinkRegion(regInfo.RegionID); return true; } else { m_log.InfoFormat("[HYPERGRID LINKER]: Region {0} not found", mapName); return false; } } // Not currently used // /// <summary> // /// Cope with this viewer limitation. // /// </summary> // /// <param name="regInfo"></param> // /// <returns></returns> // public bool Check4096(ulong realHandle, out uint x, out uint y) // { // uint ux = 0, uy = 0; // Utils.LongToUInts(realHandle, out ux, out uy); // x = ux / Constants.RegionSize; // y = uy / Constants.RegionSize; // // const uint limit = (4096 - 1) * Constants.RegionSize; // uint xmin = ux - limit; // uint xmax = ux + limit; // uint ymin = uy - limit; // uint ymax = uy + limit; // // World map boundary checks // if (xmin < 0 || xmin > ux) // xmin = 0; // if (xmax > int.MaxValue || xmax < ux) // xmax = int.MaxValue; // if (ymin < 0 || ymin > uy) // ymin = 0; // if (ymax > int.MaxValue || ymax < uy) // ymax = int.MaxValue; // // // Check for any regions that are within the possible teleport range to the linked region // List<GridRegion> regions = m_GridService.GetRegionRange(m_ScopeID, (int)xmin, (int)xmax, (int)ymin, (int)ymax); // if (regions.Count == 0) // { // return false; // } // else // { // // Check for regions which are not linked regions // List<GridRegion> hyperlinks = m_GridService.GetHyperlinks(m_ScopeID); // IEnumerable<GridRegion> availableRegions = regions.Except(hyperlinks); // if (availableRegions.Count() == 0) // return false; // } // // return true; // } private void AddHyperlinkRegion(GridRegion regionInfo, ulong regionHandle) { RegionData rdata = m_GridService.RegionInfo2RegionData(regionInfo); int flags = (int)OpenSim.Framework.RegionFlags.Hyperlink + (int)OpenSim.Framework.RegionFlags.NoDirectLogin + (int)OpenSim.Framework.RegionFlags.RegionOnline; rdata.Data["flags"] = flags.ToString(); m_Database.Store(rdata); } private void RemoveHyperlinkRegion(UUID regionID) { m_Database.Delete(regionID); } public UUID GetMapImage(UUID regionID, string imageURL) { return m_GatekeeperConnector.GetMapImage(regionID, imageURL, m_MapTileDirectory); } #endregion #region Console Commands public void HandleShow(string module, string[] cmd) { if (cmd.Length != 2) { MainConsole.Instance.Output("Syntax: show hyperlinks"); return; } List<RegionData> regions = m_Database.GetHyperlinks(UUID.Zero); if (regions == null || regions.Count < 1) { MainConsole.Instance.Output("No hyperlinks"); return; } MainConsole.Instance.Output("Region Name"); MainConsole.Instance.Output("Location Region UUID"); MainConsole.Instance.Output(new string('-', 72)); foreach (RegionData r in regions) { MainConsole.Instance.Output(String.Format("{0}\n{2,-32} {1}\n", r.RegionName, r.RegionID, String.Format("{0},{1} ({2},{3})", r.posX, r.posY, r.posX / Constants.RegionSize, r.posY / Constants.RegionSize))); } return; } public void RunCommand(string module, string[] cmdparams) { List<string> args = new List<string>(cmdparams); if (args.Count < 1) return; string command = args[0]; args.RemoveAt(0); cmdparams = args.ToArray(); RunHGCommand(command, cmdparams); } private void RunLinkRegionCommand(string[] cmdparams) { int xloc, yloc; string serverURI; string remoteName = null; xloc = Convert.ToInt32(cmdparams[0]) * (int)Constants.RegionSize; yloc = Convert.ToInt32(cmdparams[1]) * (int)Constants.RegionSize; serverURI = cmdparams[2]; if (cmdparams.Length > 3) remoteName = string.Join(" ", cmdparams, 3, cmdparams.Length - 3); string reason = string.Empty; GridRegion regInfo; if (TryCreateLink(UUID.Zero, xloc, yloc, remoteName, 0, null, serverURI, UUID.Zero, out regInfo, out reason)) MainConsole.Instance.Output("Hyperlink established"); else MainConsole.Instance.Output("Failed to link region: " + reason); } private void RunHGCommand(string command, string[] cmdparams) { if (command.Equals("link-mapping")) { if (cmdparams.Length == 2) { try { m_autoMappingX = Convert.ToUInt32(cmdparams[0]); m_autoMappingY = Convert.ToUInt32(cmdparams[1]); m_enableAutoMapping = true; } catch (Exception) { m_autoMappingX = 0; m_autoMappingY = 0; m_enableAutoMapping = false; } } } else if (command.Equals("link-region")) { if (cmdparams.Length < 3) { if ((cmdparams.Length == 1) || (cmdparams.Length == 2)) { LoadXmlLinkFile(cmdparams); } else { LinkRegionCmdUsage(); } return; } //this should be the prefererred way of setting up hg links now if (cmdparams[2].StartsWith("http")) { RunLinkRegionCommand(cmdparams); } else if (cmdparams[2].Contains(":")) { // New format string[] parts = cmdparams[2].Split(':'); if (parts.Length > 2) { // Insert remote region name ArrayList parameters = new ArrayList(cmdparams); parameters.Insert(3, parts[2]); cmdparams = (string[])parameters.ToArray(typeof(string)); } cmdparams[2] = "http://" + parts[0] + ':' + parts[1]; RunLinkRegionCommand(cmdparams); } else { // old format GridRegion regInfo; int xloc, yloc; uint externalPort; string externalHostName; try { xloc = Convert.ToInt32(cmdparams[0]); yloc = Convert.ToInt32(cmdparams[1]); externalPort = Convert.ToUInt32(cmdparams[3]); externalHostName = cmdparams[2]; //internalPort = Convert.ToUInt32(cmdparams[4]); //remotingPort = Convert.ToUInt32(cmdparams[5]); } catch (Exception e) { MainConsole.Instance.Output("[HGrid] Wrong format for link-region command: " + e.Message); LinkRegionCmdUsage(); return; } // Convert cell coordinates given by the user to meters xloc = xloc * (int)Constants.RegionSize; yloc = yloc * (int)Constants.RegionSize; string reason = string.Empty; if (TryCreateLink(UUID.Zero, xloc, yloc, string.Empty, externalPort, externalHostName, UUID.Zero, out regInfo, out reason)) { // What is this? The GridRegion instance will be discarded anyway, // which effectively ignores any local name given with the command. //if (cmdparams.Length >= 5) //{ // regInfo.RegionName = ""; // for (int i = 4; i < cmdparams.Length; i++) // regInfo.RegionName += cmdparams[i] + " "; //} } } return; } else if (command.Equals("unlink-region")) { if (cmdparams.Length < 1) { UnlinkRegionCmdUsage(); return; } string region = string.Join(" ", cmdparams); if (TryUnlinkRegion(region)) MainConsole.Instance.Output("Successfully unlinked " + region); else MainConsole.Instance.Output("Unable to unlink " + region + ", region not found."); } } private void LoadXmlLinkFile(string[] cmdparams) { //use http://www.hgurl.com/hypergrid.xml for test try { XmlReader r = XmlReader.Create(cmdparams[0]); XmlConfigSource cs = new XmlConfigSource(r); string[] excludeSections = null; if (cmdparams.Length == 2) { if (cmdparams[1].ToLower().StartsWith("excludelist:")) { string excludeString = cmdparams[1].ToLower(); excludeString = excludeString.Remove(0, 12); char[] splitter = { ';' }; excludeSections = excludeString.Split(splitter); } } for (int i = 0; i < cs.Configs.Count; i++) { bool skip = false; if ((excludeSections != null) && (excludeSections.Length > 0)) { for (int n = 0; n < excludeSections.Length; n++) { if (excludeSections[n] == cs.Configs[i].Name.ToLower()) { skip = true; break; } } } if (!skip) { ReadLinkFromConfig(cs.Configs[i]); } } } catch (Exception e) { m_log.Error(e.ToString()); } } private void ReadLinkFromConfig(IConfig config) { GridRegion regInfo; int xloc, yloc; uint externalPort; string externalHostName; uint realXLoc, realYLoc; xloc = Convert.ToInt32(config.GetString("xloc", "0")); yloc = Convert.ToInt32(config.GetString("yloc", "0")); externalPort = Convert.ToUInt32(config.GetString("externalPort", "0")); externalHostName = config.GetString("externalHostName", ""); realXLoc = Convert.ToUInt32(config.GetString("real-xloc", "0")); realYLoc = Convert.ToUInt32(config.GetString("real-yloc", "0")); if (m_enableAutoMapping) { xloc = (int)((xloc % 100) + m_autoMappingX); yloc = (int)((yloc % 100) + m_autoMappingY); } if (((realXLoc == 0) && (realYLoc == 0)) || (((realXLoc - xloc < 3896) || (xloc - realXLoc < 3896)) && ((realYLoc - yloc < 3896) || (yloc - realYLoc < 3896)))) { xloc = xloc * (int)Constants.RegionSize; yloc = yloc * (int)Constants.RegionSize; string reason = string.Empty; if (TryCreateLink(UUID.Zero, xloc, yloc, string.Empty, externalPort, externalHostName, UUID.Zero, out regInfo, out reason)) { regInfo.RegionName = config.GetString("localName", ""); } else MainConsole.Instance.Output("Unable to link " + externalHostName + ": " + reason); } } private void LinkRegionCmdUsage() { MainConsole.Instance.Output("Usage: link-region <Xloc> <Yloc> <ServerURI> [<RemoteRegionName>]"); MainConsole.Instance.Output("Usage (deprecated): link-region <Xloc> <Yloc> <HostName>:<HttpPort>[:<RemoteRegionName>]"); MainConsole.Instance.Output("Usage (deprecated): link-region <Xloc> <Yloc> <HostName> <HttpPort> [<LocalName>]"); MainConsole.Instance.Output("Usage: link-region <URI_of_xml> [<exclude>]"); } private void UnlinkRegionCmdUsage() { MainConsole.Instance.Output("Usage: unlink-region <LocalName>"); } #endregion } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using AutoMapper; using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { public partial class InvokeAzureComputeMethodCmdlet : ComputeAutomationBaseCmdlet { protected object CreateVirtualMachineScaleSetReimageDynamicParameters() { dynamicParameters = new RuntimeDefinedParameterDictionary(); var pResourceGroupName = new RuntimeDefinedParameter(); pResourceGroupName.Name = "ResourceGroupName"; pResourceGroupName.ParameterType = typeof(string); pResourceGroupName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 1, Mandatory = true }); pResourceGroupName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ResourceGroupName", pResourceGroupName); var pVMScaleSetName = new RuntimeDefinedParameter(); pVMScaleSetName.Name = "VMScaleSetName"; pVMScaleSetName.ParameterType = typeof(string); pVMScaleSetName.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 2, Mandatory = true }); pVMScaleSetName.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("VMScaleSetName", pVMScaleSetName); var pInstanceIds = new RuntimeDefinedParameter(); pInstanceIds.Name = "InstanceId"; pInstanceIds.ParameterType = typeof(string[]); pInstanceIds.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByDynamicParameters", Position = 3, Mandatory = false }); pInstanceIds.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("InstanceId", pInstanceIds); var pArgumentList = new RuntimeDefinedParameter(); pArgumentList.Name = "ArgumentList"; pArgumentList.ParameterType = typeof(object[]); pArgumentList.Attributes.Add(new ParameterAttribute { ParameterSetName = "InvokeByStaticParameters", Position = 4, Mandatory = true }); pArgumentList.Attributes.Add(new AllowNullAttribute()); dynamicParameters.Add("ArgumentList", pArgumentList); return dynamicParameters; } protected void ExecuteVirtualMachineScaleSetReimageMethod(object[] invokeMethodInputParameters) { string resourceGroupName = (string)ParseParameter(invokeMethodInputParameters[0]); string vmScaleSetName = (string)ParseParameter(invokeMethodInputParameters[1]); System.Collections.Generic.IList<string> instanceIds = null; if (invokeMethodInputParameters[2] != null) { var inputArray2 = Array.ConvertAll((object[]) ParseParameter(invokeMethodInputParameters[2]), e => e.ToString()); instanceIds = inputArray2.ToList(); } var result = VirtualMachineScaleSetsClient.Reimage(resourceGroupName, vmScaleSetName, instanceIds); WriteObject(result); } } public partial class NewAzureComputeArgumentListCmdlet : ComputeAutomationBaseCmdlet { protected PSArgument[] CreateVirtualMachineScaleSetReimageParameters() { string resourceGroupName = string.Empty; string vmScaleSetName = string.Empty; var instanceIds = new string[0]; return ConvertFromObjectsToArguments( new string[] { "ResourceGroupName", "VMScaleSetName", "InstanceIds" }, new object[] { resourceGroupName, vmScaleSetName, instanceIds }); } } [Cmdlet(VerbsCommon.Set, "AzureRmVmss", DefaultParameterSetName = "DefaultParameter", SupportsShouldProcess = true)] [OutputType(typeof(PSOperationStatusResponse))] public partial class SetAzureRmVmss : ComputeAutomationBaseCmdlet { protected override void ProcessRecord() { AutoMapper.Mapper.AddProfile<ComputeAutomationAutoMapperProfile>(); ExecuteClientAction(() => { if (ShouldProcess(this.ResourceGroupName, VerbsCommon.Set)) { string resourceGroupName = this.ResourceGroupName; string vmScaleSetName = this.VMScaleSetName; System.Collections.Generic.IList<string> instanceIds = this.InstanceId; if (this.ParameterSetName.Equals("FriendMethod")) { var result = VirtualMachineScaleSetsClient.ReimageAll(resourceGroupName, vmScaleSetName, instanceIds); var psObject = new PSOperationStatusResponse(); Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject); WriteObject(psObject); } else { var result = VirtualMachineScaleSetsClient.Reimage(resourceGroupName, vmScaleSetName, instanceIds); var psObject = new PSOperationStatusResponse(); Mapper.Map<Azure.Management.Compute.Models.OperationStatusResponse, PSOperationStatusResponse>(result, psObject); WriteObject(psObject); } } }); } [Parameter( ParameterSetName = "DefaultParameter", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] public string ResourceGroupName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 2, Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Alias("Name")] [AllowNull] public string VMScaleSetName { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [Parameter( ParameterSetName = "FriendMethod", Position = 3, Mandatory = false, ValueFromPipelineByPropertyName = true, ValueFromPipeline = false)] [AllowNull] public string [] InstanceId { get; set; } [Parameter( ParameterSetName = "DefaultParameter", Mandatory = true)] [AllowNull] public SwitchParameter Reimage { get; set; } [Parameter( ParameterSetName = "FriendMethod", Mandatory = true)] [AllowNull] public SwitchParameter ReimageAll { get; set; } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE 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; namespace Spine { public class Bone : IUpdatable { static public bool yDown; internal BoneData data; internal Skeleton skeleton; internal Bone parent; internal ExposedList<Bone> children = new ExposedList<Bone>(); internal float x, y, rotation, scaleX, scaleY; internal float appliedRotation, appliedScaleX, appliedScaleY; internal float a, b, worldX; internal float c, d, worldY; internal float worldSignX, worldSignY; public BoneData Data { get { return data; } } public Skeleton Skeleton { get { return skeleton; } } public Bone Parent { get { return parent; } } public ExposedList<Bone> Children { get { return children; } } public float X { get { return x; } set { x = value; } } public float Y { get { return y; } set { y = value; } } public float Rotation { get { return rotation; } set { rotation = value; } } /// <summary>The rotation, as calculated by any constraints.</summary> public float AppliedRotation { get { return appliedRotation; } set { appliedRotation = value; } } /// <summary>The scale X, as calculated by any constraints.</summary> public float AppliedScaleX { get { return appliedScaleX; } set { appliedScaleX = value; } } /// <summary>The scale Y, as calculated by any constraints.</summary> public float AppliedScaleY { get { return appliedScaleY; } set { appliedScaleY = value; } } public float ScaleX { get { return scaleX; } set { scaleX = value; } } public float ScaleY { get { return scaleY; } set { scaleY = value; } } public float A { get { return a; } } public float B { get { return b; } } public float C { get { return c; } } public float D { get { return d; } } public float WorldX { get { return worldX; } } public float WorldY { get { return worldY; } } public float WorldSignX { get { return worldSignX; } } public float WorldSignY { get { return worldSignY; } } public float WorldRotationX { get { return MathUtils.Atan2(c, a) * MathUtils.radDeg; } } public float WorldRotationY { get { return MathUtils.Atan2(d, b) * MathUtils.radDeg; } } public float WorldScaleX { get { return (float)Math.Sqrt(a * a + b * b) * worldSignX; } } public float WorldScaleY { get { return (float)Math.Sqrt(c * c + d * d) * worldSignY; } } /// <param name="parent">May be null.</param> public Bone (BoneData data, Skeleton skeleton, Bone parent) { if (data == null) throw new ArgumentNullException("data cannot be null."); if (skeleton == null) throw new ArgumentNullException("skeleton cannot be null."); this.data = data; this.skeleton = skeleton; this.parent = parent; SetToSetupPose(); } /// <summary>Same as {@link #updateWorldTransform()}. This method exists for Bone to implement {@link Updatable}.</summary> public void Update () { UpdateWorldTransform(x, y, rotation, scaleX, scaleY); } /// <summary>Computes the world SRT using the parent bone and this bone's local SRT.</summary> public void UpdateWorldTransform () { UpdateWorldTransform(x, y, rotation, scaleX, scaleY); } /// <summary>Computes the world SRT using the parent bone and the specified local SRT.</summary> public void UpdateWorldTransform (float x, float y, float rotation, float scaleX, float scaleY) { appliedRotation = rotation; appliedScaleX = scaleX; appliedScaleY = scaleY; float cos = MathUtils.CosDeg(rotation), sin = MathUtils.SinDeg(rotation); float la = cos * scaleX, lb = -sin * scaleY, lc = sin * scaleX, ld = cos * scaleY; Bone parent = this.parent; if (parent == null) { // Root bone. Skeleton skeleton = this.skeleton; if (skeleton.flipX) { x = -x; la = -la; lb = -lb; } if (skeleton.flipY != yDown) { y = -y; lc = -lc; ld = -ld; } a = la; b = lb; c = lc; d = ld; worldX = x; worldY = y; worldSignX = Math.Sign(scaleX); worldSignY = Math.Sign(scaleY); return; } float pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d; worldX = pa * x + pb * y + parent.worldX; worldY = pc * x + pd * y + parent.worldY; worldSignX = parent.worldSignX * Math.Sign(scaleX); worldSignY = parent.worldSignY * Math.Sign(scaleY); if (data.inheritRotation && data.inheritScale) { a = pa * la + pb * lc; b = pa * lb + pb * ld; c = pc * la + pd * lc; d = pc * lb + pd * ld; } else if (data.inheritRotation) { // No scale inheritance. pa = 1; pb = 0; pc = 0; pd = 1; do { cos = MathUtils.CosDeg(parent.appliedRotation); sin = MathUtils.SinDeg(parent.appliedRotation); float temp = pa * cos + pb * sin; pb = pa * -sin + pb * cos; pa = temp; temp = pc * cos + pd * sin; pd = pc * -sin + pd * cos; pc = temp; parent = parent.parent; } while (parent != null); a = pa * la + pb * lc; b = pa * lb + pb * ld; c = pc * la + pd * lc; d = pc * lb + pd * ld; if (skeleton.flipX) { a = -a; b = -b; } if (skeleton.flipY != yDown) { c = -c; d = -d; } } else if (data.inheritScale) { // No rotation inheritance. pa = 1; pb = 0; pc = 0; pd = 1; do { float r = parent.rotation; cos = MathUtils.CosDeg(r); sin = MathUtils.SinDeg(r); float psx = parent.appliedScaleX, psy = parent.appliedScaleY; float za = cos * psx, zb = -sin * psy, zc = sin * psx, zd = cos * psy; float temp = pa * za + pb * zc; pb = pa * zb + pb * zd; pa = temp; temp = pc * za + pd * zc; pd = pc * zb + pd * zd; pc = temp; if (psx < 0) r = -r; cos = MathUtils.CosDeg(-r); sin = MathUtils.SinDeg(-r); temp = pa * cos + pb * sin; pb = pa * -sin + pb * cos; pa = temp; temp = pc * cos + pd * sin; pd = pc * -sin + pd * cos; pc = temp; parent = parent.parent; } while (parent != null); a = pa * la + pb * lc; b = pa * lb + pb * ld; c = pc * la + pd * lc; d = pc * lb + pd * ld; if (skeleton.flipX) { a = -a; b = -b; } if (skeleton.flipY != yDown) { c = -c; d = -d; } } else { a = la; b = lb; c = lc; d = ld; } } public void SetToSetupPose () { BoneData data = this.data; x = data.x; y = data.y; rotation = data.rotation; scaleX = data.scaleX; scaleY = data.scaleY; } public void WorldToLocal (float worldX, float worldY, out float localX, out float localY) { float x = worldX - this.worldX, y = worldY - this.worldY; float a = this.a, b = this.b, c = this.c, d = this.d; float invDet = 1 / (a * d - b * c); localX = (x * a * invDet - y * b * invDet); localY = (y * d * invDet - x * c * invDet); } public void LocalToWorld (float localX, float localY, out float worldX, out float worldY) { float x = localX, y = localY; worldX = x * a + y * b + this.worldX; worldY = x * c + y * d + this.worldY; } override public String ToString () { return data.name; } } }
using VkApi.Wrapper.Objects; using VkApi.Wrapper.Responses; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace VkApi.Wrapper.Methods { public class Video { private readonly Vkontakte _vkontakte; internal Video(Vkontakte vkontakte) => _vkontakte = vkontakte; ///<summary> /// Adds a video to a user or community page. ///</summary> public Task<BaseOkResponse> Add(int? targetId = null, int? videoId = null, int? ownerId = null) { var parameters = new Dictionary<string, string>(); if (targetId != null) parameters.Add("target_id", targetId.ToApiString()); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.add", parameters); } ///<summary> /// Creates an empty album for videos. ///</summary> public Task<VideoAddAlbumResponse> AddAlbum(int? groupId = null, String title = null, String[] privacy = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (title != null) parameters.Add("title", title.ToApiString()); if (privacy != null) parameters.Add("privacy", privacy.ToApiString()); return _vkontakte.RequestAsync<VideoAddAlbumResponse>("video.addAlbum", parameters); } ///<summary> /// Adds a new comment on a video. ///</summary> public Task<int> CreateComment(int? ownerId = null, int? videoId = null, String message = null, String[] attachments = null, Boolean? fromGroup = null, int? replyToComment = null, int? stickerId = null, String guid = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (message != null) parameters.Add("message", message.ToApiString()); if (attachments != null) parameters.Add("attachments", attachments.ToApiString()); if (fromGroup != null) parameters.Add("from_group", fromGroup.ToApiString()); if (replyToComment != null) parameters.Add("reply_to_comment", replyToComment.ToApiString()); if (stickerId != null) parameters.Add("sticker_id", stickerId.ToApiString()); if (guid != null) parameters.Add("guid", guid.ToApiString()); return _vkontakte.RequestAsync<int>("video.createComment", parameters); } ///<summary> /// Deletes a video from a user or community page. ///</summary> public Task<BaseOkResponse> Delete(int? videoId = null, int? ownerId = null, int? targetId = null) { var parameters = new Dictionary<string, string>(); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (targetId != null) parameters.Add("target_id", targetId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.delete", parameters); } ///<summary> /// Deletes a video album. ///</summary> public Task<BaseOkResponse> DeleteAlbum(int? groupId = null, int? albumId = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.deleteAlbum", parameters); } ///<summary> /// Deletes a comment on a video. ///</summary> public Task<BaseOkResponse> DeleteComment(int? ownerId = null, int? commentId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.deleteComment", parameters); } ///<summary> /// Edits information about a video on a user or community page. ///</summary> public Task<BaseOkResponse> Edit(int? ownerId = null, int? videoId = null, String name = null, String desc = null, String[] privacyView = null, String[] privacyComment = null, Boolean? noComments = null, Boolean? repeat = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (name != null) parameters.Add("name", name.ToApiString()); if (desc != null) parameters.Add("desc", desc.ToApiString()); if (privacyView != null) parameters.Add("privacy_view", privacyView.ToApiString()); if (privacyComment != null) parameters.Add("privacy_comment", privacyComment.ToApiString()); if (noComments != null) parameters.Add("no_comments", noComments.ToApiString()); if (repeat != null) parameters.Add("repeat", repeat.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.edit", parameters); } ///<summary> /// Edits the title of a video album. ///</summary> public Task<BaseOkResponse> EditAlbum(int? groupId = null, int? albumId = null, String title = null, String[] privacy = null) { var parameters = new Dictionary<string, string>(); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (title != null) parameters.Add("title", title.ToApiString()); if (privacy != null) parameters.Add("privacy", privacy.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.editAlbum", parameters); } ///<summary> /// Edits the text of a comment on a video. ///</summary> public Task<BaseOkResponse> EditComment(int? ownerId = null, int? commentId = null, String message = null, String[] attachments = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); if (message != null) parameters.Add("message", message.ToApiString()); if (attachments != null) parameters.Add("attachments", attachments.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.editComment", parameters); } ///<summary> /// Returns detailed information about videos. ///</summary> public Task<VideoGetResponse> Get(int? ownerId = null, String[] videos = null, int? albumId = null, int? count = null, int? offset = null, Boolean? extended = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (videos != null) parameters.Add("videos", videos.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); return _vkontakte.RequestAsync<VideoGetResponse>("video.get", parameters); } ///<summary> /// Returns video album info ///</summary> public Task<VideoVideoAlbumFull> GetAlbumById(int? ownerId = null, int? albumId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); return _vkontakte.RequestAsync<VideoVideoAlbumFull>("video.getAlbumById", parameters); } ///<summary> /// Returns a list of video albums owned by a user or community. ///</summary> public Task<VideoGetAlbumsResponse> GetAlbums(int? ownerId = null, int? offset = null, int? count = null, Boolean? extended = null, Boolean? needSystem = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (needSystem != null) parameters.Add("need_system", needSystem.ToApiString()); return _vkontakte.RequestAsync<VideoGetAlbumsResponse>("video.getAlbums", parameters); } ///<summary> /// Returns a list of comments on a video. ///</summary> public Task<VideoGetCommentsResponse> GetComments(int? ownerId = null, int? videoId = null, Boolean? needLikes = null, int? startCommentId = null, int? offset = null, int? count = null, String sort = null, Boolean? extended = null, String[] fields = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (needLikes != null) parameters.Add("need_likes", needLikes.ToApiString()); if (startCommentId != null) parameters.Add("start_comment_id", startCommentId.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (sort != null) parameters.Add("sort", sort.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); if (fields != null) parameters.Add("fields", fields.ToApiString()); return _vkontakte.RequestAsync<VideoGetCommentsResponse>("video.getComments", parameters); } ///<summary> /// Reorders the album in the list of user video albums. ///</summary> public Task<BaseOkResponse> ReorderAlbums(int? ownerId = null, int? albumId = null, int? before = null, int? after = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (before != null) parameters.Add("before", before.ToApiString()); if (after != null) parameters.Add("after", after.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.reorderAlbums", parameters); } ///<summary> /// Reorders the video in the video album. ///</summary> public Task<BaseOkResponse> ReorderVideos(int? targetId = null, int? albumId = null, int? ownerId = null, int? videoId = null, int? beforeOwnerId = null, int? beforeVideoId = null, int? afterOwnerId = null, int? afterVideoId = null) { var parameters = new Dictionary<string, string>(); if (targetId != null) parameters.Add("target_id", targetId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (beforeOwnerId != null) parameters.Add("before_owner_id", beforeOwnerId.ToApiString()); if (beforeVideoId != null) parameters.Add("before_video_id", beforeVideoId.ToApiString()); if (afterOwnerId != null) parameters.Add("after_owner_id", afterOwnerId.ToApiString()); if (afterVideoId != null) parameters.Add("after_video_id", afterVideoId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.reorderVideos", parameters); } ///<summary> /// Reports (submits a complaint about) a video. ///</summary> public Task<BaseOkResponse> Report(int? ownerId = null, int? videoId = null, int? reason = null, String comment = null, String searchQuery = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (reason != null) parameters.Add("reason", reason.ToApiString()); if (comment != null) parameters.Add("comment", comment.ToApiString()); if (searchQuery != null) parameters.Add("search_query", searchQuery.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.report", parameters); } ///<summary> /// Reports (submits a complaint about) a comment on a video. ///</summary> public Task<BaseOkResponse> ReportComment(int? ownerId = null, int? commentId = null, int? reason = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); if (reason != null) parameters.Add("reason", reason.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.reportComment", parameters); } ///<summary> /// Restores a previously deleted video. ///</summary> public Task<BaseOkResponse> Restore(int? videoId = null, int? ownerId = null) { var parameters = new Dictionary<string, string>(); if (videoId != null) parameters.Add("video_id", videoId.ToApiString()); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); return _vkontakte.RequestAsync<BaseOkResponse>("video.restore", parameters); } ///<summary> /// Restores a previously deleted comment on a video. ///</summary> public Task<int> RestoreComment(int? ownerId = null, int? commentId = null) { var parameters = new Dictionary<string, string>(); if (ownerId != null) parameters.Add("owner_id", ownerId.ToApiString()); if (commentId != null) parameters.Add("comment_id", commentId.ToApiString()); return _vkontakte.RequestAsync<int>("video.restoreComment", parameters); } ///<summary> /// Returns a server address (required for upload) and video data. ///</summary> public Task<VideoSaveResult> Save(String name = null, String description = null, Boolean? isPrivate = null, Boolean? wallpost = null, String link = null, int? groupId = null, int? albumId = null, String[] privacyView = null, String[] privacyComment = null, Boolean? noComments = null, Boolean? repeat = null, Boolean? compression = null) { var parameters = new Dictionary<string, string>(); if (name != null) parameters.Add("name", name.ToApiString()); if (description != null) parameters.Add("description", description.ToApiString()); if (isPrivate != null) parameters.Add("is_private", isPrivate.ToApiString()); if (wallpost != null) parameters.Add("wallpost", wallpost.ToApiString()); if (link != null) parameters.Add("link", link.ToApiString()); if (groupId != null) parameters.Add("group_id", groupId.ToApiString()); if (albumId != null) parameters.Add("album_id", albumId.ToApiString()); if (privacyView != null) parameters.Add("privacy_view", privacyView.ToApiString()); if (privacyComment != null) parameters.Add("privacy_comment", privacyComment.ToApiString()); if (noComments != null) parameters.Add("no_comments", noComments.ToApiString()); if (repeat != null) parameters.Add("repeat", repeat.ToApiString()); if (compression != null) parameters.Add("compression", compression.ToApiString()); return _vkontakte.RequestAsync<VideoSaveResult>("video.save", parameters); } ///<summary> /// Returns a list of videos under the set search criterion. ///</summary> public Task<VideoSearchResponse> Search(String q = null, int? sort = null, int? hd = null, Boolean? adult = null, String[] filters = null, Boolean? searchOwn = null, int? offset = null, int? longer = null, int? shorter = null, int? count = null, Boolean? extended = null) { var parameters = new Dictionary<string, string>(); if (q != null) parameters.Add("q", q.ToApiString()); if (sort != null) parameters.Add("sort", sort.ToApiString()); if (hd != null) parameters.Add("hd", hd.ToApiString()); if (adult != null) parameters.Add("adult", adult.ToApiString()); if (filters != null) parameters.Add("filters", filters.ToApiString()); if (searchOwn != null) parameters.Add("search_own", searchOwn.ToApiString()); if (offset != null) parameters.Add("offset", offset.ToApiString()); if (longer != null) parameters.Add("longer", longer.ToApiString()); if (shorter != null) parameters.Add("shorter", shorter.ToApiString()); if (count != null) parameters.Add("count", count.ToApiString()); if (extended != null) parameters.Add("extended", extended.ToApiString()); return _vkontakte.RequestAsync<VideoSearchResponse>("video.search", parameters); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104)] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135)] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var runtime = CreateRuntime(source, compileReferences, runtimeReferences); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out resultProperties, out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143)] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"))); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty. Add("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"). Add("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } [WorkItem(1117084)] [Fact(Skip = "1114866")] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml"))); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty, "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } private RuntimeInstance CreateRuntime( string source, ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences) { var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: compileReferences); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); return CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), runtimeReferences.AddIntrinsicAssembly(), exeBytes, new SymReader(pdbBytes)); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
// 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.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.ExtractMethod; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod { internal partial class CSharpMethodExtractor { private partial class CSharpCodeGenerator { private class ExpressionCodeGenerator : CSharpCodeGenerator { public ExpressionCodeGenerator( InsertionPoint insertionPoint, SelectionResult selectionResult, AnalyzerResult analyzerResult) : base(insertionPoint, selectionResult, analyzerResult) { } public static bool IsExtractMethodOnExpression(SelectionResult code) { return code.SelectionInExpression; } protected override SyntaxToken CreateMethodName() { var methodName = "NewMethod"; var containingScope = this.CSharpSelectionResult.GetContainingScope(); methodName = GetMethodNameBasedOnExpression(methodName, containingScope); var semanticModel = this.SemanticDocument.SemanticModel; var nameGenerator = new UniqueNameGenerator(semanticModel); return SyntaxFactory.Identifier(nameGenerator.CreateUniqueMethodName(containingScope, methodName)); } private static string GetMethodNameBasedOnExpression(string methodName, SyntaxNode expression) { if (expression.Parent != null && expression.Parent.Kind() == SyntaxKind.EqualsValueClause && expression.Parent.Parent != null && expression.Parent.Parent.Kind() == SyntaxKind.VariableDeclarator) { var name = ((VariableDeclaratorSyntax)expression.Parent.Parent).Identifier.ValueText; return (name != null && name.Length > 0) ? MakeMethodName("Get", name) : methodName; } if (expression is MemberAccessExpressionSyntax) { expression = ((MemberAccessExpressionSyntax)expression).Name; } if (expression is NameSyntax) { SimpleNameSyntax unqualifiedName; switch (expression.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: unqualifiedName = (SimpleNameSyntax)expression; break; case SyntaxKind.QualifiedName: unqualifiedName = ((QualifiedNameSyntax)expression).Right; break; case SyntaxKind.AliasQualifiedName: unqualifiedName = ((AliasQualifiedNameSyntax)expression).Name; break; default: throw new System.NotSupportedException("Unexpected name kind: " + expression.Kind().ToString()); } var unqualifiedNameIdentifierValueText = unqualifiedName.Identifier.ValueText; return (unqualifiedNameIdentifierValueText != null && unqualifiedNameIdentifierValueText.Length > 0) ? MakeMethodName("Get", unqualifiedNameIdentifierValueText) : methodName; } return methodName; } protected override IEnumerable<StatementSyntax> GetInitialStatementsForMethodDefinitions() { Contract.ThrowIfFalse(IsExtractMethodOnExpression(this.CSharpSelectionResult)); ExpressionSyntax expression = null; // special case for array initializer var returnType = (ITypeSymbol)this.AnalyzerResult.ReturnType; var containingScope = this.CSharpSelectionResult.GetContainingScope(); if (returnType.TypeKind == TypeKind.Array && containingScope is InitializerExpressionSyntax) { var typeSyntax = returnType.GenerateTypeSyntax(); expression = SyntaxFactory.ArrayCreationExpression(typeSyntax as ArrayTypeSyntax, containingScope as InitializerExpressionSyntax); } else { expression = containingScope as ExpressionSyntax; } if (this.AnalyzerResult.HasReturnType) { return SpecializedCollections.SingletonEnumerable<StatementSyntax>( SyntaxFactory.ReturnStatement( WrapInCheckedExpressionIfNeeded(expression))); } else { return SpecializedCollections.SingletonEnumerable<StatementSyntax>( SyntaxFactory.ExpressionStatement( WrapInCheckedExpressionIfNeeded(expression))); } } private ExpressionSyntax WrapInCheckedExpressionIfNeeded(ExpressionSyntax expression) { var kind = this.CSharpSelectionResult.UnderCheckedExpressionContext(); if (kind == SyntaxKind.None) { return expression; } return SyntaxFactory.CheckedExpression(kind, expression); } protected override SyntaxNode GetOutermostCallSiteContainerToProcess(CancellationToken cancellationToken) { var callSiteContainer = GetCallSiteContainerFromOutermostMoveInVariable(cancellationToken); if (callSiteContainer != null) { return callSiteContainer; } else { return GetCallSiteContainerFromExpression(); } } private SyntaxNode GetCallSiteContainerFromExpression() { var container = this.CSharpSelectionResult.GetInnermostStatementContainer(); Contract.ThrowIfNull(container); Contract.ThrowIfFalse(container.IsStatementContainerNode() || container is TypeDeclarationSyntax || container is ConstructorDeclarationSyntax || container is CompilationUnitSyntax); return container; } protected override SyntaxNode GetFirstStatementOrInitializerSelectedAtCallSite() { var scope = (SyntaxNode)this.CSharpSelectionResult.GetContainingScopeOf<StatementSyntax>(); if (scope == null) { scope = this.CSharpSelectionResult.GetContainingScopeOf<FieldDeclarationSyntax>(); } if (scope == null) { scope = this.CSharpSelectionResult.GetContainingScopeOf<ConstructorInitializerSyntax>(); } return scope; } protected override SyntaxNode GetLastStatementOrInitializerSelectedAtCallSite() { return GetFirstStatementOrInitializerSelectedAtCallSite(); } protected override async Task<SyntaxNode> GetStatementOrInitializerContainingInvocationToExtractedMethodAsync( SyntaxAnnotation callSiteAnnotation, CancellationToken cancellationToken) { var enclosingStatement = GetFirstStatementOrInitializerSelectedAtCallSite(); var callSignature = CreateCallSignature().WithAdditionalAnnotations(callSiteAnnotation); var invocation = callSignature.IsKind(SyntaxKind.AwaitExpression) ? ((AwaitExpressionSyntax)callSignature).Expression : callSignature; var sourceNode = this.CSharpSelectionResult.GetContainingScope(); Contract.ThrowIfTrue( sourceNode.Parent is MemberAccessExpressionSyntax && ((MemberAccessExpressionSyntax)sourceNode.Parent).Name == sourceNode, "invalid scope. given scope is not an expression"); // To lower the chances that replacing sourceNode with callSignature will break the user's // code, we make the enclosing statement semantically explicit. This ends up being a little // bit more work because we need to annotate the sourceNode so that we can get back to it // after rewriting the enclosing statement. var updatedDocument = this.SemanticDocument.Document; var sourceNodeAnnotation = new SyntaxAnnotation(); var enclosingStatementAnnotation = new SyntaxAnnotation(); var newEnclosingStatement = enclosingStatement .ReplaceNode(sourceNode, sourceNode.WithAdditionalAnnotations(sourceNodeAnnotation)) .WithAdditionalAnnotations(enclosingStatementAnnotation); updatedDocument = await updatedDocument.ReplaceNodeAsync(enclosingStatement, newEnclosingStatement, cancellationToken).ConfigureAwait(false); var updatedRoot = await updatedDocument.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); newEnclosingStatement = updatedRoot.GetAnnotatedNodesAndTokens(enclosingStatementAnnotation).Single().AsNode(); // because of the complexifiction we cannot guarantee that there is only one annotation. // however complexification of names is prepended, so the last annotation should be the original one. sourceNode = updatedRoot.GetAnnotatedNodesAndTokens(sourceNodeAnnotation).Last().AsNode(); // we want to replace the old identifier with a invocation expression, but because of MakeExplicit we might have // a member access now instead of the identifer. So more syntax fiddling is needed. if (sourceNode.Parent.Kind() == SyntaxKind.SimpleMemberAccessExpression && ((ExpressionSyntax)sourceNode).IsRightSideOfDot()) { var explicitMemberAccess = (MemberAccessExpressionSyntax)sourceNode.Parent; var replacementMemberAccess = explicitMemberAccess.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( sourceNode.Parent.Kind(), explicitMemberAccess.Expression, (SimpleNameSyntax)((InvocationExpressionSyntax)invocation).Expression)); var newInvocation = SyntaxFactory.InvocationExpression( replacementMemberAccess, ((InvocationExpressionSyntax)invocation).ArgumentList); var newCallSignature = callSignature != invocation ? callSignature.ReplaceNode(invocation, newInvocation) : invocation.CopyAnnotationsTo(newInvocation); sourceNode = sourceNode.Parent; callSignature = newCallSignature; } return newEnclosingStatement.ReplaceNode(sourceNode, callSignature); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Apache.Geode.Client; using Apache.Geode.Client.Internal; namespace PdxTests { public enum pdxEnumTest { pdx1, pdx2, pdx3 }; public class Address : IPdxSerializable { int _aptNumber; string _street; string _city; public Address() { } public override string ToString() { return _aptNumber + " :" + _street + " : " + _city; } public Address(int aptN, string street, string city) { _aptNumber = aptN; _street = street; _city = city; } public override bool Equals(object obj) { Debug.WriteLine("in addredd equal"); if (obj == null) return false; Address other = obj as Address; if (other == null) return false; Debug.WriteLine("in addredd equal2 " + this.ToString() + " : : " + other.ToString()); if (_aptNumber == other._aptNumber && _street == other._street && _city == other._city) return true; return false; } public override int GetHashCode() { return base.GetHashCode(); } #region IPdxSerializable Members public void FromData(IPdxReader reader) { _aptNumber = reader.ReadInt("_aptNumber"); _street = reader.ReadString("_street"); _city = reader.ReadString("_city"); } public void ToData(IPdxWriter writer) { writer.WriteInt("_aptNumber", _aptNumber); writer.WriteString("_street", _street); writer.WriteString("_city", _city); } #endregion } [Serializable] public class PdxType : IPdxSerializable { char m_char; bool m_bool; sbyte m_byte; sbyte m_sbyte; short m_int16; short m_uint16; Int32 m_int32; Int32 m_uint32; long m_long; Int64 m_ulong; float m_float; double m_double; string m_string; bool[] m_boolArray; byte[] m_byteArray; byte[] m_sbyteArray; char[] m_charArray; DateTime m_dateTime; Int16[] m_int16Array; Int16[] m_uint16Array; Int32[] m_int32Array; Int32[] m_uint32Array; long[] m_longArray; Int64[] m_ulongArray; float[] m_floatArray; double[] m_doubleArray; byte[][] m_byteByteArray; string[] m_stringArray; List<object> m_arraylist = new List<object>(); IDictionary<object, object> m_map = new Dictionary<object, object>(); Hashtable m_hashtable = new Hashtable(); ArrayList m_vector = new ArrayList(); CacheableHashSet m_chs = CacheableHashSet.Create(); CacheableLinkedHashSet m_clhs = CacheableLinkedHashSet.Create(); byte[] m_byte252 = new byte[252]; byte[] m_byte253 = new byte[253]; byte[] m_byte65535 = new byte[65535]; byte[] m_byte65536 = new byte[65536]; pdxEnumTest m_pdxEnum = pdxEnumTest.pdx2; Address[] m_address; List<object> m_objectArray = new List<object>(); public void Init() { m_char = 'C'; m_bool = true; m_byte = 0x74; m_sbyte = 0x67; m_int16 = 0xab; m_uint16 = 0x2dd5; m_int32 = 0x2345abdc; m_uint32 = 0x2a65c434; m_long = 324897980; m_ulong = 238749898; m_float = 23324.324f; m_double = 3243298498d; m_string = "gfestring"; m_boolArray = new bool[] { true, false, true }; m_byteArray = new byte[] { 0x34, 0x64 }; m_sbyteArray = new byte[] { 0x34, 0x64 }; m_charArray = new char[] { 'c', 'v' }; DateTime n = new DateTime((62135596800000/*epoch*/ + 1310447869154) * 10000, DateTimeKind.Utc); m_dateTime = n.ToLocalTime(); Debug.WriteLine(m_dateTime.Ticks); m_int16Array = new short[] { 0x2332, 0x4545 }; m_uint16Array = new short[] { 0x3243, 0x3232 }; m_int32Array = new int[] { 23, 676868, 34343, 2323 }; m_uint32Array = new int[] { 435, 234324, 324324, 23432432 }; m_longArray = new long[] { 324324L, 23434545L }; m_ulongArray = new Int64[] { 3245435, 3425435 }; m_floatArray = new float[] { 232.565f, 2343254.67f }; m_doubleArray = new double[] { 23423432d, 4324235435d }; m_byteByteArray = new byte[][]{new byte[] {0x23}, new byte[]{0x34, 0x55} }; m_stringArray = new string[] { "one", "two" }; m_arraylist = new List<object>(); m_arraylist.Add(1); m_arraylist.Add(2); m_map = new Dictionary<object, object>(); m_map.Add(1, 1); m_map.Add(2, 2); m_hashtable = new Hashtable(); m_hashtable.Add(1, "1111111111111111"); m_hashtable.Add(2, "2222222222221111111111111111"); m_vector = new ArrayList(); m_vector.Add(1); m_vector.Add(2); m_vector.Add(3); m_chs.Add(1); m_clhs.Add(1); m_clhs.Add(2); m_pdxEnum = pdxEnumTest.pdx2; m_address = new Address[10]; for (int i = 0; i < 10; i++) { m_address[i] = new Address(i + 1, "street" + i.ToString(), "city" + i.ToString()); } m_objectArray = new List<object>(); for (int i = 0; i < 10; i++) { m_objectArray.Add(new Address(i + 1, "street" + i.ToString(), "city" + i.ToString())); } } public PdxType() { Init(); } public static IPdxSerializable CreateDeserializable() { return new PdxType(); } #region IPdxSerializable Members public static byte[][] compareByteByteArray(byte[][] baa, byte[][] baa2) { if (baa.Length == baa2.Length) { int i = 0; while (i < baa.Length) { compareByteArray(baa[i], baa2[i]); i++; } if (i == baa2.Length) return baa2; } throw new IllegalStateException("Not got expected value for type: " + baa2.GetType().ToString()); } bool compareBool(bool b, bool b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } bool[] compareBoolArray(bool[] a, bool[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } byte compareByte(byte b, byte b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } public static byte[] compareByteArray(byte[] a, byte[] a2) { Debug.WriteLine("Compare byte array " + a.Length + " ; " + a2.Length); if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { Debug.WriteLine("Compare byte array " + a[i] + " : " + a2[i]); if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } char[] compareCharArray(char[] a, char[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } public static List<object> compareCompareCollection(List<object> a, List<object> a2) { if (a.Count == a2.Count) { int i = 0; while (i < a.Count) { if (!a[i].Equals(a2[i])) break; else i++; } if (i == a2.Count) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } /* public static LinkedList<String> compareCompareCollection(LinkedList<String> a, LinkedList<String> a2) { if (a.Count == a2.Count) { int i = 0; while (i < a.Count) { if (!a[i].Equals(a2[i])) break; else i++; } if (i == a2.Count) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } */ public static DateTime compareData(DateTime b, DateTime b2) { Debug.WriteLine("date " + b.Ticks + " : " + b2.Ticks); //TODO: // return b; if ((b.Ticks / 10000L) == (b2.Ticks / 10000L)) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } Double compareDouble(Double b, Double b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } double[] compareDoubleArray(double[] a, double[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } float compareFloat(float b, float b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } float[] compareFloatArray(float[] a, float[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } Int16 compareInt16(Int16 b, Int16 b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } Int32 compareInt32(Int32 b, Int32 b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } Int64 compareInt64(Int64 b, Int64 b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } Int32[] compareIntArray(Int32[] a, Int32[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } long[] compareLongArray(long[] a, long[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } Int16[] compareSHortArray(Int16[] a, Int16[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } sbyte compareSByte(sbyte b, sbyte b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } sbyte[] compareSByteArray(sbyte[] a, sbyte[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } string[] compareStringArray(string[] a, string[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } UInt16 compareUInt16(UInt16 b, UInt16 b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } UInt32 compareUInt32(UInt32 b, UInt32 b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } UInt64 compareUint64(UInt64 b, UInt64 b2) { if (b == b2) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString()); } UInt32[] compareUnsignedIntArray(UInt32[] a, UInt32[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } UInt64[] compareUnsignedLongArray(UInt64[] a, UInt64[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } UInt16[] compareUnsignedShortArray(UInt16[] a, UInt16[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (a[i] != a2[i]) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } public static T[] GenericCompare<T>(T[] a, T[] a2) { if (a.Length == a2.Length) { int i = 0; while (i < a.Length) { if (!a[i].Equals(a2[i])) break; else i++; } if (i == a2.Length) return a2; } throw new IllegalStateException("Not got expected value for type: " + a2.GetType().ToString()); } public static T GenericValCompare<T>(T b, T b2) { if (b.Equals(b2)) return b; throw new IllegalStateException("Not got expected value for type: " + b2.GetType().ToString() + " : values " + b.ToString() + ": " + b2.ToString()); } public override bool Equals(object obj) { if (obj == null) return false; PdxType other = obj as PdxType; if (other == null) return false; if (other == this) return true; compareByteByteArray(other.m_byteByteArray, m_byteByteArray); GenericValCompare(other.m_char, m_char); GenericValCompare(other.m_bool, m_bool); GenericCompare(other.m_boolArray, m_boolArray); GenericValCompare(other.m_byte, m_byte); GenericCompare(other.m_byteArray, m_byteArray); GenericCompare(other.m_charArray, m_charArray); compareCompareCollection(other.m_arraylist, m_arraylist); if (other.m_map.Count != m_map.Count) throw new IllegalStateException("Not got expected value for type: " + m_map.GetType().ToString()); if (other.m_hashtable.Count != m_hashtable.Count) throw new IllegalStateException("Not got expected value for type: " + m_hashtable.GetType().ToString()); if (other.m_vector.Count != m_vector.Count) throw new IllegalStateException("Not got expected value for type: " + m_vector.GetType().ToString()); if (other.m_chs.Count != m_chs.Count) throw new IllegalStateException("Not got expected value for type: " + m_chs.GetType().ToString()); if (other.m_clhs.Count != m_clhs.Count) throw new IllegalStateException("Not got expected value for type: " + m_clhs.GetType().ToString()); GenericValCompare(other.m_string, m_string); compareData(other.m_dateTime, m_dateTime); GenericValCompare(other.m_double, m_double); GenericCompare(other.m_doubleArray, m_doubleArray); GenericValCompare(other.m_float, m_float); GenericCompare(other.m_floatArray, m_floatArray); GenericValCompare(other.m_int16, m_int16); GenericValCompare(other.m_int32, m_int32); GenericValCompare(other.m_long, m_long); GenericCompare(other.m_int32Array, m_int32Array); GenericCompare(other.m_longArray, m_longArray); GenericCompare(other.m_int16Array, m_int16Array); GenericValCompare(other.m_sbyte, m_sbyte); GenericCompare(other.m_sbyteArray, m_sbyteArray); GenericCompare(other.m_stringArray, m_stringArray); GenericValCompare(other.m_uint16, m_uint16); GenericValCompare(other.m_uint32, m_uint32); GenericValCompare(other.m_ulong, m_ulong); GenericCompare(other.m_uint32Array, m_uint32Array); GenericCompare(other.m_ulongArray, m_ulongArray); GenericCompare(other.m_uint16Array, m_uint16Array); if (m_byte252.Length != 252 && other.m_byte252.Length != 252) throw new Exception("Array len 252 not found"); if (m_byte253.Length != 253 && other.m_byte253.Length != 253) throw new Exception("Array len 253 not found"); if (m_byte65535.Length != 65535 && other.m_byte65535.Length != 65535) throw new Exception("Array len 65535 not found"); if (m_byte65536.Length != 65536 && other.m_byte65536.Length != 65536) throw new Exception("Array len 65536 not found"); if (m_pdxEnum != other.m_pdxEnum) throw new Exception("pdx enum is not equal"); { for (int i = 0; i < m_address.Length; i++) { if (!m_address[i].Equals(other.m_address[i])) throw new Exception("Address array not mateched " + i); } } for (int i = 0; i < m_objectArray.Count; i++) { if (!m_objectArray[i].Equals(other.m_objectArray[i])) return false; } return true; } public override int GetHashCode() { return base.GetHashCode(); } public void FromData(IPdxReader reader) { //byte[][] baa = reader.ReadArrayOfByteArrays("m_byteByteArray"); //m_byteByteArray = compareByteByteArray(baa, m_byteByteArray); //bool bl = reader.ReadBoolean("m_bool"); //m_bool = compareBool(bl, m_bool); //m_boolArray = compareBoolArray(reader.ReadBooleanArray("m_boolArray"), m_boolArray); //m_byte = compareByte(reader.ReadByte("m_byte"), m_byte); //m_byteArray = compareByteArray(reader.ReadByteArray("m_byteArray"), m_byteArray); //m_charArray = compareCharArray(reader.ReadCharArray("m_charArray"), m_charArray); //List<object> tmpl = new List<object>(); //reader.ReadCollection("m_list", tmpl); //m_list = compareCompareCollection(tmpl, m_list); //m_dateTime = compareData(reader.ReadDate("m_dateTime"), m_dateTime); //m_double = compareDouble(reader.ReadDouble("m_double"), m_double); //m_doubleArray = compareDoubleArray(reader.ReadDoubleArray("m_doubleArray"), m_doubleArray); //m_float = compareFloat(reader.ReadFloat("m_float"), m_float); //m_floatArray = compareFloatArray(reader.ReadFloatArray("m_floatArray"), m_floatArray); //m_int16 = compareInt16(reader.ReadInt16("m_int16"), m_int16); //m_int32 = compareInt32(reader.ReadInt32("m_int32"), m_int32); //m_long = compareInt64(reader.ReadInt64("m_long"), m_long); //m_int32Array = compareIntArray(reader.ReadIntArray("m_int32Array"), m_int32Array); //m_longArray = compareLongArray(reader.ReadLongArray("m_longArray"), m_longArray); //m_int16Array = compareSHortArray(reader.ReadShortArray("m_int16Array"), m_int16Array); //m_sbyte = compareSByte(reader.ReadSByte("m_sbyte"), m_sbyte); //m_sbyteArray = compareSByteArray(reader.ReadSByteArray("m_sbyteArray"), m_sbyteArray); //m_stringArray = compareStringArray(reader.ReadStringArray("m_stringArray"), m_stringArray); //m_uint16 = compareUInt16(reader.ReadUInt16("m_uint16"), m_uint16); //m_uint32 = compareUInt32(reader.ReadUInt32("m_uint32") , m_uint32); //m_ulong = compareUint64(reader.ReadUInt64("m_ulong"), m_ulong); //m_uint32Array = compareUnsignedIntArray(reader.ReadUnsignedIntArray("m_uint32Array"), m_uint32Array); //m_ulongArray = compareUnsignedLongArray(reader.ReadUnsignedLongArray("m_ulongArray"), m_ulongArray); //m_uint16Array = compareUnsignedShortArray(reader.ReadUnsignedShortArray("m_uint16Array"), m_uint16Array); byte[][] baa = reader.ReadArrayOfByteArrays("m_byteByteArray"); m_byteByteArray = compareByteByteArray(baa, m_byteByteArray); m_char = GenericValCompare(reader.ReadChar("m_char"), m_char); bool bl = reader.ReadBoolean("m_bool"); m_bool = GenericValCompare(bl, m_bool); m_boolArray = GenericCompare(reader.ReadBooleanArray("m_boolArray"), m_boolArray); m_byte = GenericValCompare(reader.ReadByte("m_byte"), m_byte); m_byteArray = GenericCompare(reader.ReadByteArray("m_byteArray"), m_byteArray); m_charArray = GenericCompare(reader.ReadCharArray("m_charArray"), m_charArray); List<object> tmpl = new List<object>(); tmpl = (List<object>)reader.ReadObject("m_arraylist"); m_arraylist = compareCompareCollection(tmpl, m_arraylist); IDictionary<object, object> tmpM = (IDictionary<object, object>)reader.ReadObject("m_map"); if (tmpM.Count != m_map.Count) throw new IllegalStateException("Not got expected value for type: " + m_map.GetType().ToString()); Hashtable tmpH = (Hashtable)reader.ReadObject("m_hashtable"); if (tmpH.Count != m_hashtable.Count) throw new IllegalStateException("Not got expected value for type: " + m_hashtable.GetType().ToString()); ArrayList arrAl = (ArrayList)reader.ReadObject("m_vector"); if (arrAl.Count != m_vector.Count) throw new IllegalStateException("Not got expected value for type: " + m_vector.GetType().ToString()); CacheableHashSet rmpChs = (CacheableHashSet)reader.ReadObject("m_chs"); if (rmpChs.Count != m_chs.Count) throw new IllegalStateException("Not got expected value for type: " + m_chs.GetType().ToString()); CacheableLinkedHashSet rmpClhs = (CacheableLinkedHashSet)reader.ReadObject("m_clhs"); if (rmpClhs.Count != m_clhs.Count) throw new IllegalStateException("Not got expected value for type: " + m_clhs.GetType().ToString()); m_string = GenericValCompare(reader.ReadString("m_string"), m_string); m_dateTime = compareData(reader.ReadDate("m_dateTime"), m_dateTime); m_double = GenericValCompare(reader.ReadDouble("m_double"), m_double); m_doubleArray = GenericCompare(reader.ReadDoubleArray("m_doubleArray"), m_doubleArray); m_float = GenericValCompare(reader.ReadFloat("m_float"), m_float); m_floatArray = GenericCompare(reader.ReadFloatArray("m_floatArray"), m_floatArray); m_int16 = GenericValCompare(reader.ReadShort("m_int16"), m_int16); m_int32 = GenericValCompare(reader.ReadInt("m_int32"), m_int32); m_long = GenericValCompare(reader.ReadLong("m_long"), m_long); m_int32Array = GenericCompare(reader.ReadIntArray("m_int32Array"), m_int32Array); m_longArray = GenericCompare(reader.ReadLongArray("m_longArray"), m_longArray); m_int16Array = GenericCompare(reader.ReadShortArray("m_int16Array"), m_int16Array); m_sbyte = GenericValCompare(reader.ReadByte("m_sbyte"), m_sbyte); m_sbyteArray = GenericCompare(reader.ReadByteArray("m_sbyteArray"), m_sbyteArray); m_stringArray = GenericCompare(reader.ReadStringArray("m_stringArray"), m_stringArray); m_uint16 = GenericValCompare(reader.ReadShort("m_uint16"), m_uint16); m_uint32 = GenericValCompare(reader.ReadInt("m_uint32"), m_uint32); m_ulong = GenericValCompare(reader.ReadLong("m_ulong"), m_ulong); m_uint32Array = GenericCompare(reader.ReadIntArray("m_uint32Array"), m_uint32Array); m_ulongArray = GenericCompare(reader.ReadLongArray("m_ulongArray"), m_ulongArray); m_uint16Array = GenericCompare(reader.ReadShortArray("m_uint16Array"), m_uint16Array); byte[] ret = reader.ReadByteArray("m_byte252"); if (ret.Length != 252) throw new Exception("Array len 252 not found"); ret = reader.ReadByteArray("m_byte253"); if (ret.Length != 253) throw new Exception("Array len 253 not found"); ret = reader.ReadByteArray("m_byte65535"); if (ret.Length != 65535) throw new Exception("Array len 65535 not found"); ret = reader.ReadByteArray("m_byte65536"); if (ret.Length != 65536) throw new Exception("Array len 65536 not found"); pdxEnumTest retenum = (pdxEnumTest)reader.ReadObject("m_pdxEnum"); if (retenum != m_pdxEnum) throw new Exception("Enum is not equal"); //byte[] m_byte252 = new byte[252]; //byte[] m_byte253 = new byte[253]; //byte[] m_byte65535 = new byte[65535]; //byte[] m_byte65536 = new byte[65536]; Address[] addressArray = (Address[])reader.ReadObject("m_address"); { for (int i = 0; i < m_address.Length; i++) { if (!m_address[i].Equals(addressArray[i])) { Debug.WriteLine(m_address[i]); Debug.WriteLine(addressArray[i]); throw new Exception("Address array not mateched " + i); } } } List<object> retoa = reader.ReadObjectArray("m_objectArray"); for (int i = 0; i < m_objectArray.Count; i++) { if (!m_objectArray[i].Equals(retoa[i])) throw new Exception("Object array not mateched " + i); } } public string PString { get { return m_string; } } public void ToData(IPdxWriter writer) { writer.WriteArrayOfByteArrays("m_byteByteArray", m_byteByteArray); writer.WriteChar("m_char", m_char); writer.WriteBoolean("m_bool", m_bool); writer.WriteBooleanArray("m_boolArray", m_boolArray); writer.WriteByte("m_byte", m_byte); writer.WriteByteArray("m_byteArray", m_byteArray); writer.WriteCharArray("m_charArray", m_charArray); //writer.WriteCollection("m_list", m_list); writer.WriteObject("m_arraylist", m_arraylist); writer.WriteObject("m_map", m_map); writer.WriteObject("m_hashtable", m_hashtable); writer.WriteObject("m_vector", m_vector); writer.WriteObject("m_chs", m_chs); writer.WriteObject("m_clhs", m_clhs); writer.WriteString("m_string", m_string); writer.WriteDate("m_dateTime", m_dateTime); writer.WriteDouble("m_double", m_double); writer.WriteDoubleArray("m_doubleArray", m_doubleArray); writer.WriteFloat("m_float", m_float); writer.WriteFloatArray("m_floatArray", m_floatArray); writer.WriteShort("m_int16", m_int16); writer.WriteInt("m_int32", m_int32); writer.WriteLong("m_long", m_long); writer.WriteIntArray("m_int32Array", m_int32Array); writer.WriteLongArray("m_longArray", m_longArray); writer.WriteShortArray("m_int16Array", m_int16Array); writer.WriteByte("m_sbyte", m_sbyte); writer.WriteByteArray("m_sbyteArray", m_sbyteArray); writer.WriteStringArray("m_stringArray", m_stringArray); writer.WriteShort("m_uint16", m_uint16); writer.WriteInt("m_uint32", m_uint32); writer.WriteLong("m_ulong", m_ulong); writer.WriteIntArray("m_uint32Array", m_uint32Array); writer.WriteLongArray("m_ulongArray", m_ulongArray); writer.WriteShortArray("m_uint16Array", m_uint16Array); writer.WriteByteArray("m_byte252", m_byte252); writer.WriteByteArray("m_byte253", m_byte253); writer.WriteByteArray("m_byte65535", m_byte65535); writer.WriteByteArray("m_byte65536", m_byte65536); writer.WriteObject("m_pdxEnum", m_pdxEnum); writer.WriteObject("m_address", m_address); writer.WriteObjectArray("m_objectArray", m_objectArray); //byte[] m_byte252 = new byte[252]; //byte[] m_byte253 = new byte[253]; //byte[] m_byte65535 = new byte[65535]; //byte[] m_byte65536 = new byte[65536]; } public char Char { get { return m_char; } } public bool Bool { get { return m_bool; } } public sbyte Byte { get { return m_byte; } } public sbyte Sbyte { get { return m_sbyte; } } public short Int16 { get { return m_int16; } } public short Uint16 { get { return m_uint16; } } public Int32 Int32 { get { return m_int32; } } public Int32 Uint32 { get { return m_uint32; } } public long Long { get { return m_long; } } public Int64 Ulong { get { return m_ulong; } } public float Float { get { return m_float; } } public double Double { get { return m_double; } } public string String { get { return m_string; } } public bool[] BoolArray { get { return m_boolArray; } } public byte[] ByteArray { get { return m_byteArray; } } public byte[] SbyteArray { get { return m_sbyteArray; } } public char[] CharArray { get { return m_charArray; } } public DateTime DateTime { get { return m_dateTime; } } public Int16[] Int16Array { get { return m_int16Array; } } public Int16[] Uint16Array { get { return m_uint16Array; } } public Int32[] Int32Array { get { return m_int32Array; } } public Int32[] Uint32Array { get { return m_uint32Array; } } public long[] LongArray { get { return m_longArray; } } public Int64[] UlongArray { get { return m_ulongArray; } } public float[] FloatArray { get { return m_floatArray; } } public double[] DoubleArray { get { return m_doubleArray; } } public byte[][] ByteByteArray { get { return m_byteByteArray; } } public string[] StringArray { get { return m_stringArray; } } public List<object> Arraylist { get { return m_arraylist; } } public IDictionary<object, object> Map { get { return m_map; } } public Hashtable Hashtable { get { return m_hashtable; } } public ArrayList Vector { get { return m_vector; } } public CacheableHashSet Chs { get { return m_chs; } } public CacheableLinkedHashSet Clhs { get { return m_clhs; } } public byte[] Byte252 { get { return m_byte252; } } public byte[] Byte253 { get { return m_byte253; } } public byte[] Byte65535 { get { return m_byte65535; } } public byte[] Byte65536 { get { return m_byte65536; } } public pdxEnumTest PdxEnum { get { return m_pdxEnum; } } public Address[] AddressArray { get { return m_address; } } public List<object> ObjectArray { get { return m_objectArray; } } #endregion } }
// // Copyright (C) 2008-2009 Jordi Mas i Hernandez, jmas@softcatala.org // // 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.Text; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Xml.Serialization; using Gdk; using Pango; using Cairo; using Mistelix.Core; using Mistelix.Widgets; using Mistelix.Effects; namespace Mistelix.DataModel { // // Describes an image that is part of a slideshow // public class SlideImage : SlideShowProjectElement.Image { // // Pixel order // // mistelixvideosrc uses RGB pixel order // Cairo uses ARGB (each pixel is a 32-bit quantity, ARGB. The 32-bit quantities are stored native-endian) // Pixbuf uses RGBA (big-endian order) // enum PixelFormat { CAIRO_ARGB, // PIXBUF_RGB, // 3 channels PIXBUF_ARGB // 4 channels }; [XmlIgnoreAttribute] int width, height, stride, channels = 3; [XmlIgnoreAttribute] bool alpha = false; [XmlIgnoreAttribute] byte[] pixels = null; [XmlIgnoreAttribute] Project project; [XmlIgnoreAttribute] int offset_x, offset_y, w, h; [XmlIgnoreAttribute] PixelFormat pixel_format = PixelFormat.PIXBUF_RGB; [XmlIgnoreAttribute] public int Width { get { return width; } } [XmlIgnoreAttribute] public int Height { get { return height; } } [XmlIgnoreAttribute] public int Stride { get { return stride; } } [XmlIgnoreAttribute] public int Channels { get { return channels; } } public SlideImage () { TransitionTime = 2; // Transition from slide to slide (effect duration). Hardcoded default ShowTime = Mistelix.Preferences.GetIntValue (Preferences.DefaultDurationKey); Transition = Mistelix.Preferences.GetStringValue (Preferences.DefaultTransitionKey); Position = (TextPosition) Mistelix.Preferences.GetIntValue (Preferences.DefaultTextPositionKey); } public SlideImage (string image) : this () { if (image == null) throw new ArgumentNullException ("image name cannot be null"); this.image = image; } public SlideImage (string image, string title, int time, string transition) : this () { if (transition == null) throw new ArgumentNullException ("transition cannot be null"); if (image == null) throw new ArgumentNullException ("image name cannot be null"); this.image = image; Title = title; ShowTime = time; Transition = transition; } // Used only for previewing the transition effect public SlideImage (Cairo.ImageSurface img) { if (img.Format != Cairo.Format.Argb32) throw new InvalidOperationException (String.Format ("SlideImage.SlideImage: unsupported format {0}", img.Format)); width = img.Width; height = img.Height; stride = img.Stride; channels = 4; alpha = true; pixels = img.Data; } [System.Xml.Serialization.XmlIgnoreAttribute] public byte[] Pixels { get { if (pixels == null) LoadSlide (); return pixels; } set { pixels = value; } } public void LoadSlide () { if (pixels != null) return; LoadAndScaleImage (); ProcessEffects (); ProcessImage (); } [System.Xml.Serialization.XmlIgnoreAttribute] public Project Project { set { project = value; } get { return project; } } public void CopyProperties (SlideImage src) { // TODO: Missing SlideImage properties width = src.width; height = src.height; stride = src.stride; alpha = src.alpha; channels = src.channels; Effects = src.Effects; project = src.project; Position = src.Position; image = src.image; } // The list of images for a slideshow is kept on a list // When generating the slideshow the pixels are allocated, however they are only // needed during the slideshow generation. Releasing the pixels helps to GC // to free the memory used public void ReleasePixels () { pixels = null; } public SlideImage GetSlideThumbnail(int width, int height) { return GetSlideThumbnail(width, height, false); } public SlideImage GetSlideThumbnail(int width, int height, bool copyTitle) { SlideImage newImage = new SlideImage(); newImage.CopyProperties(this); using(DataImageSurface thumbnail = this.GetThumbnail(width, height, copyTitle)) { newImage.FromDataImageSurface(thumbnail); } return newImage; } public DataImageSurface GetThumbnail (int width, int height) { return GetThumbnail(width, height, false); } public DataImageSurface GetThumbnail (int width, int height, bool copy_title) { PixelFormat pixelformat_src; SlideImage slide = new SlideImage (); slide.CopyProperties (this); if(copy_title) slide.Title = Title; slide.LoadAndScaleImage (width, height); slide.ProcessEffects (); slide.ProcessImage (); pixelformat_src = slide.pixel_format; // Pixel format of current buffer slide.pixel_format = PixelFormat.CAIRO_ARGB; // New target format slide.LoadFromPixelData (slide.pixels, pixelformat_src, width, height, width * slide.channels, slide.channels); return new DataImageSurface (DataImageSurface.Allocate (slide.Pixels), Cairo.Format.ARGB32, slide.width, slide.height, slide.stride); } public DataImageSurface ToDataImageSurface() { PixelFormat pixelformat_src; SlideImage slide = new SlideImage (); slide.CopyProperties (this); slide.pixels = (byte[]) this.Pixels.Clone(); slide.ProcessEffects (); pixelformat_src = slide.pixel_format; // Pixel format of current buffer slide.pixel_format = PixelFormat.CAIRO_ARGB; // New target format slide.LoadFromPixelData (slide.pixels, pixelformat_src, width, height, width * slide.channels, slide.channels); return new DataImageSurface (DataImageSurface.Allocate (slide.Pixels), Cairo.Format.ARGB32, slide.width, slide.height, slide.stride); } // mistelixvideosrc expects images in 24 bits (3 channels) public void FromDataImageSurface (DataImageSurface img) { if (img.Format != Cairo.Format.Argb32) throw new InvalidOperationException (String.Format ("SlideImage.FromCairo: unsupported format {0}", img.Format)); width = img.Width; height = img.Height; pixels = img.Get24bitsPixBuf (); channels = 3; stride = ((img.Width * channels) + 3) & ~3; alpha = false; } void DrawImageLegend (Cairo.Context cr, string title, int x, int y, int width, int height) { const int marginx = 50; // Distance of the coloured box from the x margins (in safe area) const int marginy = 50; // Distance of the coloured box from the y margins (in safe area) const int textoffset_x = 5; // Offset where the text is drawn const int textoffset_y = 5; // Offset where the text is drawn int box_x, box_y, box_w, box_h; int w, h; int max_width; if (title == null) return; using (Pango.Layout layout = Pango.CairoHelper.CreateLayout (cr)) { layout.SingleParagraphMode = false; max_width = width - ((marginx + textoffset_x) * 2); layout.Width = (int) (max_width * Pango.Scale.PangoScale); layout.FontDescription = FontDescription.FromString (project.Details.SlideshowsFontName); layout.SetText (title); layout.GetPixelSize (out w, out h); w = w + textoffset_x * 2; box_x = x + ((width - (marginx * 2) - w) /2); box_x += marginx; box_w = w; box_h = h + textoffset_y * 2; switch (Position) { case TextPosition.Top: box_y = y + marginy; break; case TextPosition.Bottom: default: box_y = y + height - marginy - h; break; } // Background cr.Color = project.Details.SlideshowsBackColor; cr.Rectangle (box_x, box_y, box_w, box_h); cr.Fill (); cr.Stroke (); cr.MoveTo (box_x + textoffset_x, box_y + textoffset_y); cr.Color = project.Details.SlideshowsForeColor; Pango.CairoHelper.ShowLayout (cr, layout); } } void LoadAndScaleImage () { if (project == null) throw new InvalidOperationException (String.Format ("SlideImage.CreateImage: need project defined (image {0})", image)); LoadAndScaleImage (project.Details.Width, project.Details.Height); ProcessEffects (); } // // Loads the image from disk and scales it to certain size // It is used to generate the final images and thumbnails // void LoadAndScaleImage (int width, int height) { if (image == null) throw new InvalidOperationException ("SlideImage.LoadAndScaleImage: no filename defined for image"); if (width <= 0 || height <= 0) throw new InvalidOperationException ("SlideImage.LoadAndScaleImage: width and height should be > 0"); Logger.Debug ("SlideImage.LoadAndScaleImage. {0} {1} {2}", image, width, height); int max_w = width; // max target width int max_h = height; // max target height double target_ratio = (double) max_w / (double) max_h; // aspect ratio target double scale, original_ratio, corrected_ratio; Gdk.Pixbuf raw_image, processed_image; raw_image = new Gdk.Pixbuf (image); Logger.Debug ("SlideImage.LoadAndScaleImage. Load image w:{0} h:{1} channels:{2}", raw_image.Width, raw_image.Height, raw_image.NChannels); if (raw_image.NChannels != 3 && raw_image.NChannels != 4) { Logger.Error ("SlideImage.LoadAndScaleImage. Image {0} with unsupported number of channels ({1})", image, raw_image.NChannels); return; } processed_image = new Gdk.Pixbuf (Colorspace.Rgb, raw_image.NChannels == 3 ? false : true, 8, max_w, max_h); processed_image.Fill (0x00000000); original_ratio = (double) raw_image.Width / (double) raw_image.Height; // Image is larger that target resolution, we need to rescale if (raw_image.Width > max_w || raw_image.Height > max_h) { if (original_ratio < 1) { // If X is properly scaled (the smaller), Y will be too if (original_ratio > target_ratio) corrected_ratio = target_ratio / original_ratio; else corrected_ratio = original_ratio / target_ratio; scale = (double) max_w / (double) raw_image.Width; h = (int) ((double) raw_image.Width * scale / original_ratio * corrected_ratio); w = (int) ((double) raw_image.Width * scale * corrected_ratio); } else { // If Y is properly scaled (the smaller), X will be too (used path for NTSC and PAL resolutions) if (original_ratio > target_ratio) corrected_ratio = target_ratio / original_ratio; else corrected_ratio = original_ratio / target_ratio; scale = (double) max_h / (double) raw_image.Height; h = (int) ((double) raw_image.Width * scale / original_ratio * corrected_ratio); w = (int) ((double) raw_image.Width * scale * corrected_ratio); } } else { // No need to scale w = raw_image.Width; h = raw_image.Height; } if (w < max_w) offset_x = (max_w -w) / 2; else offset_x = 0; if (h < max_h) offset_y = (max_h - h) / 2; else offset_y = 0; raw_image.Scale (processed_image, offset_x, offset_y, w, h, offset_x, offset_y, (double) w / (double) raw_image.Width, (double)h /(double) raw_image.Height, InterpType.Hyper); LoadFromPixelData (processed_image.Pixels, processed_image.NChannels == 3 ? PixelFormat.PIXBUF_RGB : PixelFormat.PIXBUF_ARGB, processed_image.Width, processed_image.Height, processed_image.Rowstride, processed_image.NChannels); raw_image.Dispose (); processed_image.Dispose (); } void ProcessImage () { Logger.Debug ("SlideImage.ProcessImage. {0} Channels {1}", image, Channels); if (Title == null || Title == string.Empty) return; Logger.Debug ("SlideImage.ProcessImage. Image {0}", image); byte[] pix; if (channels == 3) { int src = 0; byte [] source; int stride_trg = 4 * width; int len_trg = stride_trg * height; source = Pixels; pix = new byte [len_trg]; for (int trg = 0; trg < len_trg; trg = trg + 4) { pix [trg] = source [src + 2]; pix [trg + 1] = source [src + 1]; pix [trg + 2] = source [src + 0]; pix [trg + 3] = 0xff; src += 3; } } else pix = Pixels; DataImageSurface surface = new DataImageSurface (DataImageSurface.Allocate (pix), Cairo.Format.Argb32, width, height, stride); Cairo.Context gr = new Cairo.Context (surface); DrawImageLegend (gr, Title, offset_x, offset_y, w, h); FromDataImageSurface (surface); ((IDisposable)gr).Dispose (); ((IDisposable)surface).Dispose (); } public void ProcessEffects () { SlideImage processed; Effect effect; if (Effects == null) return; processed = this; foreach (string name in Effects) { Logger.Debug ("SlideImage.ProcessEffects. Effect {0}", name); effect = EffectManager.CreateFromName (name); processed = effect.Apply (processed); } Pixels = processed.Pixels; } void LoadFromPixelData (IntPtr data, PixelFormat format_src, int width_src, int height_src, int stride_src, int channels_src) { int len = stride_src * height_src; byte[] source = new byte [len]; Marshal.Copy (data, source, 0, len); LoadFromPixelData (source, format_src, width_src, height_src, stride_src, channels_src); } void LoadFromPixelData (byte[] source, PixelFormat format_src, int width_src, int height_src, int stride_src, int channels_src) { if ((pixel_format == PixelFormat.CAIRO_ARGB && pixel_format == PixelFormat.PIXBUF_RGB) || (channels_src != 3 && channels_src != 4)) { throw new InvalidOperationException ( String.Format ("Could not process SlideImage.LoadFromPixelData requested format {0} image {1}", pixel_format, channels_src)); } int src, len; Logger.Debug ("SlideImage.LoadFromPixelData. f:{0} w:{1} h:{2} s:{3} c:{4}", format_src, width_src, height_src, stride_src, channels_src); switch (pixel_format) { case PixelFormat.PIXBUF_RGB: alpha = false; channels = 3; break; case PixelFormat.PIXBUF_ARGB: case PixelFormat.CAIRO_ARGB: channels = 4; alpha = true; break; default: throw new InvalidOperationException ("Unsupported format"); } // Target data array width = width_src; height = height_src; stride = ((width * channels) + 3) & ~3; len = stride * height; pixels = new byte [len]; src = 0; for (int trg = 0; trg < len; trg = trg + channels) { if (pixel_format == PixelFormat.CAIRO_ARGB) { pixels [trg] = source [src + 2]; pixels [trg + 1] = source [src + 1]; pixels [trg + 2] = source [src + 0]; } else { pixels [trg] = source [src]; pixels [trg + 1] = source [src + 1]; pixels [trg + 2] = source [src + 2]; } if (channels == 4) pixels [trg + 3] = 0xff; src += channels_src; } } } }
/** * Couchbase Lite for .NET * * Original iOS version by Jens Alfke * Android Port by Marty Schoch, Traun Leyden * C# Port by Zack Gramana * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * Portions (c) 2013, 2014 Xamarin, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using System; using System.Collections.Generic; using Sharpen; namespace Couchbase.Lite.Util { /// <summary> /// BEGIN LAYOUTLIB CHANGE /// This is a custom version that doesn't use the non standard LinkedHashMap#eldest. /// </summary> /// <remarks> /// BEGIN LAYOUTLIB CHANGE /// This is a custom version that doesn't use the non standard LinkedHashMap#eldest. /// END LAYOUTLIB CHANGE /// A cache that holds strong references to a limited number of values. Each time /// a value is accessed, it is moved to the head of a queue. When a value is /// added to a full cache, the value at the end of that queue is evicted and may /// become eligible for garbage collection. /// <p>If your cached values hold resources that need to be explicitly released, /// override /// <see cref="LruCache{K, V}.EntryRemoved(bool, object, object, object)">LruCache&lt;K, V&gt;.EntryRemoved(bool, object, object, object) /// </see> /// . /// <p>If a cache miss should be computed on demand for the corresponding keys, /// override /// <see cref="LruCache{K, V}.Create(object)">LruCache&lt;K, V&gt;.Create(object)</see> /// . This simplifies the calling code, allowing it to /// assume a value will always be returned, even when there's a cache miss. /// <p>By default, the cache size is measured in the number of entries. Override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// to size the cache in different units. For example, this cache /// is limited to 4MiB of bitmaps: /// <pre> /// <code>int cacheSize = 4 * 1024 * 1024; // 4MiB</code> /// LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) /// protected int sizeOf(String key, Bitmap value) { /// return value.getByteCount(); /// } /// }}</pre> /// <p>This class is thread-safe. Perform multiple cache operations atomically by /// synchronizing on the cache: <pre> /// <code></code> /// synchronized (cache) /// if (cache.get(key) == null) { /// cache.put(key, value); /// } /// }}</pre> /// <p>This class does not allow null to be used as a key or value. A return /// value of null from /// <see cref="LruCache{K, V}.Get(object)">LruCache&lt;K, V&gt;.Get(object)</see> /// , /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// or /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// is /// unambiguous: the key was not in the cache. /// <p>This class appeared in Android 3.1 (Honeycomb MR1); it's available as part /// of <a href="http://developer.android.com/sdk/compatibility-library.html">Android's /// Support Package</a> for earlier releases. /// </remarks> public class LruCache<K, V> { private readonly LinkedHashMap<K, V> map; /// <summary>Size of this cache in units.</summary> /// <remarks>Size of this cache in units. Not necessarily the number of elements.</remarks> private int size; private int maxSize; private int putCount; private int createCount; private int evictionCount; private int hitCount; private int missCount; /// <param name="maxSize"> /// for caches that do not override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// , this is /// the maximum number of entries in the cache. For all other caches, /// this is the maximum sum of the sizes of the entries in this cache. /// </param> public LruCache(int maxSize) { // COPY: Copied from android.util.LruCache if (maxSize <= 0) { throw new ArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap<K, V>(0, 0.75f, true); } /// <summary>Sets the size of the cache.</summary> /// <remarks>Sets the size of the cache.</remarks> /// <param name="maxSize">The new maximum size.</param> /// <hide></hide> public virtual void Resize(int maxSize) { if (maxSize <= 0) { throw new ArgumentException("maxSize <= 0"); } lock (this) { this.maxSize = maxSize; } TrimToSize(maxSize); } /// <summary> /// Returns the value for /// <code>key</code> /// if it exists in the cache or can be /// created by /// <code>#create</code> /// . If a value was returned, it is moved to the /// head of the queue. This returns null if a value is not cached and cannot /// be created. /// </summary> public V Get(K key) { if (key == null) { throw new ArgumentNullException("key == null"); } V mapValue; lock (this) { mapValue = map.Get(key); if (mapValue != null) { hitCount++; return mapValue; } missCount++; } V createdValue = Create(key); if (createdValue == null) { return null; } lock (this) { createCount++; mapValue = map.Put(key, createdValue); if (mapValue != null) { // There was a conflict so undo that last put map.Put(key, mapValue); } else { size += SafeSizeOf(key, createdValue); } } if (mapValue != null) { EntryRemoved(false, key, createdValue, mapValue); return mapValue; } else { TrimToSize(maxSize); return createdValue; } } /// <summary> /// Caches /// <code>value</code> /// for /// <code>key</code> /// . The value is moved to the head of /// the queue. /// </summary> /// <returns> /// the previous value mapped by /// <code>key</code> /// . /// </returns> public V Put(K key, V value) { if (key == null || value == null) { throw new ArgumentNullException("key == null || value == null"); } V previous; lock (this) { putCount++; size += SafeSizeOf(key, value); previous = map.Put(key, value); if (previous != null) { size -= SafeSizeOf(key, previous); } } if (previous != null) { EntryRemoved(false, key, previous, value); } TrimToSize(maxSize); return previous; } /// <param name="maxSize"> /// the maximum size of the cache before returning. May be -1 /// to evict even 0-sized elements. /// </param> private void TrimToSize(int maxSize) { while (true) { K key; V value; lock (this) { if (size < 0 || (map.IsEmpty() && size != 0)) { throw new InvalidOperationException(GetType().FullName + ".sizeOf() is reporting inconsistent results!" ); } if (size <= maxSize) { break; } // BEGIN LAYOUTLIB CHANGE // get the last item in the linked list. // This is not efficient, the goal here is to minimize the changes // compared to the platform version. KeyValuePair<K, V> toEvict = null; foreach (KeyValuePair<K, V> entry in map.EntrySet()) { toEvict = entry; } // END LAYOUTLIB CHANGE if (toEvict == null) { break; } key = toEvict.Key; value = toEvict.Value; Sharpen.Collections.Remove(map, key); size -= SafeSizeOf(key, value); evictionCount++; } EntryRemoved(true, key, value, null); } } /// <summary> /// Removes the entry for /// <code>key</code> /// if it exists. /// </summary> /// <returns> /// the previous value mapped by /// <code>key</code> /// . /// </returns> public V Remove(K key) { if (key == null) { throw new ArgumentNullException("key == null"); } V previous; lock (this) { previous = Sharpen.Collections.Remove(map, key); if (previous != null) { size -= SafeSizeOf(key, previous); } } if (previous != null) { EntryRemoved(false, key, previous, null); } return previous; } /// <summary>Called for entries that have been evicted or removed.</summary> /// <remarks> /// Called for entries that have been evicted or removed. This method is /// invoked when a value is evicted to make space, removed by a call to /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// , or replaced by a call to /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// . The default /// implementation does nothing. /// <p>The method is called without synchronization: other threads may /// access the cache while this method is executing. /// </remarks> /// <param name="evicted"> /// true if the entry is being removed to make space, false /// if the removal was caused by a /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// or /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// . /// </param> /// <param name="newValue"> /// the new value for /// <code>key</code> /// , if it exists. If non-null, /// this removal was caused by a /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// . Otherwise it was caused by /// an eviction or a /// <see cref="LruCache{K, V}.Remove(object)">LruCache&lt;K, V&gt;.Remove(object)</see> /// . /// </param> protected internal virtual void EntryRemoved(bool evicted, K key, V oldValue, V newValue ) { } /// <summary>Called after a cache miss to compute a value for the corresponding key.</summary> /// <remarks> /// Called after a cache miss to compute a value for the corresponding key. /// Returns the computed value or null if no value can be computed. The /// default implementation returns null. /// <p>The method is called without synchronization: other threads may /// access the cache while this method is executing. /// <p>If a value for /// <code>key</code> /// exists in the cache when this method /// returns, the created value will be released with /// <see cref="LruCache{K, V}.EntryRemoved(bool, object, object, object)">LruCache&lt;K, V&gt;.EntryRemoved(bool, object, object, object) /// </see> /// and discarded. This can occur when multiple threads request the same key /// at the same time (causing multiple values to be created), or when one /// thread calls /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// while another is creating a value for the same /// key. /// </remarks> protected internal virtual V Create(K key) { return null; } private int SafeSizeOf(K key, V value) { int result = SizeOf(key, value); if (result < 0) { throw new InvalidOperationException("Negative size: " + key + "=" + value); } return result; } /// <summary> /// Returns the size of the entry for /// <code>key</code> /// and /// <code>value</code> /// in /// user-defined units. The default implementation returns 1 so that size /// is the number of entries and max size is the maximum number of entries. /// <p>An entry's size must not change while it is in the cache. /// </summary> protected internal virtual int SizeOf(K key, V value) { return 1; } /// <summary> /// Clear the cache, calling /// <see cref="LruCache{K, V}.EntryRemoved(bool, object, object, object)">LruCache&lt;K, V&gt;.EntryRemoved(bool, object, object, object) /// </see> /// on each removed entry. /// </summary> public void EvictAll() { TrimToSize(-1); } // -1 will evict 0-sized elements /// <summary> /// For caches that do not override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// , this returns the number /// of entries in the cache. For all other caches, this returns the sum of /// the sizes of the entries in this cache. /// </summary> public int Size() { lock (this) { return size; } } /// <summary> /// For caches that do not override /// <see cref="LruCache{K, V}.SizeOf(object, object)">LruCache&lt;K, V&gt;.SizeOf(object, object) /// </see> /// , this returns the maximum /// number of entries in the cache. For all other caches, this returns the /// maximum sum of the sizes of the entries in this cache. /// </summary> public int MaxSize() { lock (this) { return maxSize; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Get(object)">LruCache&lt;K, V&gt;.Get(object)</see> /// returned a value that was /// already present in the cache. /// </summary> public int HitCount() { lock (this) { return hitCount; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Get(object)">LruCache&lt;K, V&gt;.Get(object)</see> /// returned null or required a new /// value to be created. /// </summary> public int MissCount() { lock (this) { return missCount; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Create(object)">LruCache&lt;K, V&gt;.Create(object)</see> /// returned a value. /// </summary> public int CreateCount() { lock (this) { return createCount; } } /// <summary> /// Returns the number of times /// <see cref="LruCache{K, V}.Put(object, object)">LruCache&lt;K, V&gt;.Put(object, object) /// </see> /// was called. /// </summary> public int PutCount() { lock (this) { return putCount; } } /// <summary>Returns the number of values that have been evicted.</summary> /// <remarks>Returns the number of values that have been evicted.</remarks> public int EvictionCount() { lock (this) { return evictionCount; } } /// <summary> /// Returns a copy of the current contents of the cache, ordered from least /// recently accessed to most recently accessed. /// </summary> /// <remarks> /// Returns a copy of the current contents of the cache, ordered from least /// recently accessed to most recently accessed. /// </remarks> public IDictionary<K, V> Snapshot() { lock (this) { return new LinkedHashMap<K, V>(map); } } public sealed override string ToString() { lock (this) { int accesses = hitCount + missCount; int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0; return string.Format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", maxSize , hitCount, missCount, hitPercent); } } } }
// 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; // for TraceInformation using System.Threading; using System.Runtime.CompilerServices; namespace System.Threading { public enum LockRecursionPolicy { NoRecursion = 0, SupportsRecursion = 1, } // // ReaderWriterCount tracks how many of each kind of lock is held by each thread. // We keep a linked list for each thread, attached to a ThreadStatic field. // These are reused wherever possible, so that a given thread will only // allocate N of these, where N is the maximum number of locks held simultaneously // by that thread. // internal class ReaderWriterCount { // Which lock does this object belong to? This is a numeric ID for two reasons: // 1) We don't want this field to keep the lock object alive, and a WeakReference would // be too expensive. // 2) Setting the value of a long is faster than setting the value of a reference. // The "hot" paths in ReaderWriterLockSlim are short enough that this actually // matters. public long lockID; // How many reader locks does this thread hold on this ReaderWriterLockSlim instance? public int readercount; // Ditto for writer/upgrader counts. These are only used if the lock allows recursion. // But we have to have the fields on every ReaderWriterCount instance, because // we reuse it for different locks. public int writercount; public int upgradecount; // Next RWC in this thread's list. public ReaderWriterCount next; } /// <summary> /// A reader-writer lock implementation that is intended to be simple, yet very /// efficient. In particular only 1 interlocked operation is taken for any lock /// operation (we use spin locks to achieve this). The spin lock is never held /// for more than a few instructions (in particular, we never call event APIs /// or in fact any non-trivial API while holding the spin lock). /// </summary> public class ReaderWriterLockSlim : IDisposable { //Specifying if locked can be reacquired recursively. private bool _fIsReentrant; // Lock specification for myLock: This lock protects exactly the local fields associated with this // instance of ReaderWriterLockSlim. It does NOT protect the memory associated with // the events that hang off this lock (eg writeEvent, readEvent upgradeEvent). private int _myLock; //The variables controlling spinning behavior of Mylock(which is a spin-lock) private const int LockSpinCycles = 20; private const int LockSpinCount = 10; private const int LockSleep0Count = 5; // These variables allow use to avoid Setting events (which is expensive) if we don't have to. private uint _numWriteWaiters; // maximum number of threads that can be doing a WaitOne on the writeEvent private uint _numReadWaiters; // maximum number of threads that can be doing a WaitOne on the readEvent private uint _numWriteUpgradeWaiters; // maximum number of threads that can be doing a WaitOne on the upgradeEvent (at most 1). private uint _numUpgradeWaiters; //Variable used for quick check when there are no waiters. private bool _fNoWaiters; private int _upgradeLockOwnerId; private int _writeLockOwnerId; // conditions we wait on. private EventWaitHandle _writeEvent; // threads waiting to aquire a write lock go here. private EventWaitHandle _readEvent; // threads waiting to aquire a read lock go here (will be released in bulk) private EventWaitHandle _upgradeEvent; // thread waiting to acquire the upgrade lock private EventWaitHandle _waitUpgradeEvent; // thread waiting to upgrade from the upgrade lock to a write lock go here (at most one) // Every lock instance has a unique ID, which is used by ReaderWriterCount to associate itself with the lock // without holding a reference to it. private static long s_nextLockID; private long _lockID; // See comments on ReaderWriterCount. [ThreadStatic] private static ReaderWriterCount t_rwc; private bool _fUpgradeThreadHoldingRead; private const int MaxSpinCount = 20; //The uint, that contains info like if the writer lock is held, num of //readers etc. private uint _owners; //Various R/W masks //Note: //The Uint is divided as follows: // //Writer-Owned Waiting-Writers Waiting Upgraders Num-Readers // 31 30 29 28.......0 // //Dividing the uint, allows to vastly simplify logic for checking if a //reader should go in etc. Setting the writer bit will automatically //make the value of the uint much larger than the max num of readers //allowed, thus causing the check for max_readers to fail. private const uint WRITER_HELD = 0x80000000; private const uint WAITING_WRITERS = 0x40000000; private const uint WAITING_UPGRADER = 0x20000000; //The max readers is actually one less then its theoretical max. //This is done in order to prevent reader count overflows. If the reader //count reaches max, other readers will wait. private const uint MAX_READER = 0x10000000 - 2; private const uint READER_MASK = 0x10000000 - 1; private bool _fDisposed; private void InitializeThreadCounts() { _upgradeLockOwnerId = -1; _writeLockOwnerId = -1; } public ReaderWriterLockSlim() : this(LockRecursionPolicy.NoRecursion) { } public ReaderWriterLockSlim(LockRecursionPolicy recursionPolicy) { if (recursionPolicy == LockRecursionPolicy.SupportsRecursion) { _fIsReentrant = true; } InitializeThreadCounts(); _fNoWaiters = true; _lockID = Interlocked.Increment(ref s_nextLockID); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static bool IsRWEntryEmpty(ReaderWriterCount rwc) { if (rwc.lockID == 0) return true; else if (rwc.readercount == 0 && rwc.writercount == 0 && rwc.upgradecount == 0) return true; else return false; } private bool IsRwHashEntryChanged(ReaderWriterCount lrwc) { return lrwc.lockID != _lockID; } /// <summary> /// This routine retrieves/sets the per-thread counts needed to enforce the /// various rules related to acquiring the lock. /// /// DontAllocate is set to true if the caller just wants to get an existing /// entry for this thread, but doesn't want to add one if an existing one /// could not be found. /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] private ReaderWriterCount GetThreadRWCount(bool dontAllocate) { ReaderWriterCount rwc = t_rwc; ReaderWriterCount empty = null; while (rwc != null) { if (rwc.lockID == _lockID) return rwc; if (!dontAllocate && empty == null && IsRWEntryEmpty(rwc)) empty = rwc; rwc = rwc.next; } if (dontAllocate) return null; if (empty == null) { empty = new ReaderWriterCount(); empty.next = t_rwc; t_rwc = empty; } empty.lockID = _lockID; return empty; } public void EnterReadLock() { TryEnterReadLock(-1); } // // Common timeout support // private struct TimeoutTracker { private int _total; private int _start; public TimeoutTracker(TimeSpan timeout) { long ltm = (long)timeout.TotalMilliseconds; if (ltm < -1 || ltm > (long)Int32.MaxValue) throw new ArgumentOutOfRangeException(nameof(timeout)); _total = (int)ltm; if (_total != -1 && _total != 0) _start = Environment.TickCount; else _start = 0; } public TimeoutTracker(int millisecondsTimeout) { if (millisecondsTimeout < -1) throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); _total = millisecondsTimeout; if (_total != -1 && _total != 0) _start = Environment.TickCount; else _start = 0; } public int RemainingMilliseconds { get { if (_total == -1 || _total == 0) return _total; int elapsed = Environment.TickCount - _start; // elapsed may be negative if TickCount has overflowed by 2^31 milliseconds. if (elapsed < 0 || elapsed >= _total) return 0; return _total - elapsed; } } public bool IsExpired { get { return RemainingMilliseconds == 0; } } } public bool TryEnterReadLock(TimeSpan timeout) { return TryEnterReadLock(new TimeoutTracker(timeout)); } public bool TryEnterReadLock(int millisecondsTimeout) { return TryEnterReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterReadLock(TimeoutTracker timeout) { return TryEnterReadLockCore(timeout); } private bool TryEnterReadLockCore(TimeoutTracker timeout) { if (_fDisposed) throw new ObjectDisposedException(null); ReaderWriterCount lrwc = null; int id = Environment.CurrentManagedThreadId; if (!_fIsReentrant) { if (id == _writeLockOwnerId) { //Check for AW->AR throw new LockRecursionException(SR.LockRecursionException_ReadAfterWriteNotAllowed); } EnterMyLock(); lrwc = GetThreadRWCount(false); //Check if the reader lock is already acquired. Note, we could //check the presence of a reader by not allocating rwc (But that //would lead to two lookups in the common case. It's better to keep //a count in the structure). if (lrwc.readercount > 0) { ExitMyLock(); throw new LockRecursionException(SR.LockRecursionException_RecursiveReadNotAllowed); } else if (id == _upgradeLockOwnerId) { //The upgrade lock is already held. //Update the global read counts and exit. lrwc.readercount++; _owners++; ExitMyLock(); return true; } } else { EnterMyLock(); lrwc = GetThreadRWCount(false); if (lrwc.readercount > 0) { lrwc.readercount++; ExitMyLock(); return true; } else if (id == _upgradeLockOwnerId) { //The upgrade lock is already held. //Update the global read counts and exit. lrwc.readercount++; _owners++; ExitMyLock(); _fUpgradeThreadHoldingRead = true; return true; } else if (id == _writeLockOwnerId) { //The write lock is already held. //Update global read counts here, lrwc.readercount++; _owners++; ExitMyLock(); return true; } } bool retVal = true; int spincount = 0; for (; ;) { // We can enter a read lock if there are only read-locks have been given out // and a writer is not trying to get in. if (_owners < MAX_READER) { // Good case, there is no contention, we are basically done _owners++; // Indicate we have another reader lrwc.readercount++; break; } if (spincount < MaxSpinCount) { ExitMyLock(); if (timeout.IsExpired) return false; spincount++; SpinWait(spincount); EnterMyLock(); //The per-thread structure may have been recycled as the lock is acquired (due to message pumping), load again. if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(false); continue; } // Drat, we need to wait. Mark that we have waiters and wait. if (_readEvent == null) // Create the needed event { LazyCreateEvent(ref _readEvent, false); if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(false); continue; // since we left the lock, start over. } retVal = WaitOnEvent(_readEvent, ref _numReadWaiters, timeout, isWriteWaiter: false); if (!retVal) { return false; } if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(false); } ExitMyLock(); return retVal; } public void EnterWriteLock() { TryEnterWriteLock(-1); } public bool TryEnterWriteLock(TimeSpan timeout) { return TryEnterWriteLock(new TimeoutTracker(timeout)); } public bool TryEnterWriteLock(int millisecondsTimeout) { return TryEnterWriteLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterWriteLock(TimeoutTracker timeout) { return TryEnterWriteLockCore(timeout); } private bool TryEnterWriteLockCore(TimeoutTracker timeout) { if (_fDisposed) throw new ObjectDisposedException(null); int id = Environment.CurrentManagedThreadId; ReaderWriterCount lrwc; bool upgradingToWrite = false; if (!_fIsReentrant) { if (id == _writeLockOwnerId) { //Check for AW->AW throw new LockRecursionException(SR.LockRecursionException_RecursiveWriteNotAllowed); } else if (id == _upgradeLockOwnerId) { //AU->AW case is allowed once. upgradingToWrite = true; } EnterMyLock(); lrwc = GetThreadRWCount(true); //Can't acquire write lock with reader lock held. if (lrwc != null && lrwc.readercount > 0) { ExitMyLock(); throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed); } } else { EnterMyLock(); lrwc = GetThreadRWCount(false); if (id == _writeLockOwnerId) { lrwc.writercount++; ExitMyLock(); return true; } else if (id == _upgradeLockOwnerId) { upgradingToWrite = true; } else if (lrwc.readercount > 0) { //Write locks may not be acquired if only read locks have been //acquired. ExitMyLock(); throw new LockRecursionException(SR.LockRecursionException_WriteAfterReadNotAllowed); } } int spincount = 0; bool retVal = true; for (; ;) { if (IsWriterAcquired()) { // Good case, there is no contention, we are basically done SetWriterAcquired(); break; } //Check if there is just one upgrader, and no readers. //Assumption: Only one thread can have the upgrade lock, so the //following check will fail for all other threads that may sneak in //when the upgrading thread is waiting. if (upgradingToWrite) { uint readercount = GetNumReaders(); if (readercount == 1) { //Good case again, there is just one upgrader, and no readers. SetWriterAcquired(); // indicate we have a writer. break; } else if (readercount == 2) { if (lrwc != null) { if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(false); if (lrwc.readercount > 0) { //This check is needed for EU->ER->EW case, as the owner count will be two. Debug.Assert(_fIsReentrant); Debug.Assert(_fUpgradeThreadHoldingRead); //Good case again, there is just one upgrader, and no readers. SetWriterAcquired(); // indicate we have a writer. break; } } } } if (spincount < MaxSpinCount) { ExitMyLock(); if (timeout.IsExpired) return false; spincount++; SpinWait(spincount); EnterMyLock(); continue; } if (upgradingToWrite) { if (_waitUpgradeEvent == null) // Create the needed event { LazyCreateEvent(ref _waitUpgradeEvent, true); continue; // since we left the lock, start over. } Debug.Assert(_numWriteUpgradeWaiters == 0, "There can be at most one thread with the upgrade lock held."); retVal = WaitOnEvent(_waitUpgradeEvent, ref _numWriteUpgradeWaiters, timeout, isWriteWaiter: true); //The lock is not held in case of failure. if (!retVal) return false; } else { // Drat, we need to wait. Mark that we have waiters and wait. if (_writeEvent == null) // create the needed event. { LazyCreateEvent(ref _writeEvent, true); continue; // since we left the lock, start over. } retVal = WaitOnEvent(_writeEvent, ref _numWriteWaiters, timeout, isWriteWaiter: true); //The lock is not held in case of failure. if (!retVal) return false; } } Debug.Assert((_owners & WRITER_HELD) > 0); if (_fIsReentrant) { if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(false); lrwc.writercount++; } ExitMyLock(); _writeLockOwnerId = id; return true; } public void EnterUpgradeableReadLock() { TryEnterUpgradeableReadLock(-1); } public bool TryEnterUpgradeableReadLock(TimeSpan timeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(timeout)); } public bool TryEnterUpgradeableReadLock(int millisecondsTimeout) { return TryEnterUpgradeableReadLock(new TimeoutTracker(millisecondsTimeout)); } private bool TryEnterUpgradeableReadLock(TimeoutTracker timeout) { return TryEnterUpgradeableReadLockCore(timeout); } private bool TryEnterUpgradeableReadLockCore(TimeoutTracker timeout) { if (_fDisposed) throw new ObjectDisposedException(null); int id = Environment.CurrentManagedThreadId; ReaderWriterCount lrwc; if (!_fIsReentrant) { if (id == _upgradeLockOwnerId) { //Check for AU->AU throw new LockRecursionException(SR.LockRecursionException_RecursiveUpgradeNotAllowed); } else if (id == _writeLockOwnerId) { //Check for AU->AW throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterWriteNotAllowed); } EnterMyLock(); lrwc = GetThreadRWCount(true); //Can't acquire upgrade lock with reader lock held. if (lrwc != null && lrwc.readercount > 0) { ExitMyLock(); throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } else { EnterMyLock(); lrwc = GetThreadRWCount(false); if (id == _upgradeLockOwnerId) { lrwc.upgradecount++; ExitMyLock(); return true; } else if (id == _writeLockOwnerId) { //Write lock is already held, Just update the global state //to show presence of upgrader. Debug.Assert((_owners & WRITER_HELD) > 0); _owners++; _upgradeLockOwnerId = id; lrwc.upgradecount++; if (lrwc.readercount > 0) _fUpgradeThreadHoldingRead = true; ExitMyLock(); return true; } else if (lrwc.readercount > 0) { //Upgrade locks may not be acquired if only read locks have been //acquired. ExitMyLock(); throw new LockRecursionException(SR.LockRecursionException_UpgradeAfterReadNotAllowed); } } bool retVal = true; int spincount = 0; for (; ;) { //Once an upgrade lock is taken, it's like having a reader lock held //until upgrade or downgrade operations are performed. if ((_upgradeLockOwnerId == -1) && (_owners < MAX_READER)) { _owners++; _upgradeLockOwnerId = id; break; } if (spincount < MaxSpinCount) { ExitMyLock(); if (timeout.IsExpired) return false; spincount++; SpinWait(spincount); EnterMyLock(); continue; } // Drat, we need to wait. Mark that we have waiters and wait. if (_upgradeEvent == null) // Create the needed event { LazyCreateEvent(ref _upgradeEvent, true); continue; // since we left the lock, start over. } //Only one thread with the upgrade lock held can proceed. retVal = WaitOnEvent(_upgradeEvent, ref _numUpgradeWaiters, timeout, isWriteWaiter: false); if (!retVal) return false; } if (_fIsReentrant) { //The lock may have been dropped getting here, so make a quick check to see whether some other //thread did not grab the entry. if (IsRwHashEntryChanged(lrwc)) lrwc = GetThreadRWCount(false); lrwc.upgradecount++; } ExitMyLock(); return true; } public void ExitReadLock() { ReaderWriterCount lrwc = null; EnterMyLock(); lrwc = GetThreadRWCount(true); if (lrwc == null || lrwc.readercount < 1) { //You have to be holding the read lock to make this call. ExitMyLock(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedRead); } if (_fIsReentrant) { if (lrwc.readercount > 1) { lrwc.readercount--; ExitMyLock(); return; } if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) { _fUpgradeThreadHoldingRead = false; } } Debug.Assert(_owners > 0, "ReleasingReaderLock: releasing lock and no read lock taken"); --_owners; Debug.Assert(lrwc.readercount == 1); lrwc.readercount--; ExitAndWakeUpAppropriateWaiters(); } public void ExitWriteLock() { ReaderWriterCount lrwc; if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _writeLockOwnerId) { //You have to be holding the write lock to make this call. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); } EnterMyLock(); } else { EnterMyLock(); lrwc = GetThreadRWCount(false); if (lrwc == null) { ExitMyLock(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); } if (lrwc.writercount < 1) { ExitMyLock(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedWrite); } lrwc.writercount--; if (lrwc.writercount > 0) { ExitMyLock(); return; } } Debug.Assert((_owners & WRITER_HELD) > 0, "Calling ReleaseWriterLock when no write lock is held"); ClearWriterAcquired(); _writeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } public void ExitUpgradeableReadLock() { ReaderWriterCount lrwc; if (!_fIsReentrant) { if (Environment.CurrentManagedThreadId != _upgradeLockOwnerId) { //You have to be holding the upgrade lock to make this call. throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); } EnterMyLock(); } else { EnterMyLock(); lrwc = GetThreadRWCount(true); if (lrwc == null) { ExitMyLock(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); } if (lrwc.upgradecount < 1) { ExitMyLock(); throw new SynchronizationLockException(SR.SynchronizationLockException_MisMatchedUpgrade); } lrwc.upgradecount--; if (lrwc.upgradecount > 0) { ExitMyLock(); return; } _fUpgradeThreadHoldingRead = false; } _owners--; _upgradeLockOwnerId = -1; ExitAndWakeUpAppropriateWaiters(); } /// <summary> /// A routine for lazily creating a event outside the lock (so if errors /// happen they are outside the lock and that we don't do much work /// while holding a spin lock). If all goes well, reenter the lock and /// set 'waitEvent' /// </summary> private void LazyCreateEvent(ref EventWaitHandle waitEvent, bool makeAutoResetEvent) { #if DEBUG Debug.Assert(MyLockHeld); Debug.Assert(waitEvent == null); #endif ExitMyLock(); EventWaitHandle newEvent; if (makeAutoResetEvent) newEvent = new AutoResetEvent(false); else newEvent = new ManualResetEvent(false); EnterMyLock(); if (waitEvent == null) // maybe someone snuck in. waitEvent = newEvent; else newEvent.Dispose(); } /// <summary> /// Waits on 'waitEvent' with a timeout /// Before the wait 'numWaiters' is incremented and is restored before leaving this routine. /// </summary> private bool WaitOnEvent( EventWaitHandle waitEvent, ref uint numWaiters, TimeoutTracker timeout, bool isWriteWaiter) { #if DEBUG Debug.Assert(MyLockHeld); #endif waitEvent.Reset(); numWaiters++; _fNoWaiters = false; //Setting these bits will prevent new readers from getting in. if (_numWriteWaiters == 1) SetWritersWaiting(); if (_numWriteUpgradeWaiters == 1) SetUpgraderWaiting(); bool waitSuccessful = false; ExitMyLock(); // Do the wait outside of any lock try { waitSuccessful = waitEvent.WaitOne(timeout.RemainingMilliseconds); } finally { EnterMyLock(); --numWaiters; if (_numWriteWaiters == 0 && _numWriteUpgradeWaiters == 0 && _numUpgradeWaiters == 0 && _numReadWaiters == 0) _fNoWaiters = true; if (_numWriteWaiters == 0) ClearWritersWaiting(); if (_numWriteUpgradeWaiters == 0) ClearUpgraderWaiting(); if (!waitSuccessful) // We may also be about to throw for some reason. Exit myLock. { if (isWriteWaiter) { // Write waiters block read waiters from acquiring the lock. Since this was the last write waiter, try // to wake up the appropriate read waiters. ExitAndWakeUpAppropriateReadWaiters(); } else ExitMyLock(); } } return waitSuccessful; } /// <summary> /// Determines the appropriate events to set, leaves the locks, and sets the events. /// </summary> private void ExitAndWakeUpAppropriateWaiters() { #if DEBUG Debug.Assert(MyLockHeld); #endif if (_fNoWaiters) { ExitMyLock(); return; } ExitAndWakeUpAppropriateWaitersPreferringWriters(); } private void ExitAndWakeUpAppropriateWaitersPreferringWriters() { uint readercount = GetNumReaders(); //We need this case for EU->ER->EW case, as the read count will be 2 in //that scenario. if (_fIsReentrant) { if (_numWriteUpgradeWaiters > 0 && _fUpgradeThreadHoldingRead && readercount == 2) { ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) _waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one). return; } } if (readercount == 1 && _numWriteUpgradeWaiters > 0) { //We have to be careful now, as we are droppping the lock. //No new writes should be allowed to sneak in if an upgrade //was pending. ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) _waitUpgradeEvent.Set(); // release all upgraders (however there can be at most one). } else if (readercount == 0 && _numWriteWaiters > 0) { ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) _writeEvent.Set(); // release one writer. } else { ExitAndWakeUpAppropriateReadWaiters(); } } private void ExitAndWakeUpAppropriateReadWaiters() { #if DEBUG Debug.Assert(MyLockHeld); #endif if (_numWriteWaiters != 0 || _numWriteUpgradeWaiters != 0 || _fNoWaiters) { ExitMyLock(); return; } Debug.Assert(_numReadWaiters != 0 || _numUpgradeWaiters != 0); bool setReadEvent = _numReadWaiters != 0; bool setUpgradeEvent = _numUpgradeWaiters != 0 && _upgradeLockOwnerId == -1; ExitMyLock(); // Exit before signaling to improve efficiency (wakee will need the lock) if (setReadEvent) _readEvent.Set(); // release all readers. if (setUpgradeEvent) _upgradeEvent.Set(); //release one upgrader. } private bool IsWriterAcquired() { return (_owners & ~WAITING_WRITERS) == 0; } private void SetWriterAcquired() { _owners |= WRITER_HELD; // indicate we have a writer. } private void ClearWriterAcquired() { _owners &= ~WRITER_HELD; } private void SetWritersWaiting() { _owners |= WAITING_WRITERS; } private void ClearWritersWaiting() { _owners &= ~WAITING_WRITERS; } private void SetUpgraderWaiting() { _owners |= WAITING_UPGRADER; } private void ClearUpgraderWaiting() { _owners &= ~WAITING_UPGRADER; } private uint GetNumReaders() { return _owners & READER_MASK; } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnterMyLock() { if (Interlocked.CompareExchange(ref _myLock, 1, 0) != 0) EnterMyLockSpin(); } private void EnterMyLockSpin() { int pc = Environment.ProcessorCount; for (int i = 0; ; i++) { if (i < LockSpinCount && pc > 1) { Helpers.Spin(LockSpinCycles * (i + 1)); // Wait a few dozen instructions to let another processor release lock. } else if (i < (LockSpinCount + LockSleep0Count)) { Helpers.Sleep(0); // Give up my quantum. } else { Helpers.Sleep(1); // Give up my quantum. } if (_myLock == 0 && Interlocked.CompareExchange(ref _myLock, 1, 0) == 0) return; } } private void ExitMyLock() { Debug.Assert(_myLock != 0, "Exiting spin lock that is not held"); Volatile.Write(ref _myLock, 0); } #if DEBUG private bool MyLockHeld { get { return _myLock != 0; } } #endif private static void SpinWait(int SpinCount) { //Exponential backoff if ((SpinCount < 5) && (Environment.ProcessorCount > 1)) { Helpers.Spin(LockSpinCycles * SpinCount); } else if (SpinCount < MaxSpinCount - 3) { Helpers.Sleep(0); } else { Helpers.Sleep(1); } } public void Dispose() { Dispose(true); } private void Dispose(bool disposing) { if (disposing && !_fDisposed) { if (WaitingReadCount > 0 || WaitingUpgradeCount > 0 || WaitingWriteCount > 0) throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose); if (IsReadLockHeld || IsUpgradeableReadLockHeld || IsWriteLockHeld) throw new SynchronizationLockException(SR.SynchronizationLockException_IncorrectDispose); if (_writeEvent != null) { _writeEvent.Dispose(); _writeEvent = null; } if (_readEvent != null) { _readEvent.Dispose(); _readEvent = null; } if (_upgradeEvent != null) { _upgradeEvent.Dispose(); _upgradeEvent = null; } if (_waitUpgradeEvent != null) { _waitUpgradeEvent.Dispose(); _waitUpgradeEvent = null; } _fDisposed = true; } } public bool IsReadLockHeld { get { if (RecursiveReadCount > 0) return true; else return false; } } public bool IsUpgradeableReadLockHeld { get { if (RecursiveUpgradeCount > 0) return true; else return false; } } public bool IsWriteLockHeld { get { if (RecursiveWriteCount > 0) return true; else return false; } } public LockRecursionPolicy RecursionPolicy { get { if (_fIsReentrant) { return LockRecursionPolicy.SupportsRecursion; } else { return LockRecursionPolicy.NoRecursion; } } } public int CurrentReadCount { get { int numreaders = (int)GetNumReaders(); if (_upgradeLockOwnerId != -1) return numreaders - 1; else return numreaders; } } public int RecursiveReadCount { get { int count = 0; ReaderWriterCount lrwc = GetThreadRWCount(true); if (lrwc != null) count = lrwc.readercount; return count; } } public int RecursiveUpgradeCount { get { if (_fIsReentrant) { int count = 0; ReaderWriterCount lrwc = GetThreadRWCount(true); if (lrwc != null) count = lrwc.upgradecount; return count; } else { if (Environment.CurrentManagedThreadId == _upgradeLockOwnerId) return 1; else return 0; } } } public int RecursiveWriteCount { get { if (_fIsReentrant) { int count = 0; ReaderWriterCount lrwc = GetThreadRWCount(true); if (lrwc != null) count = lrwc.writercount; return count; } else { if (Environment.CurrentManagedThreadId == _writeLockOwnerId) return 1; else return 0; } } } public int WaitingReadCount { get { return (int)_numReadWaiters; } } public int WaitingUpgradeCount { get { return (int)_numUpgradeWaiters; } } public int WaitingWriteCount { get { return (int)_numWriteWaiters; } } } }
#if MONO using System; using System.Diagnostics; using System.Drawing; using System.Windows.Forms; using Palaso.Email; using Palaso.Reporting; using System.IO; namespace Palaso.Reporting { public class PalasoErrorDialog : Form, IDisposable { #region Member variables private Label label3; private TextBox _details; private TextBox _pleaseHelpText; private TextBox m_reproduce; private bool _isLethal; private Button _sendAndCloseButton; private TextBox _notificationText; private TextBox textBox1; private ComboBox _methodCombo; private Button _privacyNoticeButton; private Label _emailAddress; private static bool s_doIgnoreReport = false; private string _errorFileName; #endregion public PalasoErrorDialog(bool isLethal, string errorFileName, string emailAddress, string emailSubject) { _isLethal = isLethal; _errorFileName = errorFileName; ErrorReport.EmailAddress = emailAddress; ErrorReport.EmailSubject = emailSubject; PrepareDialog(); using (StreamReader reader = File.OpenText(errorFileName)) { _details.Text = reader.ReadToEnd(); } } #region IDisposable override /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) { throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected override void Dispose(bool disposing) { //Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (IsDisposed) { return; } if (disposing) { // Dispose managed resources here. } // Dispose unmanaged resources here, whether disposing is true or false. base.Dispose(disposing); } #endregion IDisposable override #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PalasoErrorDialog)); this.m_reproduce = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this._details = new System.Windows.Forms.TextBox(); this._sendAndCloseButton = new System.Windows.Forms.Button(); this._pleaseHelpText = new System.Windows.Forms.TextBox(); this._notificationText = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this._methodCombo = new System.Windows.Forms.ComboBox(); this._privacyNoticeButton = new System.Windows.Forms.Button(); this._emailAddress = new System.Windows.Forms.Label(); this.SuspendLayout(); // // m_reproduce // this.m_reproduce.AcceptsReturn = true; this.m_reproduce.AcceptsTab = true; resources.ApplyResources(this.m_reproduce, "m_reproduce"); this.m_reproduce.Name = "m_reproduce"; // // label3 // resources.ApplyResources(this.label3, "label3"); this.label3.Name = "label3"; // // _details // resources.ApplyResources(this._details, "_details"); this._details.BackColor = System.Drawing.SystemColors.ControlLightLight; this._details.Name = "_details"; this._details.ReadOnly = true; // // _sendAndCloseButton // resources.ApplyResources(this._sendAndCloseButton, "_sendAndCloseButton"); this._sendAndCloseButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._sendAndCloseButton.Name = "_sendAndCloseButton"; this._sendAndCloseButton.Click += new System.EventHandler(this.btnClose_Click); // // _pleaseHelpText // resources.ApplyResources(this._pleaseHelpText, "_pleaseHelpText"); this._pleaseHelpText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._pleaseHelpText.BorderStyle = System.Windows.Forms.BorderStyle.None; this._pleaseHelpText.ForeColor = System.Drawing.Color.Black; this._pleaseHelpText.Name = "_pleaseHelpText"; this._pleaseHelpText.ReadOnly = true; // // _notificationText // resources.ApplyResources(this._notificationText, "_notificationText"); this._notificationText.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this._notificationText.BorderStyle = System.Windows.Forms.BorderStyle.None; this._notificationText.ForeColor = System.Drawing.Color.Black; this._notificationText.Name = "_notificationText"; this._notificationText.ReadOnly = true; // // textBox1 // resources.ApplyResources(this.textBox1, "textBox1"); this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox1.ForeColor = System.Drawing.Color.Black; this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; // // _methodCombo // resources.ApplyResources(this._methodCombo, "_methodCombo"); this._methodCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this._methodCombo.FormattingEnabled = true; this._methodCombo.Name = "_methodCombo"; this._methodCombo.SelectedIndexChanged += new System.EventHandler(this._methodCombo_SelectedIndexChanged); // // _privacyNoticeButton // resources.ApplyResources(this._privacyNoticeButton, "_privacyNoticeButton"); this._privacyNoticeButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this._privacyNoticeButton.Image = global::Palaso.Properties.Resources.spy16x16; this._privacyNoticeButton.Name = "_privacyNoticeButton"; this._privacyNoticeButton.UseVisualStyleBackColor = true; this._privacyNoticeButton.Click += new System.EventHandler(this._privacyNoticeButton_Click); // // _emailAddress // resources.ApplyResources(this._emailAddress, "_emailAddress"); this._emailAddress.ForeColor = System.Drawing.Color.DimGray; this._emailAddress.Name = "_emailAddress"; // // PalasoErrorDialog // this.AcceptButton = this._sendAndCloseButton; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(255)))), ((int)(((byte)(192))))); //this.ControlBox = false; this.Controls.Add(this._emailAddress); this.Controls.Add(this._privacyNoticeButton); this.Controls.Add(this._methodCombo); this.Controls.Add(this.textBox1); this.Controls.Add(this.m_reproduce); this.Controls.Add(this._notificationText); this.Controls.Add(this._pleaseHelpText); this.Controls.Add(this._details); this.Controls.Add(this.label3); this.Controls.Add(this._sendAndCloseButton); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PalasoErrorDialog"; this.TopMost = true; this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.PalasoErrorDialog_KeyPress); this.ResumeLayout(false); this.PerformLayout(); } private void SetupMethodCombo() { _methodCombo.Items.Clear(); _methodCombo.Items.Add(new ReportingMethod("Send using my email program", "&Email", "mapiWithPopup", SendViaEmail)); #if !MONO // DG May 2012: doesn't stay on clipboard after app closes on mono so not using it _methodCombo.Items.Add(new ReportingMethod("Copy to clipboard", "&Copy", "clipboard", PutOnClipboard)); #endif _methodCombo.Items.Add(new ReportingMethod("Open as text file", "&Open", "textfile", OpenTextFile)); } class ReportingMethod { private readonly string _label; public readonly string CloseButtonLabel; public readonly string Id; public readonly Func<bool> Method; public ReportingMethod(string label, string closeButtonLabel, string id, Func<bool> method) { _label = label; CloseButtonLabel = closeButtonLabel; Id = id; Method = method; } public override string ToString() { return _label; } } #endregion /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// ------------------------------------------------------------------------------------ protected void GatherData() { _details.Text += "\r\nTo Reproduce: " + m_reproduce.Text + "\r\n"; } private void PrepareDialog() { CheckDisposed(); Font = SystemFonts.MessageBoxFont; // // Required for Windows Form Designer support // InitializeComponent(); _emailAddress.Text = ErrorReport.EmailAddress; SetupMethodCombo(); foreach (ReportingMethod method in _methodCombo.Items) { if (ErrorReportSettings.Default.ReportingMethod == method.Id) { SelectedMethod = method; break; } } if (!_isLethal) { BackColor = Color.FromArgb(255, 255, 192); //yellow _notificationText.Text = "Take Courage. It'll work out."; _notificationText.BackColor = BackColor; _pleaseHelpText.BackColor = BackColor; textBox1.BackColor = BackColor; } SetupCloseButtonText(); } /// ------------------------------------------------------------------------------------ /// <summary> /// /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ private void btnClose_Click(object sender, EventArgs e) { ErrorReportSettings.Default.ReportingMethod = ((ReportingMethod) (_methodCombo.SelectedItem)).Id; ErrorReportSettings.Default.Save(); if (ModifierKeys.Equals(Keys.Shift)) { return; } GatherData(); // Clipboard.SetDataObject(_details.Text, true); if (SelectedMethod.Method()) { CloseUp(); } else { PutOnClipboard(); CloseUp(); } } private bool PutOnClipboard() { if (ErrorReport.EmailAddress != null) { _details.Text = String.Format(ReportingStrings.ksPleaseEMailThisToUs, ErrorReport.EmailAddress, _details.Text); } Clipboard.SetDataObject(_details.Text, true); return true; } private bool OpenTextFile() { if (ErrorReport.EmailAddress != null) { _details.Text = String.Format(ReportingStrings.ksPleaseEMailThisToUs, ErrorReport.EmailAddress, _details.Text); } string tempdirPath = Path.GetDirectoryName(_errorFileName); string tempFileName = Path.Combine (tempdirPath, "Report.txt"); File.WriteAllText(tempFileName, _details.Text); Process.Start(tempFileName); return true; } private bool SendViaEmail() { try { var emailProvider = EmailProviderFactory.PreferredEmailProvider(); var emailMessage = emailProvider.CreateMessage(); emailMessage.To.Add(ErrorReport.EmailAddress); emailMessage.Subject = ErrorReport.EmailSubject; emailMessage.Body = _details.Text; if (emailMessage.Send(emailProvider)) { CloseUp(); return true; } } catch (Exception) { Console.WriteLine("First attempt at creating email failed"); //swallow it and go to the alternate method } try { //EmailMessage msg = new EmailMessage(); // This currently does not work. The main issue seems to be the length of the error report. mailto // apparently has some limit on the length of the message, and we are exceeding that. var emailProvider = EmailProviderFactory.PreferredEmailProvider(); var emailMessage = emailProvider.CreateMessage(); emailMessage.To.Add(ErrorReport.EmailAddress); emailMessage.Subject = ErrorReport.EmailSubject; if (Environment.OSVersion.Platform == PlatformID.Unix) { string tempdirPath = Path.GetDirectoryName(_errorFileName); string tempFileName = Path.Combine (tempdirPath, "Report.txt"); File.WriteAllText(tempFileName, _details.Text); emailMessage.Body = "The error is in the attached file.\n\n<Please give a quick explanation for the developers here>"; emailMessage.AttachmentFilePath.Add(tempFileName); } else { PutOnClipboard(); emailMessage.Body = "<Details of the crash have been copied to the clipboard. Please paste them here>"; } if (emailMessage.Send(emailProvider)) { CloseUp(); return true; } } catch (Exception error) { PutOnClipboard(); ErrorReport.NotifyUserOfProblem(error, "This program wasn't able to get your email program, if you have one, to send the error message. The contents of the error message has been placed on your Clipboard."); return false; } return false; } /// ------------------------------------------------------------------------------------ /// <summary> /// Shows the attempt to continue label if the shift key is pressed /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected override void OnKeyDown(KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && Visible) { _sendAndCloseButton.Text = "Continue"; } base.OnKeyDown(e); } /// ------------------------------------------------------------------------------------ /// <summary> /// Hides the attempt to continue label if the shift key is pressed /// </summary> /// <param name="e"></param> /// ------------------------------------------------------------------------------------ protected override void OnKeyUp(KeyEventArgs e) { if (e.KeyCode == Keys.ShiftKey && Visible) { SetupCloseButtonText(); } base.OnKeyUp(e); } private void OnJustExit_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { CloseUp(); } private void _methodCombo_SelectedIndexChanged(object sender, EventArgs e) { SetupCloseButtonText(); } private void SetupCloseButtonText() { _sendAndCloseButton.Text = SelectedMethod.CloseButtonLabel; if (!_isLethal) { // _dontSendEmailLink.Text = "Don't Send Email"; } else { _sendAndCloseButton.Text += " and Exit"; } } private ReportingMethod SelectedMethod { get { return ((ReportingMethod) _methodCombo.SelectedItem); } set { _methodCombo.SelectedItem = value; } } private void _privacyNoticeButton_Click(object sender, EventArgs e) { MessageBox.Show( @"If you don't care who reads your bug report, you can skip this notice. When you submit a crash report or other issue, the contents of your email go in our issue tracking system, 'jira', which is available via the web at http://jira.palso.org/issues. This is the normal way to handle issues in an open-source project. Our issue-tracking system is not searchable by those without an account. Therefore, someone searching via Google will not find your bug reports. However, anyone can make an account and then read what you sent us. So if you have something private to say, please send it to one of the developers privately with a note that you don't want the issue in our issue tracking system. If need be, we'll make some kind of sanitized place-holder for your issue so that we don't lose it. "); } private void PalasoErrorDialog_KeyPress(object sender, KeyPressEventArgs e) { if(e.KeyChar== 27)//ESCAPE { CloseUp(); } } private void CloseUp() { Close(); } } } #endif
<?cs def:frame_picture(image, link, size) ?> <TABLE cellspacing=0 cellpadding=0 border=0 WIDTH=1%> <TR> <TD><IMG name="frame0" border=0 height=8 width=8 src="0.gif"></TD> <TD><IMG name="frame1" border=0 height=8 width=<?cs var:image.width ?> src="1.gif"></TD> <TD><IMG name="frame2" border=0 height=8 width=8 src="2.gif"></TD> </TR> <TR> <TD><IMG name="frame3" border=0 height=<?cs var:image.height ?> width=8 src="3.gif"></TD> <TD><a href="<?cs var:link ?>"><img border=0 width=<?cs var:image.width ?> height=<?cs var:image.height ?> src="<?cs var:CGI.PathInfo?>?image=<?cs var:url_escape(Album) ?>/<?cs var:url_escape(image) ?>&width=<?cs var:image.width ?>&height=<?cs var:image.height ?>"></a></TD> <TD><IMG name="frame4" border=0 height=<?cs var:image.height ?> width=8 src="4.gif"></TD> </TR> <TR> <TD><IMG name="frame5" border=0 height=8 width=8 src="5.gif"></TD> <TD><IMG name="frame6" border=0 height=8 width=<?cs var:image.width ?> src="6.gif"></TD> <TD><IMG name="frame7" border=0 height=8 width=8 src="7.gif"></TD> </TR> </TABLE> <?cs /def ?> <HTML> <HEAD> <TITLE><?cs var:Title ?><?cs if:Context == "album" ?> <?cs var:Album.Raw ?> <?cs var:Album.Start + #1 ?> - <?cs var:Album.Next ?> of <?cs var:Album.Count ?><?cs else ?> <?cs var:Album.Raw ?> - <?cs var:Picture ?><?cs /if ?></TITLE> </HEAD> <BODY BGCOLOR=#ffffff> <?cs include:"/home/www/header.html" ?> <A HREF="<?cs var:CGI.PathInfo?>"><?cs var:Title ?></A> <?cs each:part = Album.Path ?> <?cs if:part.path == Album ?> / <?cs var:part ?> <?cs else ?> / <A HREF="<?cs var:CGI.PathInfo?>?album=<?cs var:url_escape(part.path) ?>"><?cs var:part ?></A> <?cs /if ?> <?cs /each ?> <?cs if:Context == "album" ?> <?cs if:Albums.0 ?> <p> <?cs each:album = Albums ?> <TABLE BORDER=0 CELLSPACING=1 CELLPADDING=1 width=100%> <TR><TD style="border-bottom:2px solid #888888;" COLSPAN=4><font size=+2> <a href="<?cs var:CGI.PathInfo?>?album=<?cs if:Album ?><?cs var:Album ?>/<?cs /if ?><?cs var:album ?>"><?cs var:album ?></a></font> (<?cs var:album.Count ?> images) </td></tr> <TR> <?cs each:image = album.Images ?> <td align=center> <TABLE cellspacing=0 cellpadding=0 border=0 WIDTH=1%> <TR> <TD><IMG name="frame0" border=0 height=8 width=8 src="0.gif"></TD> <TD><IMG name="frame1" border=0 height=8 width=<?cs var:image.width ?> src="1.gif"></TD> <TD><IMG name="frame2" border=0 height=8 width=8 src="2.gif"></TD> </TR> <TR> <TD><IMG name="frame3" border=0 height=<?cs var:image.height ?> width=8 src="3.gif"></TD> <TD><a href="<?cs var:CGI.PathInfo?>?album=<?cs if:Album ?><?cs var:Album ?>/<?cs /if ?><?cs var:album ?>&picture=<?cs var:url_escape(image) ?>"><img border=0 width=<?cs var:image.width ?> height=<?cs var:image.height ?> src="<?cs var:CGI.PathInfo?>?image=<?cs if:Album ?><?cs var:url_escape(Album) ?>/<?cs /if ?><?cs var:url_escape(album) ?>/<?cs var:url_escape(image) ?>&width=<?cs var:image.width ?>&height=<?cs var:image.height ?>"></a></TD> <TD><IMG name="frame4" border=0 height=<?cs var:image.height ?> width=8 src="4.gif"></TD> </TR> <TR> <TD><IMG name="frame5" border=0 height=8 width=8 src="5.gif"></TD> <TD><IMG name="frame6" border=0 height=8 width=<?cs var:image.width ?> src="6.gif"></TD> <TD><IMG name="frame7" border=0 height=8 width=8 src="7.gif"></TD> </TR> </TABLE> </td> <?cs /each ?> </TR> </TABLE> <?cs /each ?> <?cs /if ?> <?cs if:#Album.Count ?> <DIV ALIGN=RIGHT> <?cs if:Album.Start > #0 ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>">First</A> <?cs else ?> First <?cs /if ?> &nbsp; <?cs if:Album.Prev > #0 ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&start=<?cs var:Album.Prev ?>">Prev</A> <?cs else ?> Prev <?cs /if ?> &nbsp; <?cs var:#Album.Start + #1 ?> - <?cs var:#Album.Next ?> of <?cs var:#Album.Count ?> &nbsp; <?cs if:#Album.Next < #Album.Count ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&start=<?cs var:Album.Next ?>">Next</A> <?cs else ?> Next <?cs /if ?> &nbsp; <?cs if:#Album.Start < #Album.Last ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&start=<?cs var:Album.Last ?>">Last</A> <?cs else ?> Last <?cs /if ?> </DIV> <TABLE> <TR> <?cs set:TotalWidth = #0 ?> <?cs each:image=Images ?> <?cs set:nextWidth = #TotalWidth + #image.width ?> <?cs if:#nextWidth > #PageWidth ?></TR></TABLE><TABLE><TR><?cs set:TotalWidth = image.width ?><?cs else ?><?cs set:TotalWidth = nextWidth ?><?cs /if ?> <TD><?cs call:frame_picture(image, CGI.PathInfo + "?album=" + Album + "&picture=" + url_escape(image), "8") ?></TD> <?cs /each ?> </TR> </TABLE> <DIV ALIGN=RIGHT> <?cs if:Album.Start > #0 ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>">First</A> <?cs else ?> First <?cs /if ?> &nbsp; <?cs if:Album.Prev > #0 ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&start=<?cs var:Album.Prev ?>">Prev</A> <?cs else ?> Prev <?cs /if ?> &nbsp; <?cs var:#Album.Start + #1 ?> - <?cs var:#Album.Next ?> of <?cs var:#Album.Count ?> &nbsp; <?cs if:#Album.Next < #Album.Count ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&start=<?cs var:Album.Next ?>">Next</A> <?cs else ?> Next <?cs /if ?> &nbsp; <?cs if:#Album.Start < #Album.Last ?> <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&start=<?cs var:Album.Last ?>">Last</A> <?cs else ?> Last <?cs /if ?> </DIV> <?cs /if ?> <?cs else ?><?cs # picture ?> <DIV ALIGN=RIGHT> <?cs set:count = #0 ?> <?cs each:image=Show ?> <a href="<?cs var:CGI.PathInfo?>?album=<?cs var:Album ?>&picture=<?cs var:url_escape(image) ?>"> <?cs if:count == #0 ?> More <?cs elif:count == #1 ?> Previous <?cs elif:count == #2 ?> Image #<?cs Name:image ?> <?cs elif:count == #3 ?> Next <?cs elif:count == #4 ?> More <?cs /if ?> <?cs set:count = count + #1 ?> </a> &nbsp; <?cs /each ?> </DIV> <hr> <TABLE cellspacing=0 cellpadding=0 border=0 align=center> <TR> <TD><IMG name="frame0" border=0 height=18 width=18 src="0.gif"></TD> <TD><IMG name="frame1" border=0 height=18 width=<?cs var:Picture.width ?> src="1.gif"></TD> <TD><IMG name="frame2" border=0 height=18 width=18 src="2.gif"></TD> </TR> <TR> <TD><IMG name="frame3" border=0 height=<?cs var:Picture.height ?> width=18 src="3.gif"></TD> <?cs if:#0 && Picture.avi ?> <TD><EMBED CONTROLborder=0 width=<?cs var:Picture.width?> height=<?cs var:Picture.height?> src="<?cs var:CGI.PathInfo?>?image=<?cs var:url_escape(Album) ?>/<?cs var:url_escape(Picture.avi) ?>" AUTOSTART=true></EMBED></TD> <?cs else ?> <TD><img border=0 width=<?cs var:Picture.width?> height=<?cs var:Picture.height?> src="<?cs var:CGI.PathInfo?>?image=<?cs var:url_escape(Album) ?>/<?cs var:url_escape(Picture) ?>&width=<?cs var:Picture.width ?>&height=<?cs var:Picture.height?>&quality=1" <?cs if:Picture.avi ?>dynsrc="<?cs var:CGI.PathInfo?>?image=<?cs var:url_escape(Album) ?>/<?cs var:url_escape(Picture.avi) ?>&width=<?cs var:Picture.width ?>&height=<?cs var:Picture.height?>&quality=1"<?cs /if ?>></TD> <?cs /if ?> <TD><IMG name="frame4" border=0 height=<?cs var:Picture.height ?> width=18 src="4.gif"></TD> </TR> <TR> <TD><IMG name="frame5" border=0 height=18 width=18 src="5.gif"></TD> <TD><IMG name="frame6" border=0 height=18 width=<?cs var:Picture.width ?> src="6.gif"></TD> <TD><IMG name="frame7" border=0 height=18 width=18 src="7.gif"></TD> </TR> <TR><TD COLSPAN=3 ALIGN=CENTER> <?cs if:Picture.avi ?> <a href="<?cs var:CGI.PathInfo?>?image=<?cs var:url_escape(Album) ?>/<?cs var:url_escape(Picture.avi) ?>">Raw Video <?cs var:html_escape(Picture.avi) ?></a> <?cs else ?> <a href="<?cs var:CGI.PathInfo?>?image=<?cs var:url_escape(Album) ?>/<?cs var:url_escape(Picture) ?>&quality=1">Raw Picture <?cs var:html_escape(Picture) ?></a> <?cs /if ?> </TD></TR> </TABLE> <CENTER> <TABLE> <TR> <?cs each:image=Show ?> <?cs if:image != Picture ?> <TD><?cs call:frame_picture(image, CGI.PathInfo + "?album=" + Album + "&picture=" + url_escape(image), "8") ?></TD> <?cs /if ?> <?cs /each ?> </TR> </TABLE> </CENTER> <?cs if:0 && CGI.RemoteAddress == "66.125.228.221" ?> &nbsp; Rotate: <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&picture=<?cs var:url_escape(Picture) ?>&rotate=-90">Left</A> - <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&picture=<?cs var:url_escape(Picture) ?>&rotate=90">Right</A> - <A HREF="<?cs var:CGI.PathInfo ?>?album=<?cs var:Album ?>&picture=<?cs var:url_escape(Picture) ?>&rotate=180">Flip</A> <?cs /if ?> <?cs /if ?> <?cs include:"/home/www/footer.html" ?> </BODY> </HTML>
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Network.Fluent { using Microsoft.Azure; using Microsoft.Azure.Management.Network.Fluent.Models; using Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Definition; using Microsoft.Azure.Management.Network.Fluent.NetworkInterface.Update; using Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.Definition; using Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.Update; using Microsoft.Azure.Management.Network.Fluent.NicIPConfiguration.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.HasPrivateIPAddress.Definition; using Microsoft.Azure.Management.Network.Fluent.HasPrivateIPAddress.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.HasPrivateIPAddress.Update; using Microsoft.Azure.Management.Network.Fluent.HasPublicIPAddress.Definition; using Microsoft.Azure.Management.Network.Fluent.HasPublicIPAddress.UpdateDefinition; using Microsoft.Azure.Management.Network.Fluent.HasPublicIPAddress.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update; using Microsoft.Azure.Management.ResourceManager.Fluent.Core.ResourceActions; using System.Collections.Generic; internal partial class NicIPConfigurationImpl { /// <return>The associated public IP address.</return> Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress Microsoft.Azure.Management.Network.Fluent.IHasPublicIPAddress.GetPublicIPAddress() { return this.GetPublicIPAddress(); } /// <summary> /// Gets the resource ID of the associated public IP address. /// </summary> string Microsoft.Azure.Management.Network.Fluent.IHasPublicIPAddress.PublicIPAddressId { get { return this.PublicIPAddressId(); } } /// <summary> /// Specifies the IP version for the private IP address. /// </summary> /// <param name="ipVersion">An IP version.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithPrivateIP.WithPrivateIPVersion(IPVersion ipVersion) { return this.WithPrivateIPVersion(ipVersion); } /// <summary> /// Specifies the IP version for the private IP address. /// </summary> /// <param name="ipVersion">An IP version.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithPrivateIP<NetworkInterface.Update.IUpdate>.WithPrivateIPVersion(IPVersion ipVersion) { return this.WithPrivateIPVersion(ipVersion); } /// <summary> /// Specifies the IP version for the private IP address. /// </summary> /// <param name="ipVersion">An IP version.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithPrivateIP<NetworkInterface.Definition.IWithCreate>.WithPrivateIPVersion(IPVersion ipVersion) { return this.WithPrivateIPVersion(ipVersion); } /// <summary> /// Create a new virtual network to associate with the network interface IP configuration, /// based on the provided definition. /// </summary> /// <param name="creatable">A creatable definition for a new virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithPrivateIP<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithNetwork<NetworkInterface.Update.IUpdate>.WithNewNetwork(ICreatable<Microsoft.Azure.Management.Network.Fluent.INetwork> creatable) { return this.WithNewNetwork(creatable); } /// <summary> /// Creates a new virtual network to associate with the network interface IP configuration. /// the virtual network will be created in the same resource group and region as of parent /// network interface, it will be created with the specified address space and a default subnet /// covering the entirety of the network IP address space. /// </summary> /// <param name="name">The name of the new virtual network.</param> /// <param name="addressSpace">The address space for rhe virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithPrivateIP<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithNetwork<NetworkInterface.Update.IUpdate>.WithNewNetwork(string name, string addressSpace) { return this.WithNewNetwork(name, addressSpace); } /// <summary> /// Creates a new virtual network to associate with the network interface IP configuration. /// the virtual network will be created in the same resource group and region as of parent network interface, /// it will be created with the specified address space and a default subnet covering the entirety of the /// network IP address space. /// </summary> /// <param name="addressSpace">The address space for the virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithPrivateIP<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithNetwork<NetworkInterface.Update.IUpdate>.WithNewNetwork(string addressSpace) { return this.WithNewNetwork(addressSpace); } /// <summary> /// Associate an existing virtual network with the network interface IP configuration. /// </summary> /// <param name="network">An existing virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithSubnet<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithNetwork<NetworkInterface.Update.IUpdate>.WithExistingNetwork(INetwork network) { return this.WithExistingNetwork(network); } /// <summary> /// Create a new virtual network to associate with the network interface IP configuration, /// based on the provided definition. /// </summary> /// <param name="creatable">A creatable definition for a new virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithPrivateIP<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithNetwork<NetworkInterface.Definition.IWithCreate>.WithNewNetwork(ICreatable<Microsoft.Azure.Management.Network.Fluent.INetwork> creatable) { return this.WithNewNetwork(creatable); } /// <summary> /// Creates a new virtual network to associate with the network interface IP configuration. /// the virtual network will be created in the same resource group and region as of parent /// network interface, it will be created with the specified address space and a default subnet /// covering the entirety of the network IP address space. /// </summary> /// <param name="name">The name of the new virtual network.</param> /// <param name="addressSpace">The address space for rhe virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithPrivateIP<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithNetwork<NetworkInterface.Definition.IWithCreate>.WithNewNetwork(string name, string addressSpace) { return this.WithNewNetwork(name, addressSpace); } /// <summary> /// Creates a new virtual network to associate with the network interface IP configuration. /// the virtual network will be created in the same resource group and region as of parent network interface, /// it will be created with the specified address space and a default subnet covering the entirety of the /// network IP address space. /// </summary> /// <param name="addressSpace">The address space for the virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithPrivateIP<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithNetwork<NetworkInterface.Definition.IWithCreate>.WithNewNetwork(string addressSpace) { return this.WithNewNetwork(addressSpace); } /// <summary> /// Associate an existing virtual network with the network interface IP configuration. /// </summary> /// <param name="network">An existing virtual network.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithSubnet<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithNetwork<NetworkInterface.Definition.IWithCreate>.WithExistingNetwork(INetwork network) { return this.WithExistingNetwork(network); } /// <summary> /// Creates a new public IP address in the same region and group as the resource, with the specified DNS label /// and associates it with the resource. /// The internal name for the public IP address will be derived from the DNS label. /// </summary> /// <param name="leafDnsLabel">The leaf domain label.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Update.IUpdate HasPublicIPAddress.Update.IWithNewPublicIPAddress<NicIPConfiguration.Update.IUpdate>.WithNewPublicIPAddress(string leafDnsLabel) { return this.WithNewPublicIPAddress(leafDnsLabel); } /// <summary> /// Creates a new public IP address in the same region and group as the resource, with the specified DNS label /// and associates it with the resource. /// The internal name for the public IP address will be derived from the DNS label. /// </summary> /// <param name="leafDnsLabel">The leaf domain label.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithNewPublicIPAddress<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithNewPublicIPAddress(string leafDnsLabel) { return this.WithNewPublicIPAddress(leafDnsLabel); } /// <summary> /// Creates a new public IP address in the same region and group as the resource, with the specified DNS label /// and associates it with the resource. /// The internal name for the public IP address will be derived from the DNS label. /// </summary> /// <param name="leafDnsLabel">The leaf domain label.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPublicIPAddress.Definition.IWithNewPublicIPAddress<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithNewPublicIPAddress(string leafDnsLabel) { return this.WithNewPublicIPAddress(leafDnsLabel); } /// <summary> /// Specifies the application gateway backend to associate this IP configuration with. /// </summary> /// <param name="appGateway">An existing application gateway.</param> /// <param name="backendName">The name of an existing backend on the application gateway.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithApplicationGatewayBeta.WithExistingApplicationGatewayBackend(IApplicationGateway appGateway, string backendName) { return this.WithExistingApplicationGatewayBackend(appGateway, backendName); } /// <summary> /// Removes all existing associations with application gateway backends. /// </summary> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithApplicationGatewayBeta.WithoutApplicationGatewayBackends() { return this.WithoutApplicationGatewayBackends(); } /// <summary> /// Attaches the child definition to the parent resource update. /// </summary> /// <return>The next stage of the parent definition.</return> NetworkInterface.Update.IUpdate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Update.IInUpdate<NetworkInterface.Update.IUpdate>.Attach() { return this.Attach(); } /// <summary> /// Attaches the child definition to the parent resource definiton. /// </summary> /// <return>The next stage of the parent definition.</return> NetworkInterface.Definition.IWithCreate Microsoft.Azure.Management.ResourceManager.Fluent.Core.ChildResource.Definition.IInDefinition<NetworkInterface.Definition.IWithCreate>.Attach() { return this.Attach(); } /// <summary> /// Enables dynamic private IP address allocation within the associated subnet. /// </summary> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate HasPrivateIPAddress.Update.IWithPrivateIPAddress<NicIPConfiguration.Update.IUpdate>.WithPrivateIPAddressDynamic() { return this.WithPrivateIPAddressDynamic(); } /// <summary> /// Assigns the specified static private IP address within the associated subnet. /// </summary> /// <param name="ipAddress">A static IP address within the associated private IP range.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate HasPrivateIPAddress.Update.IWithPrivateIPAddress<NicIPConfiguration.Update.IUpdate>.WithPrivateIPAddressStatic(string ipAddress) { return this.WithPrivateIPAddressStatic(ipAddress); } /// <summary> /// Enables dynamic private IP address allocation within the associated subnet. /// </summary> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPrivateIPAddress.UpdateDefinition.IWithPrivateIPAddress<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithPrivateIPAddressDynamic() { return this.WithPrivateIPAddressDynamic(); } /// <summary> /// Assigns the specified static private IP address within the associated subnet. /// </summary> /// <param name="ipAddress">A static IP address within the associated private IP range.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPrivateIPAddress.UpdateDefinition.IWithPrivateIPAddress<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithPrivateIPAddressStatic(string ipAddress) { return this.WithPrivateIPAddressStatic(ipAddress); } /// <summary> /// Enables dynamic private IP address allocation within the associated subnet. /// </summary> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPrivateIPAddress.Definition.IWithPrivateIPAddress<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithPrivateIPAddressDynamic() { return this.WithPrivateIPAddressDynamic(); } /// <summary> /// Assigns the specified static private IP address within the associated subnet. /// </summary> /// <param name="ipAddress">A static IP address within the associated private IP range.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPrivateIPAddress.Definition.IWithPrivateIPAddress<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithPrivateIPAddressStatic(string ipAddress) { return this.WithPrivateIPAddressStatic(ipAddress); } /// <summary> /// Removes all the existing associations with load balancer backends. /// </summary> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithLoadBalancer.WithoutLoadBalancerBackends() { return this.WithoutLoadBalancerBackends(); } /// <summary> /// Removes all the existing associations with load balancer inbound NAT rules. /// </summary> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithLoadBalancer.WithoutLoadBalancerInboundNatRules() { return this.WithoutLoadBalancerInboundNatRules(); } /// <summary> /// Specifies the load balancer inbound NAT rule to associate this IP configuration with. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="inboundNatRuleName">The name of an existing inbound NAT rule on the selected load balancer.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithLoadBalancer.WithExistingLoadBalancerInboundNatRule(ILoadBalancer loadBalancer, string inboundNatRuleName) { return this.WithExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); } /// <summary> /// Specifies the load balancer to associate this IP configuration with. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="backendName">The name of an existing backend on that load balancer.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithLoadBalancer.WithExistingLoadBalancerBackend(ILoadBalancer loadBalancer, string backendName) { return this.WithExistingLoadBalancerBackend(loadBalancer, backendName); } /// <summary> /// Specifies the load balancer inbound NAT rule to associate this IP configuration with. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="inboundNatRuleName">The name of an existing inbound NAT rule on the selected load balancer.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithLoadBalancer<NetworkInterface.Update.IUpdate>.WithExistingLoadBalancerInboundNatRule(ILoadBalancer loadBalancer, string inboundNatRuleName) { return this.WithExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); } /// <summary> /// Specifies the load balancer to associate this IP configuration with. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="backendName">The name of an existing backend on that load balancer.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithLoadBalancer<NetworkInterface.Update.IUpdate>.WithExistingLoadBalancerBackend(ILoadBalancer loadBalancer, string backendName) { return this.WithExistingLoadBalancerBackend(loadBalancer, backendName); } /// <summary> /// Specifies the load balancer inbound NAT rule to associate this IP configuration with. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="inboundNatRuleName">The name of an existing inbound NAT rule on the selected load balancer.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithLoadBalancer<NetworkInterface.Definition.IWithCreate>.WithExistingLoadBalancerInboundNatRule(ILoadBalancer loadBalancer, string inboundNatRuleName) { return this.WithExistingLoadBalancerInboundNatRule(loadBalancer, inboundNatRuleName); } /// <summary> /// Specifies the load balancer backend to associate this IP configuration with. /// </summary> /// <param name="loadBalancer">An existing load balancer.</param> /// <param name="backendName">The name of an existing backend on that load balancer.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithLoadBalancer<NetworkInterface.Definition.IWithCreate>.WithExistingLoadBalancerBackend(ILoadBalancer loadBalancer, string backendName) { return this.WithExistingLoadBalancerBackend(loadBalancer, backendName); } /// <summary> /// Creates a new public IP address to associate with the resource. /// </summary> /// <param name="creatable">A creatable definition for a new public IP.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Update.IUpdate HasPublicIPAddress.Update.IWithNewPublicIPAddressNoDnsLabel<NicIPConfiguration.Update.IUpdate>.WithNewPublicIPAddress(ICreatable<Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress> creatable) { return this.WithNewPublicIPAddress(creatable); } /// <summary> /// Creates a new public IP address in the same region and group as the resource and associates it with the resource. /// The internal name and DNS label for the public IP address will be derived from the resource's name. /// </summary> /// <return>The next stage of the definition.</return> NicIPConfiguration.Update.IUpdate HasPublicIPAddress.Update.IWithNewPublicIPAddressNoDnsLabel<NicIPConfiguration.Update.IUpdate>.WithNewPublicIPAddress() { return this.WithNewPublicIPAddress(); } /// <summary> /// Creates a new public IP address to associate with the resource. /// </summary> /// <param name="creatable">A creatable definition for a new public IP.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithNewPublicIPAddressNoDnsLabel<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithNewPublicIPAddress(ICreatable<Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress> creatable) { return this.WithNewPublicIPAddress(creatable); } /// <summary> /// Creates a new public IP address in the same region and group as the resource and associates it with the resource. /// The internal name and DNS label for the public IP address will be derived from the resource's name. /// </summary> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithNewPublicIPAddressNoDnsLabel<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithNewPublicIPAddress() { return this.WithNewPublicIPAddress(); } /// <summary> /// Creates a new public IP address to associate with the resource. /// </summary> /// <param name="creatable">A creatable definition for a new public IP.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPublicIPAddress.Definition.IWithNewPublicIPAddressNoDnsLabel<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithNewPublicIPAddress(ICreatable<Microsoft.Azure.Management.Network.Fluent.IPublicIPAddress> creatable) { return this.WithNewPublicIPAddress(creatable); } /// <summary> /// Creates a new public IP address in the same region and group as the resource and associates it with the resource. /// The internal name and DNS label for the public IP address will be derived from the resource's name. /// </summary> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPublicIPAddress.Definition.IWithNewPublicIPAddressNoDnsLabel<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithNewPublicIPAddress() { return this.WithNewPublicIPAddress(); } /// <summary> /// Specifies the application gateway backend to associate this IP configuration with. /// </summary> /// <param name="appGateway">An existing application gateway.</param> /// <param name="backendName">The name of an existing backend on the application gateway.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithApplicationGatewayBeta<NetworkInterface.Update.IUpdate>.WithExistingApplicationGatewayBackend(IApplicationGateway appGateway, string backendName) { return this.WithExistingApplicationGatewayBackend(appGateway, backendName); } /// <summary> /// Specifies the application gateway backend to associate this IP configuration with. /// </summary> /// <param name="appGateway">An existing application gateway.</param> /// <param name="backendName">The name of an existing backend on the application gateway.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithApplicationGatewayBeta<NetworkInterface.Definition.IWithCreate>.WithExistingApplicationGatewayBackend(IApplicationGateway appGateway, string backendName) { return this.WithExistingApplicationGatewayBackend(appGateway, backendName); } /// <summary> /// Removes the existing reference to a public IP address. /// </summary> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate HasPublicIPAddress.Update.IWithExistingPublicIPAddress<NicIPConfiguration.Update.IUpdate>.WithoutPublicIPAddress() { return this.WithoutPublicIPAddress(); } /// <summary> /// Associates an existing public IP address with the resource. /// </summary> /// <param name="publicIPAddress">An existing public IP address.</param> /// <return>The next stage of the update.</return> NicIPConfiguration.Update.IUpdate HasPublicIPAddress.Update.IWithExistingPublicIPAddress<NicIPConfiguration.Update.IUpdate>.WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress) { return this.WithExistingPublicIPAddress(publicIPAddress); } /// <summary> /// Associates an existing public IP address with the resource. /// </summary> /// <param name="resourceId">The resource ID of an existing public IP address.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Update.IUpdate HasPublicIPAddress.Update.IWithExistingPublicIPAddress<NicIPConfiguration.Update.IUpdate>.WithExistingPublicIPAddress(string resourceId) { return this.WithExistingPublicIPAddress(resourceId); } /// <summary> /// Associates an existing public IP address with the resource. /// </summary> /// <param name="publicIPAddress">An existing public IP address.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithExistingPublicIPAddress<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress) { return this.WithExistingPublicIPAddress(publicIPAddress); } /// <summary> /// Associates an existing public IP address with the resource. /// </summary> /// <param name="resourceId">The resource ID of an existing public IP address.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate> HasPublicIPAddress.UpdateDefinition.IWithExistingPublicIPAddress<NicIPConfiguration.UpdateDefinition.IWithAttach<NetworkInterface.Update.IUpdate>>.WithExistingPublicIPAddress(string resourceId) { return this.WithExistingPublicIPAddress(resourceId); } /// <summary> /// Associates an existing public IP address with the resource. /// </summary> /// <param name="publicIPAddress">An existing public IP address.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPublicIPAddress.Definition.IWithExistingPublicIPAddress<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithExistingPublicIPAddress(IPublicIPAddress publicIPAddress) { return this.WithExistingPublicIPAddress(publicIPAddress); } /// <summary> /// Associates an existing public IP address with the resource. /// </summary> /// <param name="resourceId">The resource ID of an existing public IP address.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate> HasPublicIPAddress.Definition.IWithExistingPublicIPAddress<NicIPConfiguration.Definition.IWithAttach<NetworkInterface.Definition.IWithCreate>>.WithExistingPublicIPAddress(string resourceId) { return this.WithExistingPublicIPAddress(resourceId); } /// <summary> /// Associate a subnet with the network interface IP configuration. /// </summary> /// <param name="name">The subnet name.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.UpdateDefinition.IWithPrivateIP<NetworkInterface.Update.IUpdate> NicIPConfiguration.UpdateDefinition.IWithSubnet<NetworkInterface.Update.IUpdate>.WithSubnet(string name) { return this.WithSubnet(name); } /// <summary> /// Associate a subnet with the network interface IP configuration. /// </summary> /// <param name="name">The subnet name.</param> /// <return>The next stage of the definition.</return> NicIPConfiguration.Definition.IWithPrivateIP<NetworkInterface.Definition.IWithCreate> NicIPConfiguration.Definition.IWithSubnet<NetworkInterface.Definition.IWithCreate>.WithSubnet(string name) { return this.WithSubnet(name); } /// <summary> /// Associate a subnet with the network interface IP configuration. /// </summary> /// <param name="name">The subnet name.</param> /// <return>The next stage of the network interface IP configuration update.</return> NicIPConfiguration.Update.IUpdate NicIPConfiguration.Update.IWithSubnet.WithSubnet(string name) { return this.WithSubnet(name); } } }
// // ScrollViewBackend.cs // // Author: // Lluis Sanchez Gual <lluis@xamarin.com> // // Copyright (c) 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using Xwt.Backends; #if MONOMAC using nint = System.Int32; using nfloat = System.Single; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using CGSize = System.Drawing.SizeF; using MonoMac.AppKit; using MonoMac.CoreGraphics; #else using AppKit; using CoreGraphics; #endif namespace Xwt.Mac { public class ScrollViewBackend: ViewBackend<NSScrollView,IScrollViewEventSink>, IScrollViewBackend { IWidgetBackend child; ScrollPolicy verticalScrollPolicy; ScrollPolicy horizontalScrollPolicy; NormalClipView clipView; public override void Initialize () { ViewObject = new CustomScrollView (); Widget.HasHorizontalScroller = true; Widget.HasVerticalScroller = true; Widget.AutoresizesSubviews = true; } protected override Size GetNaturalSize () { return EventSink.GetDefaultNaturalSize (); } public void SetChild (IWidgetBackend child) { this.child = child; ViewBackend backend = (ViewBackend) child; if (backend.EventSink.SupportsCustomScrolling ()) { var vs = new ScrollAdjustmentBackend (Widget, true); var hs = new ScrollAdjustmentBackend (Widget, false); CustomClipView clipView = new CustomClipView (hs, vs); Widget.ContentView = clipView; var dummy = new DummyClipView (); dummy.AddSubview (backend.Widget); backend.Widget.Frame = new CGRect (0, 0, clipView.Frame.Width, clipView.Frame.Height); clipView.DocumentView = dummy; backend.EventSink.SetScrollAdjustments (hs, vs); vertScroll = vs; horScroll = hs; } else { clipView = new NormalClipView (); clipView.Scrolled += OnScrolled; Widget.ContentView = clipView; Widget.DocumentView = backend.Widget; UpdateChildSize (); } } public ScrollPolicy VerticalScrollPolicy { get { return verticalScrollPolicy; } set { verticalScrollPolicy = value; Widget.HasVerticalScroller = verticalScrollPolicy != ScrollPolicy.Never; } } public ScrollPolicy HorizontalScrollPolicy { get { return horizontalScrollPolicy; } set { horizontalScrollPolicy = value; Widget.HasHorizontalScroller = horizontalScrollPolicy != ScrollPolicy.Never; } } IScrollControlBackend vertScroll; public IScrollControlBackend CreateVerticalScrollControl () { if (vertScroll == null) vertScroll = new ScrollControlBackend (ApplicationContext, Widget, true); return vertScroll; } IScrollControlBackend horScroll; public IScrollControlBackend CreateHorizontalScrollControl () { if (horScroll == null) horScroll = new ScrollControlBackend (ApplicationContext, Widget, false); return horScroll; } void OnScrolled (object o, EventArgs e) { if (vertScroll is ScrollControlBackend) ((ScrollControlBackend)vertScroll).NotifyValueChanged (); if (horScroll is ScrollControlBackend) ((ScrollControlBackend)horScroll).NotifyValueChanged (); } public Rectangle VisibleRect { get { return Rectangle.Zero; } } public bool BorderVisible { get { return false; } set { } } void UpdateChildSize () { if (child == null) return; if (Widget.ContentView is CustomClipView) { } else { NSView view = (NSView)Widget.DocumentView; ViewBackend c = (ViewBackend)child; Size s; if (horizontalScrollPolicy == ScrollPolicy.Never) { s = c.Frontend.Surface.GetPreferredSize (SizeConstraint.WithSize (Widget.ContentView.Frame.Width), SizeConstraint.Unconstrained); } else if (verticalScrollPolicy == ScrollPolicy.Never) { s = c.Frontend.Surface.GetPreferredSize (SizeConstraint.Unconstrained, SizeConstraint.WithSize (Widget.ContentView.Frame.Width)); } else { s = c.Frontend.Surface.GetPreferredSize (); } var w = Math.Max (s.Width, Widget.ContentView.Frame.Width); var h = Math.Max (s.Height, Widget.ContentView.Frame.Height); view.Frame = new CGRect (view.Frame.X, view.Frame.Y, (nfloat)w, (nfloat)h); } } public void SetChildSize (Size s) { UpdateChildSize (); } } class CustomScrollView: NSScrollView, IViewObject { public NSView View { get { return this; } } public ViewBackend Backend { get; set; } public override bool IsFlipped { get { return true; } } } class DummyClipView: NSView { public override bool IsFlipped { get { return true; } } } class CustomClipView: NSClipView { ScrollAdjustmentBackend hScroll; ScrollAdjustmentBackend vScroll; double currentX; double currentY; float ratioX = 1, ratioY = 1; public CustomClipView (ScrollAdjustmentBackend hScroll, ScrollAdjustmentBackend vScroll) { this.hScroll = hScroll; this.vScroll = vScroll; CopiesOnScroll = false; } public double CurrentX { get { return hScroll.LowerValue + (currentX / ratioX); } set { ScrollToPoint (new CGPoint ((nfloat)(value - hScroll.LowerValue) * ratioX, (nfloat)currentY)); } } public double CurrentY { get { return vScroll.LowerValue + (currentY / ratioY); } set { ScrollToPoint (new CGPoint ((nfloat)currentX, (nfloat)(value - vScroll.LowerValue) * ratioY)); } } public override bool IsFlipped { get { return true; } } public override void SetFrameSize (CGSize newSize) { base.SetFrameSize (newSize); var v = DocumentView.Subviews [0]; v.Frame = new CGRect (v.Frame.X, v.Frame.Y, newSize.Width, newSize.Height); } public override void ScrollToPoint (CGPoint newOrigin) { base.ScrollToPoint (newOrigin); var v = DocumentView.Subviews [0]; currentX = newOrigin.X >= 0 ? newOrigin.X : 0; currentY = newOrigin.Y >= 0 ? newOrigin.Y : 0; if (currentX + v.Frame.Width > DocumentView.Frame.Width) currentX = DocumentView.Frame.Width - v.Frame.Width; if (currentY + v.Frame.Height > DocumentView.Frame.Height) currentY = DocumentView.Frame.Height - v.Frame.Height; v.Frame = new CGRect ((nfloat)currentX, (nfloat)currentY, v.Frame.Width, v.Frame.Height); hScroll.NotifyValueChanged (); vScroll.NotifyValueChanged (); } public void UpdateDocumentSize () { var vr = DocumentVisibleRect (); ratioX = hScroll.PageSize != 0 ? (float)vr.Width / (float)hScroll.PageSize : 1; ratioY = vScroll.PageSize != 0 ? (float)vr.Height / (float)vScroll.PageSize : 1; DocumentView.Frame = new CGRect (0, 0, (nfloat)(hScroll.UpperValue - hScroll.LowerValue) * ratioX, (nfloat)(vScroll.UpperValue - vScroll.LowerValue) * ratioY); } } class NormalClipView: NSClipView { public event EventHandler Scrolled; public override void ScrollToPoint (CGPoint newOrigin) { base.ScrollToPoint (newOrigin); if (Scrolled != null) Scrolled (this, EventArgs.Empty); } } }
// *********************************************************************** // Copyright (c) 2008-2015 Charlie Poole, Rob Prouse // // 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.Collections.Generic; using System.Globalization; using System.Linq; using System.Reflection; using NUnit.Compatibility; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework { /// <summary> /// RandomAttribute is used to supply a set of random values /// to a single parameter of a parameterized test. /// </summary> [AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)] public class RandomAttribute : DataAttribute, IParameterDataSource { private RandomDataSource _source; private int _count; /// <summary> /// If true, no value will be repeated. /// </summary> public bool Distinct { get; set; } #region Constructors /// <summary> /// Construct a random set of values appropriate for the Type of the /// parameter on which the attribute appears, specifying only the count. /// </summary> /// <param name="count"></param> public RandomAttribute(int count) { _count = count; } /// <summary> /// Construct a set of ints within a specified range /// </summary> public RandomAttribute(int min, int max, int count) { _source = new IntDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned ints within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(uint min, uint max, int count) { _source = new UIntDataSource(min, max, count); } /// <summary> /// Construct a set of longs within a specified range /// </summary> public RandomAttribute(long min, long max, int count) { _source = new LongDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned longs within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(ulong min, ulong max, int count) { _source = new ULongDataSource(min, max, count); } /// <summary> /// Construct a set of shorts within a specified range /// </summary> public RandomAttribute(short min, short max, int count) { _source = new ShortDataSource(min, max, count); } /// <summary> /// Construct a set of unsigned shorts within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(ushort min, ushort max, int count) { _source = new UShortDataSource(min, max, count); } /// <summary> /// Construct a set of doubles within a specified range /// </summary> public RandomAttribute(double min, double max, int count) { _source = new DoubleDataSource(min, max, count); } /// <summary> /// Construct a set of floats within a specified range /// </summary> public RandomAttribute(float min, float max, int count) { _source = new FloatDataSource(min, max, count); } /// <summary> /// Construct a set of bytes within a specified range /// </summary> public RandomAttribute(byte min, byte max, int count) { _source = new ByteDataSource(min, max, count); } /// <summary> /// Construct a set of sbytes within a specified range /// </summary> [CLSCompliant(false)] public RandomAttribute(sbyte min, sbyte max, int count) { _source = new SByteDataSource(min, max, count); } #endregion #region IParameterDataSource Interface /// <summary> /// Get the collection of values to be used as arguments. /// </summary> public IEnumerable GetData(IParameterInfo parameter) { // Since a separate Randomizer is used for each parameter, // we can't fill in the data in the constructor of the // attribute. Only now, when GetData is called, do we have // sufficient information to create the values in a // repeatable manner. Type parmType = parameter.ParameterType; if (_source == null) { if (parmType == typeof(int)) _source = new IntDataSource(_count); else if (parmType == typeof(uint)) _source = new UIntDataSource(_count); else if (parmType == typeof(long)) _source = new LongDataSource(_count); else if (parmType == typeof(ulong)) _source = new ULongDataSource(_count); else if (parmType == typeof(short)) _source = new ShortDataSource(_count); else if (parmType == typeof(ushort)) _source = new UShortDataSource(_count); else if (parmType == typeof(double)) _source = new DoubleDataSource(_count); else if (parmType == typeof(float)) _source = new FloatDataSource(_count); else if (parmType == typeof(byte)) _source = new ByteDataSource(_count); else if (parmType == typeof(sbyte)) _source = new SByteDataSource(_count); else if (parmType == typeof(decimal)) _source = new DecimalDataSource(_count); else if (parmType.GetTypeInfo().IsEnum) _source = new EnumDataSource(_count); else // Default _source = new IntDataSource(_count); } else if (_source.DataType != parmType && WeConvert(_source.DataType, parmType)) { _source.Distinct = Distinct; _source = new RandomDataConverter(_source); } _source.Distinct = Distinct; return _source.GetData(parameter); //// Copy the random values into the data array //// and call the base class which may need to //// convert them to another type. //this.data = new object[values.Count]; //for (int i = 0; i < values.Count; i++) // this.data[i] = values[i]; //return base.GetData(parameter); } private bool WeConvert(Type sourceType, Type targetType) { if (targetType == typeof(short) || targetType == typeof(ushort) || targetType == typeof(byte) || targetType == typeof(sbyte)) return sourceType == typeof(int); if (targetType == typeof(decimal)) return sourceType == typeof(int) || sourceType == typeof(double); return false; } #endregion #region Nested DataSource Classes #region RandomDataSource abstract class RandomDataSource : IParameterDataSource { public Type DataType { get; protected set; } public bool Distinct { get; set; } public abstract IEnumerable GetData(IParameterInfo parameter); } abstract class RandomDataSource<T> : RandomDataSource { private T _min; private T _max; private int _count; private bool _inRange; private List<T> previousValues = new List<T>(); protected Randomizer _randomizer; protected RandomDataSource(int count) { _count = count; _inRange = false; DataType = typeof(T); } protected RandomDataSource(T min, T max, int count) { _min = min; _max = max; _count = count; _inRange = true; DataType = typeof(T); } public override IEnumerable GetData(IParameterInfo parameter) { //Guard.ArgumentValid(parameter.ParameterType == typeof(T), "Parameter type must be " + typeof(T).Name, "parameter"); _randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); Guard.OperationValid(!(Distinct && _inRange && !CanBeDistinct(_min, _max, _count)), $"The range of values is [{_min}, {_max}[ and the random value count is {_count} so the values cannot be distinct."); for (int i = 0; i < _count; i++) { if (Distinct) { T next; do { next = _inRange ? GetNext(_min, _max) : GetNext(); } while (previousValues.Contains(next)); previousValues.Add(next); yield return next; } else yield return _inRange ? GetNext(_min, _max) : GetNext(); } } protected abstract T GetNext(); protected abstract T GetNext(T min, T max); protected abstract bool CanBeDistinct(T min, T max, int count); } #endregion #region RandomDataConverter class RandomDataConverter : RandomDataSource { IParameterDataSource _source; public RandomDataConverter(IParameterDataSource source) { _source = source; } public override IEnumerable GetData(IParameterInfo parameter) { Type parmType = parameter.ParameterType; foreach (object obj in _source.GetData(parameter)) { if (obj is int) { int ival = (int)obj; // unbox first if (parmType == typeof(short)) yield return (short)ival; else if (parmType == typeof(ushort)) yield return (ushort)ival; else if (parmType == typeof(byte)) yield return (byte)ival; else if (parmType == typeof(sbyte)) yield return (sbyte)ival; else if (parmType == typeof(decimal)) yield return (decimal)ival; } else if (obj is double) { double d = (double)obj; // unbox first if (parmType == typeof(decimal)) yield return (decimal)d; } } } } #endregion #region IntDataSource class IntDataSource : RandomDataSource<int> { public IntDataSource(int count) : base(count) { } public IntDataSource(int min, int max, int count) : base(min, max, count) { } protected override int GetNext() { return _randomizer.Next(); } protected override int GetNext(int min, int max) { return _randomizer.Next(min, max); } protected override bool CanBeDistinct(int min, int max, int count) { return count <= max - min; } } #endregion #region UIntDataSource class UIntDataSource : RandomDataSource<uint> { public UIntDataSource(int count) : base(count) { } public UIntDataSource(uint min, uint max, int count) : base(min, max, count) { } protected override uint GetNext() { return _randomizer.NextUInt(); } protected override uint GetNext(uint min, uint max) { return _randomizer.NextUInt(min, max); } protected override bool CanBeDistinct(uint min, uint max, int count) { return count <= max - min; } } #endregion #region LongDataSource class LongDataSource : RandomDataSource<long> { public LongDataSource(int count) : base(count) { } public LongDataSource(long min, long max, int count) : base(min, max, count) { } protected override long GetNext() { return _randomizer.NextLong(); } protected override long GetNext(long min, long max) { return _randomizer.NextLong(min, max); } protected override bool CanBeDistinct(long min, long max, int count) { return count <= max - min; } } #endregion #region ULongDataSource class ULongDataSource : RandomDataSource<ulong> { public ULongDataSource(int count) : base(count) { } public ULongDataSource(ulong min, ulong max, int count) : base(min, max, count) { } protected override ulong GetNext() { return _randomizer.NextULong(); } protected override ulong GetNext(ulong min, ulong max) { return _randomizer.NextULong(min, max); } protected override bool CanBeDistinct(ulong min, ulong max, int count) { return (uint)count <= max - min; } } #endregion #region ShortDataSource class ShortDataSource : RandomDataSource<short> { public ShortDataSource(int count) : base(count) { } public ShortDataSource(short min, short max, int count) : base(min, max, count) { } protected override short GetNext() { return _randomizer.NextShort(); } protected override short GetNext(short min, short max) { return _randomizer.NextShort(min, max); } protected override bool CanBeDistinct(short min, short max, int count) { return count <= max - min; } } #endregion #region UShortDataSource class UShortDataSource : RandomDataSource<ushort> { public UShortDataSource(int count) : base(count) { } public UShortDataSource(ushort min, ushort max, int count) : base(min, max, count) { } protected override ushort GetNext() { return _randomizer.NextUShort(); } protected override ushort GetNext(ushort min, ushort max) { return _randomizer.NextUShort(min, max); } protected override bool CanBeDistinct(ushort min, ushort max, int count) { return count <= max - min; } } #endregion #region DoubleDataSource class DoubleDataSource : RandomDataSource<double> { public DoubleDataSource(int count) : base(count) { } public DoubleDataSource(double min, double max, int count) : base(min, max, count) { } protected override double GetNext() { return _randomizer.NextDouble(); } protected override double GetNext(double min, double max) { return _randomizer.NextDouble(min, max); } protected override bool CanBeDistinct(double min, double max, int count) { return true; } } #endregion #region FloatDataSource class FloatDataSource : RandomDataSource<float> { public FloatDataSource(int count) : base(count) { } public FloatDataSource(float min, float max, int count) : base(min, max, count) { } protected override float GetNext() { return _randomizer.NextFloat(); } protected override float GetNext(float min, float max) { return _randomizer.NextFloat(min, max); } protected override bool CanBeDistinct(float min, float max, int count) { return true; } } #endregion #region ByteDataSource class ByteDataSource : RandomDataSource<byte> { public ByteDataSource(int count) : base(count) { } public ByteDataSource(byte min, byte max, int count) : base(min, max, count) { } protected override byte GetNext() { return _randomizer.NextByte(); } protected override byte GetNext(byte min, byte max) { return _randomizer.NextByte(min, max); } protected override bool CanBeDistinct(byte min, byte max, int count) { return count <= max - min; } } #endregion #region SByteDataSource class SByteDataSource : RandomDataSource<sbyte> { public SByteDataSource(int count) : base(count) { } public SByteDataSource(sbyte min, sbyte max, int count) : base(min, max, count) { } protected override sbyte GetNext() { return _randomizer.NextSByte(); } protected override sbyte GetNext(sbyte min, sbyte max) { return _randomizer.NextSByte(min, max); } protected override bool CanBeDistinct(sbyte min, sbyte max, int count) { return count <= max - min; } } #endregion #region EnumDataSource class EnumDataSource : RandomDataSource { private int _count; private List<object> previousValues = new List<object>(); public EnumDataSource(int count) { _count = count; DataType = typeof(Enum); } public override IEnumerable GetData(IParameterInfo parameter) { Guard.ArgumentValid(parameter.ParameterType.GetTypeInfo().IsEnum, "EnumDataSource requires an enum parameter", "parameter"); Randomizer randomizer = Randomizer.GetRandomizer(parameter.ParameterInfo); DataType = parameter.ParameterType; int valueCount = Enum.GetValues(DataType).Cast<int>().Distinct().Count(); Guard.OperationValid(!(Distinct && _count > valueCount), $"The enum \"{DataType.Name}\" has {valueCount} values and the random value count is {_count} so the values cannot be distinct."); for (int i = 0; i < _count; i++) { if (Distinct) { object next; do { next = randomizer.NextEnum(parameter.ParameterType); } while (previousValues.Contains(next)); previousValues.Add(next); yield return next; } else yield return randomizer.NextEnum(parameter.ParameterType); } } } #endregion #region DecimalDataSource // Currently, Randomizer doesn't implement methods for decimal // so we use random Ulongs and convert them. This doesn't cover // the full range of decimal, so it's temporary. class DecimalDataSource : RandomDataSource<decimal> { public DecimalDataSource(int count) : base(count) { } public DecimalDataSource(decimal min, decimal max, int count) : base(min, max, count) { } protected override decimal GetNext() { return _randomizer.NextDecimal(); } protected override decimal GetNext(decimal min, decimal max) { return _randomizer.NextDecimal(min, max); } protected override bool CanBeDistinct(decimal min, decimal max, int count) { return true; } } #endregion #endregion } }
/*************************************************************************************************************************************** * Copyright (C) 2001-2012 LearnLift USA * * Contact: Learnlift USA, 12 Greenway Plaza, Suite 1510, Houston, Texas 77046, support@memorylifter.com * * * * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * * as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public License along with this library; if not, * * write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * ***************************************************************************************************************************************/ using System; using System.Drawing; using System.Windows.Forms; using MLifter.DAL; using MLifter.DAL.Interfaces; namespace MLifter.BusinessLayer { /// <summary> /// This class hold all needed information about a learning module. /// </summary> /// <remarks>Documented by Dev05, 2009-02-18</remarks> [Serializable()] public class LearningModulesIndexEntry : IIndexEntry { [NonSerialized()] private IUser user; /// <summary> /// Gets or sets the user. /// </summary> /// <value>The user.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public IUser User { get { return user; } set { user = value; if (user != null) { UserId = user.Id; UserName = user.UserName; } else { UserId = -1; UserName = string.Empty; } } } /// <summary> /// Gets or sets the user id. /// </summary> /// <value>The user id.</value> /// <remarks>Documented by Dev05, 2009-04-29</remarks> public int UserId { get; set; } /// <summary> /// Gets or sets the name of the user. /// </summary> /// <value>The name of the user.</value> /// <remarks>Documented by Dev05, 2009-04-28</remarks> public string UserName { get; set; } [NonSerialized()] private IDictionary dictionary; /// <summary> /// Gets or sets the dictionary. /// </summary> /// <value>The dictionary.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public IDictionary Dictionary { get { return dictionary; } set { dictionary = value; } } private LearningModuleType type; /// <summary> /// Gets or sets the type. /// </summary> /// <value>The type.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public LearningModuleType Type { get { return type; } set { type = value; } } [NonSerialized()] private ListViewGroup group; /// <summary> /// Gets or sets the group. /// </summary> /// <value>The group.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public ListViewGroup Group { get { return group; } set { group = value; } } private ConnectionStringStruct connectionString; /// <summary> /// Gets or sets the connection string. /// </summary> /// <value>The connection string.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public ConnectionStringStruct ConnectionString { get { return connectionString; } set { connectionString = value; } } private string description = string.Empty; /// <summary> /// Gets or sets the Description. /// </summary> /// <value>The Description.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public string Description { get { return description; } set { description = value; } } private Category category; /// <summary> /// Gets or sets the category. /// </summary> /// <value>The category.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public Category Category { get { return category; } set { category = value; } } private string author = string.Empty; /// <summary> /// Gets or sets the author. /// </summary> /// <value>The author.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public string Author { get { return author; } set { author = value; } } /// <summary> /// Gets or sets the size. /// </summary> /// <value>The size.</value> /// <remarks>Documented by Dev05, 2009-03-26</remarks> public long Size { get; set; } private DateTime lastTimeLearned; /// <summary> /// Gets or sets the last time learned. /// </summary> /// <value>The last time learned.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public DateTime LastTimeLearned { get { return lastTimeLearned; } set { lastTimeLearned = value; } } private LearningModuleStatistics statistics = null; /// <summary> /// Gets or sets the statistics. /// </summary> /// <value>The statistics.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public LearningModuleStatistics Statistics { get { return statistics; } set { statistics = value; } } private LearningModulePreview preview = null; /// <summary> /// Gets or sets the preview. /// </summary> /// <value>The preview.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public LearningModulePreview Preview { get { return preview; } set { preview = value; } } /// <summary> /// Gets or sets the synced path. /// </summary> /// <value>The synced path.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public string SyncedPath { get; set; } /// <summary> /// Gets or sets the name of the connection. /// </summary> /// <value>The name of the connection.</value> /// <remarks>Documented by Dev05, 2009-03-02</remarks> public string ConnectionName { get; set; } /// <summary> /// Gets or sets a value indicating whether this learning module is accessible. /// </summary> /// <value> /// <c>true</c> if this learning module is accessible; otherwise, <c>false</c>. /// </value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public bool IsAccessible { get; set; } /// <summary> /// Gets or sets the not accessible reason. /// </summary> /// <value>The not accessible reason.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public LearningModuleNotAccessibleReason NotAccessibleReason { get; set; } /// <summary> /// Initializes a new instance of the <see cref="LearningModulesIndexEntry"/> class. /// </summary> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public LearningModulesIndexEntry() { DisplayName = string.Empty; IsAccessible = true; IsVerified = false; IsFromCache = false; Description = string.Empty; Count = -1; Author = string.Empty; Statistics = null; Preview = null; IsAccessible = true; NotAccessibleReason = LearningModuleNotAccessibleReason.IsAccessible; } /// <summary> /// Initializes a new instance of the <see cref="LearningModulesIndexEntry"/> class. /// </summary> /// <param name="connectionStringStruct">The connection string struct.</param> /// <remarks>Documented by Dev05, 2009-03-02</remarks> public LearningModulesIndexEntry(ConnectionStringStruct connectionStringStruct) : this() { ConnectionString = connectionStringStruct; } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public override string ToString() { return DisplayName + " (" + Author + ") - Cards: " + Count.ToString() + " - Protected: " + ConnectionString.ProtectedLm.ToString(); } /// <summary> /// Determines whether this entry contains the specified filter words. /// </summary> /// <param name="filterWords">The filter words.</param> /// <returns> /// <c>true</c> if contains the specified filter words; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev05, 2008-12-10</remarks> public bool Contains(string[] filterWords) { foreach (string word in filterWords) if (!Contains(word)) return false; return true; } /// <summary> /// Determines whether this entry contains the specified filter word. /// </summary> /// <param name="filterWord">The filter word.</param> /// <returns> /// <c>true</c> if contains the specified filter word; otherwise, <c>false</c>. /// </returns> /// <remarks>Documented by Dev05, 2008-12-10</remarks> public bool Contains(string filterWord) { return DisplayName.ToLower().Contains(filterWord) || IsVerified && IsAccessible && (Author.ToLower().Contains(filterWord) || Category.ToString().ToLower().Contains(filterWord) || Description.ToLower().Contains(filterWord) || Group.Header.ToLower().Contains(filterWord) || LastTimeLearned.ToLongTimeString().ToLower().Contains(filterWord)); } /// <summary> /// Occurs when IsVerified changed. /// </summary> /// <remarks>Documented by Dev05, 2009-03-07</remarks> [field: NonSerialized] public event EventHandler IsVerifiedChanged; /// <summary> /// Raises the <see cref="E:IsVerifiedChanged"/> event. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> /// <remarks>Documented by Dev05, 2009-03-07</remarks> protected virtual void OnIsVerifiedChanged(EventArgs e) { if (IsVerifiedChanged != null) IsVerifiedChanged(this, e); } #region IIndexEntry Members private string displayName = string.Empty; /// <summary> /// Gets or sets the display name. /// </summary> /// <value>The display name.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public string DisplayName { get { return displayName; } set { displayName = value; } } private bool isVerified = false; /// <summary> /// Gets or sets a value indicating whether this instance is verified. /// </summary> /// <value> /// <c>true</c> if this instance is verified; otherwise, <c>false</c>. /// </value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public bool IsVerified { get { return isVerified; } set { isVerified = value; OnIsVerifiedChanged(EventArgs.Empty); } } private bool isFromCache = false; /// <summary> /// Gets or sets a value indicating whether this instance is from cache. /// </summary> /// <value> /// <c>true</c> if this instance is from cache; otherwise, <c>false</c>. /// </value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public bool IsFromCache { get { return isFromCache; } set { isFromCache = value; } } private int count = -1; /// <summary> /// Gets or sets the card count. /// </summary> /// <value>The card count.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public int Count { get { return count; } set { count = value; } } private Image logo; /// <summary> /// Gets or sets the logo. /// </summary> /// <value>The logo.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public Image Logo { get { return logo; } set { logo = value; } } private IConnectionString connection; /// <summary> /// Gets or sets the connection. /// </summary> /// <value>The connection.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public IConnectionString Connection { get { return connection; } set { connection = value; ConnectionName = value.Name; } } #endregion } /// <summary> /// The last statistics of a learning module. /// </summary> /// <remarks>Documented by Dev05, 2009-02-18</remarks> [Serializable()] public class LearningModuleStatistics { /// <summary> /// Gets or sets the last session time. /// </summary> /// <value>The last session time.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public TimeSpan LastSessionTime { get; set; } /// <summary> /// Gets or sets the last start time. /// </summary> /// <value>The last start time.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public DateTime LastStartTime { get; set; } /// <summary> /// Gets or sets the last end time. /// </summary> /// <value>The last end time.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public DateTime LastEndTime { get; set; } /// <summary> /// Gets or sets the cards asked count. /// </summary> /// <value>The cards asked.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public int CardsAsked { get; set; } /// <summary> /// Gets or sets the right card count. /// </summary> /// <value>The right.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public int Right { get; set; } /// <summary> /// Gets or sets the wrong card count. /// </summary> /// <value>The wrong.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public int Wrong { get; set; } /// <summary> /// Gets the ratio. /// </summary> /// <value>The ratio.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public double Ratio { get { return Right * 100.0 / CardsAsked; } } /// <summary> /// Gets the time per card. /// </summary> /// <value>The time per card.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public TimeSpan TimePerCard { get { try { return new TimeSpan(LastSessionTime.Ticks / CardsAsked); } catch (DivideByZeroException) { return new TimeSpan(); } } } /// <summary> /// Gets the cards per minute. /// </summary> /// <value>The cards per minute.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public double CardsPerMinute { get { try { return 60 / TimePerCard.TotalSeconds; } catch (DivideByZeroException) { return 0; } } } } /// <summary> /// The preview-data of a learning module. /// </summary> /// <remarks>Documented by Dev05, 2009-02-18</remarks> [Serializable()] public class LearningModulePreview { /// <summary> /// Gets or sets the Description. /// </summary> /// <value>The Description.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public string Description { get; set; } /// <summary> /// Gets or sets the preview image. /// </summary> /// <value>The preview image.</value> /// <remarks>Documented by Dev05, 2009-02-18</remarks> public Image PreviewImage { get; set; } } }
/* Copyright (c) 2006 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser joseph.feser@gmail.com * Removed warnings * */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Net; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.UnitTests; using Google.GData.Extensions; using Google.GData.Contacts; using System.Collections.Generic; using Google.Contacts; namespace Google.GData.Client.LiveTests { [TestFixture] [Category("LiveTest")] public class ContactsTestSuite : BaseLiveTestClass { ////////////////////////////////////////////////////////////////////// /// <summary>default empty constructor</summary> ////////////////////////////////////////////////////////////////////// public ContactsTestSuite() { } public override string ServiceName { get { return ContactsService.GContactService; } } ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ContactsObjectModelTest() { Tracing.TraceMsg("Entering ContactsObjectModelTest"); EMail email = new EMail("joe@doe.com"); Assert.AreEqual(email.Address, "joe@doe.com", "constructor should have set address field"); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ContactsAuthenticationTest() { Tracing.TraceMsg("Entering ContactsAuthenticationTest"); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName)); ContactsService service = new ContactsService("unittests"); if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } ContactsFeed feed = service.Query(query); ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("ContactsAuthTest")); if (feed != null && feed.Entries.Count > 0) { Tracing.TraceMsg("Found a Feed " + feed.ToString()); foreach (ContactEntry entry in feed.Entries) { Assert.IsTrue(entry.Etag != null, "contact entries should have etags"); } } } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /// <summary>runs an basic auth test against the groups feed test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void GroupsAuthenticationTest() { Tracing.TraceMsg("Entering GroupsAuthenticationTest"); GroupsQuery query = new GroupsQuery(ContactsQuery.CreateGroupsUri(this.userName)); ContactsService service = new ContactsService("unittests"); if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } GroupsFeed feed = service.Query(query); ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("GroupsAuthTest")); GroupEntry newGroup = new GroupEntry(); newGroup.Title.Text = "Private Data"; GroupEntry insertedGroup = feed.Insert(newGroup); GroupEntry g2 = new GroupEntry(); g2.Title.Text = "Another Private Group"; GroupEntry insertedGroup2 = feed.Insert(g2); // now insert a new contact that belongs to that group ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName)); ContactsFeed cf = service.Query(q); ContactEntry entry = ObjectModelHelper.CreateContactEntry(1); GroupMembership member = new GroupMembership(); member.HRef = insertedGroup.Id.Uri.ToString(); GroupMembership member2 = new GroupMembership(); member2.HRef = insertedGroup2.Id.Uri.ToString(); ContactEntry insertedEntry = cf.Insert(entry); // now change the group membership insertedEntry.GroupMembership.Add(member); insertedEntry.GroupMembership.Add(member2); ContactEntry currentEntry = insertedEntry.Update(); Assert.IsTrue(currentEntry.GroupMembership.Count == 2, "The entry should be in 2 groups"); currentEntry.GroupMembership.Clear(); currentEntry = currentEntry.Update(); // now we should have 2 new groups and one new entry with no groups anymore int oldCountGroups = feed.Entries.Count; int oldCountContacts = cf.Entries.Count; currentEntry.Delete(); insertedGroup.Delete(); insertedGroup2.Delete(); feed = service.Query(query); cf = service.Query(q); Assert.AreEqual(oldCountContacts, cf.Entries.Count, "Contacts count should be the same"); Assert.AreEqual(oldCountGroups, feed.Entries.Count, "Groups count should be the same"); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /// <summary>runs an basic auth test against the groups feed test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void GroupsSystemTest() { Tracing.TraceMsg("Entering GroupsSystemTest"); GroupsQuery query = new GroupsQuery(ContactsQuery.CreateGroupsUri(this.userName)); ContactsService service = new ContactsService("unittests"); if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } GroupsFeed feed = service.Query(query); int i = 0; foreach (GroupEntry g in feed.Entries ) { if (g.SystemGroup != null) { i++; } } Assert.IsTrue(i==4, "There should be 4 system groups in the groups feed"); ObjectModelHelper.DumpAtomObject(feed,CreateDumpFileName("GroupsAuthTest")); GroupEntry newGroup = new GroupEntry(); newGroup.Title.Text = "Private Data"; GroupEntry insertedGroup = feed.Insert(newGroup); GroupEntry g2 = new GroupEntry(); g2.Title.Text = "Another Private Group"; GroupEntry insertedGroup2 = feed.Insert(g2); // now insert a new contact that belongs to that group ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName)); ContactsFeed cf = service.Query(q); ContactEntry entry = ObjectModelHelper.CreateContactEntry(1); GroupMembership member = new GroupMembership(); member.HRef = insertedGroup.Id.Uri.ToString(); GroupMembership member2 = new GroupMembership(); member2.HRef = insertedGroup2.Id.Uri.ToString(); ContactEntry insertedEntry = cf.Insert(entry); // now change the group membership insertedEntry.GroupMembership.Add(member); insertedEntry.GroupMembership.Add(member2); ContactEntry currentEntry = insertedEntry.Update(); Assert.IsTrue(currentEntry.GroupMembership.Count == 2, "The entry should be in 2 groups"); currentEntry.GroupMembership.Clear(); currentEntry = currentEntry.Update(); // now we should have 2 new groups and one new entry with no groups anymore int oldCountGroups = feed.Entries.Count; int oldCountContacts = cf.Entries.Count; currentEntry.Delete(); insertedGroup.Delete(); insertedGroup2.Delete(); feed = service.Query(query); cf = service.Query(q); Assert.AreEqual(oldCountContacts, cf.Entries.Count, "Contacts count should be the same"); Assert.AreEqual(oldCountGroups, feed.Entries.Count, "Groups count should be the same"); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] [Ignore("with v2, it is not clear anymore how to force a conflict")] public void ConflictContactsTest() { const int numberOfInserts = 50; const int numberWithAdds = 60; Tracing.TraceMsg("Entering InsertContactsTest"); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName)); ContactsService service = new ContactsService("unittests"); if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } // clean the contacts feed DeleteAllContacts(); ContactsFeed feed = service.Query(query); int originalCount = feed.Entries.Count; string email = Guid.NewGuid().ToString(); List<ContactEntry> inserted = new List<ContactEntry>(); // insert a number of guys for (int i = 0; i < numberOfInserts; i++) { ContactEntry entry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = email + i.ToString() + "@doe.com"; entry = feed.Insert(entry); AddContactPhoto(entry, service); inserted.Add(entry); } if (feed != null) { for (int x = numberOfInserts; x <= numberWithAdds; x++) { for (int i = 0; i < x; i++) { ContactEntry entry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = email + i.ToString() + "@doe.com"; try { entry = feed.Insert(entry); AddContactPhoto(entry, service); inserted.Add(entry); } catch (GDataRequestException) { } } } } List<ContactEntry> list = new List<ContactEntry>(); feed = service.Query(query); foreach (ContactEntry e in feed.Entries) { list.Add(e); } while (feed.NextChunk != null) { ContactsQuery nq = new ContactsQuery(feed.NextChunk); feed = service.Query(nq); foreach (ContactEntry e in feed.Entries) { list.Add(e); } } Assert.AreEqual(list.Count, numberWithAdds - originalCount, "We should have added new entries"); // clean the contacts feed DeleteAllContacts(); } ///////////////////////////////////////////////////////////////////////////// private void AddContactPhoto(ContactEntry entry, ContactsService contactService) { try { using (FileStream fs = new FileStream(this.resourcePath + "contactphoto.jpg", System.IO.FileMode.Open)) { Stream res = contactService.StreamSend(entry.PhotoUri, fs, GDataRequestType.Update, "image/jpg", null); res.Close(); } } finally { } } private void DeleteAllContacts() { RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); ContactsTestSuite.DeleteAllContacts(rs); } internal static void DeleteAllContacts(RequestSettings rs) { rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); List<Contact> list = new List<Contact>(); int i=0; foreach (Contact c in f.Entries) { c.BatchData = new GDataBatchEntryData(); c.BatchData.Id = i.ToString(); c.BatchData.Type = GDataBatchOperationType.delete; i++; list.Add(c); } cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.delete); f = cr.GetContacts(); Assert.IsTrue(f.TotalResults == 0, "Feed should be empty now"); } ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void InsertContactsTest() { const int numberOfInserts = 37; Tracing.TraceMsg("Entering InsertContactsTest"); ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri(this.userName)); ContactsService service = new ContactsService("unittests"); if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } ContactsFeed feed = service.Query(query); int originalCount = feed.Entries.Count; PhoneNumber p = null; List<ContactEntry> inserted = new List<ContactEntry>(); if (feed != null) { Assert.IsTrue(feed.Entries != null, "the contacts needs entries"); for (int i = 0; i < numberOfInserts; i++) { ContactEntry entry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; p = entry.PrimaryPhonenumber; inserted.Add(feed.Insert(entry)); } } List<ContactEntry> list = new List<ContactEntry>(); feed = service.Query(query); foreach (ContactEntry e in feed.Entries) { list.Add(e); } while (feed.NextChunk != null) { ContactsQuery nq = new ContactsQuery(feed.NextChunk); feed = service.Query(nq); foreach (ContactEntry e in feed.Entries) { list.Add(e); } } if (inserted.Count > 0) { int iVer = numberOfInserts; // let's find those guys for (int i = 0; i < inserted.Count; i++) { ContactEntry test = inserted[i] as ContactEntry; foreach (ContactEntry e in list) { if (e.Id == test.Id) { iVer--; // verify we got the phonenumber back.... Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber"); Assert.AreEqual(e.PrimaryPhonenumber.Value,p.Value, "They should be identical"); } } } Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have " + iVer + " now"); } // now delete them again foreach (ContactEntry e in inserted) { e.Delete(); } // now make sure they are gone if (inserted.Count > 0) { feed = service.Query(query); // let's find those guys, we should not find ANY for (int i = 0; i < inserted.Count; i++) { ContactEntry test = inserted[i] as ContactEntry; foreach (ContactEntry e in feed.Entries) { Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now"); } } Assert.IsTrue(feed.Entries.Count == originalCount, "The count should be correct as well"); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact with an extended property</summary> ////////////////////////////////////////////////////////////////////// [Test] public void InsertExtendedPropertyContactsTest() { Tracing.TraceMsg("Entering InsertExtendedPropertyContactsTest"); DeleteAllContacts(); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; FeedQuery query = new FeedQuery(); query.Uri = new Uri(CreateUri(this.resourcePath + "contactsextendedprop.xml")); ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.Get<Contact>(query); Contact newEntry = null; foreach (Contact c in f.Entries) { ExtendedProperty e = c.ExtendedProperties[0]; Assert.IsTrue(e != null); newEntry = c; } f = cr.GetContacts(); Contact createdEntry = cr.Insert<Contact>(f, newEntry); cr.Delete(createdEntry); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>Tests the primary Accessors</summary> ////////////////////////////////////////////////////////////////////// [Test] public void TestPrimaryContactsProperties() { Tracing.TraceMsg("Entering TestPrimaryContactsProperties"); ContactEntry entry = new ContactEntry(); EMail e = new EMail(); e.Primary = true; e.Address = "joe@smith.com"; Assert.IsTrue(entry.PrimaryEmail == null, "Entry should have no primary Email"); entry.Emails.Add(e); Assert.IsTrue(entry.PrimaryEmail == e, "Entry should have one primary Email"); entry.Emails.Remove(e); Assert.IsTrue(entry.PrimaryEmail == null, "Entry should have no primary Email"); entry.Emails.Add(e); Assert.IsTrue(entry.PrimaryEmail == e, "Entry should have one primary Email"); entry.Emails.RemoveAt(0); Assert.IsTrue(entry.PrimaryEmail == null, "Entry should have no primary Email"); foreach (Object o in entry.ExtensionElements) { if (o is EMail) { Assert.IsTrue(o == null, "There should be no email in the collection"); } } StructuredPostalAddress p = CreatePostalAddress(); Assert.IsTrue(entry.PrimaryPostalAddress == null, "Entry should have no primary Postal"); entry.PostalAddresses.Add(p); Assert.IsTrue(entry.PrimaryPostalAddress == p, "Entry should have one primary Postal"); entry.PostalAddresses.Remove(p); Assert.IsTrue(entry.PrimaryPostalAddress == null, "Entry should have no primary Postal"); PhoneNumber n = new PhoneNumber("123345"); n.Primary = true; Assert.IsTrue(entry.PrimaryPhonenumber == null, "Entry should have no primary Phonenumber"); entry.Phonenumbers.Add(n); Assert.IsTrue(entry.PrimaryPhonenumber == n, "Entry should have one primary Phonenumber"); entry.Phonenumbers.Remove(n); Assert.IsTrue(entry.PrimaryPhonenumber == null, "Entry should have no primary Phonenumber"); IMAddress i = new IMAddress("joe@smight.com"); i.Primary = true; Assert.IsTrue(entry.PrimaryIMAddress == null, "Entry should have no primary IM"); entry.IMs.Add(new IMAddress()); entry.IMs.Add(i); Assert.IsTrue(entry.PrimaryIMAddress == i, "Entry should have one primary IMAddress"); entry.IMs.Remove(i); Assert.IsTrue(entry.PrimaryIMAddress == null, "Entry should have no primary IM"); } public static StructuredPostalAddress CreatePostalAddress() { StructuredPostalAddress p = new StructuredPostalAddress(); p.City = "TestTown"; p.Street = "Rosanna Drive"; p.Postcode = "12345"; p.Country = "The good ole Country"; p.Primary = true; return p; } ////////////////////////////////////////////////////////////////////// /// <summary>Tests the primary Accessors</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelPrimaryContactsProperties() { Tracing.TraceMsg("Entering TestModelPrimaryContactsProperties"); Contact c = new Contact(); EMail e = new EMail(); e.Primary = true; e.Address = "joe@smith.com"; Assert.IsTrue(c.PrimaryEmail == null, "Contact should have no primary Email"); c.Emails.Add(e); Assert.IsTrue(c.PrimaryEmail == e, "Contact should have one primary Email"); c.Emails.Remove(e); Assert.IsTrue(c.PrimaryEmail == null, "Contact should have no primary Email"); c.Emails.Add(e); Assert.IsTrue(c.PrimaryEmail == e, "Contact should have one primary Email"); c.Emails.RemoveAt(0); Assert.IsTrue(c.PrimaryEmail == null, "Contact should have no primary Email"); foreach (Object o in c.ContactEntry.ExtensionElements) { if (o is EMail) { Assert.IsTrue(o == null, "There should be no email in the collection"); } } StructuredPostalAddress p = CreatePostalAddress(); Assert.IsTrue(c.PrimaryPostalAddress == null, "Contact should have no primary Postal"); c.PostalAddresses.Add(p); Assert.IsTrue(c.PrimaryPostalAddress == p, "Contact should have one primary Postal"); c.PostalAddresses.Remove(p); Assert.IsTrue(c.PrimaryPostalAddress == null, "Contact should have no primary Postal"); PhoneNumber n = new PhoneNumber("123345"); n.Primary = true; Assert.IsTrue(c.PrimaryPhonenumber == null, "Contact should have no primary Phonenumber"); c.Phonenumbers.Add(n); Assert.IsTrue(c.PrimaryPhonenumber == n, "Contact should have one primary Phonenumber"); c.Phonenumbers.Remove(n); Assert.IsTrue(c.PrimaryPhonenumber == null, "Contact should have no primary Phonenumber"); IMAddress i = new IMAddress("joe@smight.com"); i.Primary = true; Assert.IsTrue(c.PrimaryIMAddress == null, "Contact should have no primary IM"); c.IMs.Add(new IMAddress()); c.IMs.Add(i); Assert.IsTrue(c.PrimaryIMAddress == i, "Contact should have one primary IMAddress"); c.IMs.Remove(i); Assert.IsTrue(c.PrimaryIMAddress == null, "Contact should have no primary IM"); } ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelInsertContactsTest() { const int numberOfInserts = 37; Tracing.TraceMsg("Entering ModelInsertContactsTest"); DeleteAllContacts(); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); int originalCount = f.TotalResults; PhoneNumber p = null; List<Contact> inserted = new List<Contact>(); if (f != null) { Assert.IsTrue(f.Entries != null, "the contacts needs entries"); for (int i = 0; i < numberOfInserts; i++) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; p = entry.PrimaryPhonenumber; inserted.Add(cr.Insert(f, entry)); } } List<Contact> list = new List<Contact>(); f = cr.GetContacts(); foreach (Contact e in f.Entries) { list.Add(e); } if (inserted.Count > 0) { int iVer = numberOfInserts; // let's find those guys for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i]; foreach (Contact e in list) { if (e.Id == test.Id) { iVer--; // verify we got the phonenumber back.... Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber"); Assert.AreEqual(e.PrimaryPhonenumber.Value,p.Value, "They should be identical"); } } } Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, " + iVer + " left over"); } // now delete them again DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch)); // now make sure they are gone if (inserted.Count > 0) { f = cr.GetContacts(); Assert.IsTrue(f.TotalResults == originalCount, "The count should be correct as well"); foreach (Contact e in f.Entries) { // let's find those guys, we should not find ANY for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i] as Contact; Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now"); } } } } ///////////////////////////////////////////////////////////////////////////// internal static void DeleteList(List<Contact> list, ContactsRequest cr, Uri batch) { int i = 0; foreach (Contact c in list) { c.BatchData = new GDataBatchEntryData(); c.BatchData.Id = i.ToString(); i++; } cr.Batch(list, batch, GDataBatchOperationType.delete); } ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelUpdateContactsTest() { const int numberOfInserts = 5; Tracing.TraceMsg("Entering ModelInsertContactsTest"); DeleteAllContacts(); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); int originalCount = f.TotalResults; PhoneNumber p = null; List<Contact> inserted = new List<Contact>(); if (f != null) { Assert.IsTrue(f.Entries != null, "the contacts needs entries"); for (int i = 0; i < numberOfInserts; i++) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; p = entry.PrimaryPhonenumber; inserted.Add(cr.Insert(f, entry)); } } string newTitle = "This is an update to the title"; f = cr.GetContacts(); if (inserted.Count > 0) { int iVer = numberOfInserts; // let's find those guys foreach (Contact e in f.Entries ) { for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i]; if (e.Id == test.Id) { iVer--; // verify we got the phonenumber back.... Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber"); Assert.AreEqual(e.PrimaryPhonenumber.Value,p.Value, "They should be identical"); e.Name.FamilyName = newTitle; inserted[i] = cr.Update(e); } } } Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have " + iVer + " left"); } f = cr.GetContacts(); if (inserted.Count > 0) { int iVer = numberOfInserts; // let's find those guys foreach (Contact e in f.Entries ) { for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i]; if (e.Id == test.Id) { iVer--; // verify we got the phonenumber back.... Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber"); Assert.AreEqual(e.PrimaryPhonenumber.Value,p.Value, "They should be identical"); Assert.AreEqual(e.Name.FamilyName, newTitle, "The familyname should have been updated"); } } } Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have: " + iVer + " now"); } // now delete them again DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch)); // now make sure they are gone if (inserted.Count > 0) { int iVer = inserted.Count; f = cr.GetContacts(); foreach (Contact e in f.Entries) { // let's find those guys, we should not find ANY for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i] as Contact; Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now"); } } Assert.IsTrue(f.TotalResults == originalCount, "The count should be correct as well"); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelUpdateIfMatchAllContactsTest() { const int numberOfInserts = 5; Tracing.TraceMsg("Entering ModelInsertContactsTest"); DeleteAllContacts(); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); int originalCount = f.TotalResults; PhoneNumber p = null; List<Contact> inserted = new List<Contact>(); if (f != null) { Assert.IsTrue(f.Entries != null, "the contacts needs entries"); for (int i = 0; i < numberOfInserts; i++) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; p = entry.PrimaryPhonenumber; inserted.Add(cr.Insert(f, entry)); } } string newTitle = "This is an update to the title"; f = cr.GetContacts(); if (inserted.Count > 0) { int iVer = numberOfInserts; // let's find those guys foreach (Contact e in f.Entries) { for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i]; if (e.Id == test.Id) { iVer--; // verify we got the phonenumber back.... Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber"); Assert.AreEqual(e.PrimaryPhonenumber.Value, p.Value, "They should be identical"); e.Name.FamilyName = newTitle; e.ETag = GDataRequestFactory.IfMatchAll; inserted[i] = cr.Update(e); } } } Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have " + iVer + " left"); } f = cr.GetContacts(); if (inserted.Count > 0) { int iVer = numberOfInserts; // let's find those guys foreach (Contact e in f.Entries) { for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i]; if (e.Id == test.Id) { iVer--; // verify we got the phonenumber back.... Assert.IsTrue(e.PrimaryPhonenumber != null, "They should have a primary phonenumber"); Assert.AreEqual(e.PrimaryPhonenumber.Value, p.Value, "They should be identical"); Assert.AreEqual(e.Name.FamilyName, newTitle, "The familyname should have been updated"); } } } Assert.IsTrue(iVer == 0, "The new entries should all be part of the feed now, we have: " + iVer + " now"); } // now delete them again DeleteList(inserted, cr, new Uri(f.AtomFeed.Batch)); // now make sure they are gone if (inserted.Count > 0) { int iVer = inserted.Count; f = cr.GetContacts(); foreach (Contact e in f.Entries) { // let's find those guys, we should not find ANY for (int i = 0; i < inserted.Count; i++) { Contact test = inserted[i] as Contact; Assert.IsTrue(e.Id != test.Id, "The new entries should all be deleted now"); } } Assert.IsTrue(f.TotalResults == originalCount, "The count should be correct as well"); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests querying contacts with an etag</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelTestETagQuery() { Tracing.TraceMsg("Entering ModelTestETagQuery"); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); ContactsQuery q = new ContactsQuery(ContactsQuery.CreateContactsUri(null)); q.Etag = ((ISupportsEtag)f.AtomFeed).Etag; try { f = cr.Get<Contact>(q); foreach (Contact c in f.Entries) { } } catch (GDataNotModifiedException g) { Assert.IsTrue(g != null); } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelPhotoTest() { Tracing.TraceMsg("Entering ModelPhotoTest"); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Contact> f = cr.GetContacts(); Contact e = null; if (f != null) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(1); entry.PrimaryEmail.Address = "joe@doe.com"; e = cr.Insert(f, entry); } Assert.IsTrue(e!=null, "we should have a contact here"); Stream s = cr.GetPhoto(e); Assert.IsTrue(s == null, "There should be no photo yet"); using (FileStream fs = new FileStream(this.resourcePath + "contactphoto.jpg", System.IO.FileMode.Open)) { cr.SetPhoto(e, fs); } // now delete the guy, which requires us to reload him from the server first, as the photo change operation // changes the etag off the entry e = cr.Retrieve(e); cr.Delete(e); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test, inserts a new contact</summary> ////////////////////////////////////////////////////////////////////// [Test] public void ModelBatchContactsTest() { const int numberOfInserts = 5; Tracing.TraceMsg("Entering ModelInsertContactsTest"); DeleteAllContacts(); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); List<Contact> list = new List<Contact>(); Feed<Contact> f = cr.GetContacts(); for (int i = 0; i < numberOfInserts; i++) { Contact entry = new Contact(); entry.AtomEntry = ObjectModelHelper.CreateContactEntry(i); entry.PrimaryEmail.Address = "joe" + i.ToString() + "@doe.com"; GDataBatchEntryData g = new GDataBatchEntryData(); g.Id = i.ToString(); g.Type = GDataBatchOperationType.insert; entry.BatchData = g; list.Add(entry); } Feed<Contact> r = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default); list.Clear(); int iVerify = 0; foreach (Contact c in r.Entries ) { // let's count and update them iVerify++; c.Name.FamilyName = "get a nother one"; c.BatchData.Type = GDataBatchOperationType.update; list.Add(c); } Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 inserts"); Feed<Contact> u = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default); list.Clear(); iVerify = 0; foreach (Contact c in u.Entries ) { // let's count and update them iVerify++; c.BatchData.Type = GDataBatchOperationType.delete; list.Add(c); } Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 updates"); Feed<Contact> d = cr.Batch(list, new Uri(f.AtomFeed.Batch), GDataBatchOperationType.Default); iVerify = 0; foreach (Contact c in d.Entries ) { if (c.BatchData.Status.Code == 200) { // let's count and update them iVerify++; } } Assert.IsTrue(iVerify == numberOfInserts, "should have gotten 5 deletes"); } ///////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// /// <summary>runs an basic auth test against the groups feed test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void GroupsModelTest() { Tracing.TraceMsg("Entering GroupsModelTest"); RequestSettings rs = new RequestSettings(this.ApplicationName, this.userName, this.passWord); rs.AutoPaging = true; ContactsRequest cr = new ContactsRequest(rs); Feed<Group> fg = cr.GetGroups(); Group newGroup = new Group(); newGroup.Title = "Private Data"; Group insertedGroup = cr.Insert(fg, newGroup); Group g2 = new Group(); g2.Title = "Another private Group"; Group insertedGroup2 = cr.Insert(fg, g2); // now insert a new contact that belongs to that group Feed<Contact> fc = cr.GetContacts(); Contact c = new Contact(); c.AtomEntry = ObjectModelHelper.CreateContactEntry(1); GroupMembership member = new GroupMembership(); member.HRef = insertedGroup.Id; GroupMembership member2 = new GroupMembership(); member2.HRef = insertedGroup2.Id; Contact insertedEntry = cr.Insert(fc, c); // now change the group membership insertedEntry.GroupMembership.Add(member); insertedEntry.GroupMembership.Add(member2); Contact currentEntry = cr.Update(insertedEntry); Assert.IsTrue(currentEntry.GroupMembership.Count == 2, "The entry should be in 2 groups"); currentEntry.GroupMembership.Clear(); currentEntry = cr.Update(currentEntry); Assert.IsTrue(currentEntry.GroupMembership.Count == 0, "The entry should not be in a group"); cr.Delete(currentEntry); cr.Delete(insertedGroup); cr.Delete(insertedGroup2); } ///////////////////////////////////////////////////////////////////////////// } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; using Xunit; namespace System.Linq.Expressions.Tests { public static class MemberAccessTests { private class UnreadableIndexableClass { public int this[int index] { set { } } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructInstanceFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(new FS() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructStaticFieldTest(bool useInterpreter) { FS.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { FS.SI = 0; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructConstFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "CI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructStaticReadOnlyFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FS), "RI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructInstancePropertyTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(new PS() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessStructStaticPropertyTest(bool useInterpreter) { PS.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( null, typeof(PS), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { PS.SI = 0; } } [Theory, ClassData(typeof(CompilationTypes))] public static void NullNullableValueException(bool useInterpreter) { string localizedMessage = null; try { int dummy = default(int?).Value; } catch (InvalidOperationException ioe) { localizedMessage = ioe.Message; } Expression<Func<long>> e = () => default(long?).Value; Func<long> f = e.Compile(useInterpreter); InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => f()); Assert.Equal(localizedMessage, exception.Message); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(new FC() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassStaticFieldTest(bool useInterpreter) { FC.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { FC.SI = 0; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassConstFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "CI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassStaticReadOnlyFieldTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( null, typeof(FC), "RI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Fact] public static void Field_NullField_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("field", () => Expression.Field(null, (FieldInfo)null)); Assert.Throws<ArgumentNullException>("fieldName", () => Expression.Field(Expression.Constant(new FC()), (string)null)); } [Fact] public static void Field_NullType_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("type", () => Expression.Field(Expression.Constant(new FC()), null, "AField")); } [Fact] public static void Field_StaticField_NonNullExpression_ThrowsArgumentException() { Expression expression = Expression.Constant(new FC()); Assert.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC), nameof(FC.SI))); Assert.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.SI)))); Assert.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.SI)))); } [Fact] public static void Field_ByrefTypeFieldAccessor_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Expression.Property(null, typeof(GenericClass<string>).MakeByRefType(), nameof(GenericClass<string>.Field))); } [Fact] public static void Field_GenericFieldAccessor_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Expression.Property(null, typeof(GenericClass<>), nameof(GenericClass<string>.Field))); } [Fact] public static void Field_InstanceField_NullExpression_ThrowsArgumentException() { Assert.Throws<ArgumentNullException>("expression", () => Expression.Field(null, "fieldName")); Assert.Throws<ArgumentException>("field", () => Expression.Field(null, typeof(FC), nameof(FC.II))); Assert.Throws<ArgumentException>("field", () => Expression.Field(null, typeof(FC).GetField(nameof(FC.II)))); Assert.Throws<ArgumentException>("field", () => Expression.MakeMemberAccess(null, typeof(FC).GetField(nameof(FC.II)))); } [Fact] public static void Field_ExpressionNotReadable_ThrowsArgumentException() { Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)); Assert.Throws<ArgumentException>("expression", () => Expression.Field(expression, "fieldName")); Assert.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC), nameof(FC.SI))); Assert.Throws<ArgumentException>("expression", () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.SI)))); Assert.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.SI)))); } [Fact] public static void Field_ExpressionNotTypeOfDeclaringType_ThrowsArgumentException() { Expression expression = Expression.Constant(new PC()); Assert.Throws<ArgumentException>(null, () => Expression.Field(expression, typeof(FC), nameof(FC.II))); Assert.Throws<ArgumentException>(null, () => Expression.Field(expression, typeof(FC).GetField(nameof(FC.II)))); Assert.Throws<ArgumentException>(null, () => Expression.MakeMemberAccess(expression, typeof(FC).GetField(nameof(FC.II)))); } [Fact] public static void Field_NoSuchFieldName_ThrowsArgumentException() { Assert.Throws<ArgumentException>(null, () => Expression.Field(Expression.Constant(new FC()), "NoSuchField")); Assert.Throws<ArgumentException>(null, () => Expression.Field(Expression.Constant(new FC()), typeof(FC), "NoSuchField")); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstancePropertyTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(new PC() { II = 42 }), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassStaticPropertyTest(bool useInterpreter) { PC.SI = 42; try { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( null, typeof(PC), "SI"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Equal(42, f()); } finally { PC.SI = 0; } } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceFieldNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Field( Expression.Constant(null, typeof(FC)), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceFieldAssignNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Assign( Expression.Field( Expression.Constant(null, typeof(FC)), "II"), Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstancePropertyNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(null, typeof(PC)), "II"), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceIndexerNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Property( Expression.Constant(null, typeof(PC)), "Item", Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Theory] [ClassData(typeof(CompilationTypes))] public static void CheckMemberAccessClassInstanceIndexerAssignNullReferenceTest(bool useInterpreter) { Expression<Func<int>> e = Expression.Lambda<Func<int>>( Expression.Assign( Expression.Property( Expression.Constant(null, typeof(PC)), "Item", Expression.Constant(1)), Expression.Constant(1)), Enumerable.Empty<ParameterExpression>()); Func<int> f = e.Compile(useInterpreter); Assert.Throws<NullReferenceException>(() => f()); } [Fact] public static void AccessIndexedPropertyWithoutIndex() { Assert.Throws<ArgumentException>("property", () => Expression.Property(Expression.Default(typeof(List<int>)), typeof(List<int>).GetProperty("Item"))); } [Fact] public static void AccessIndexedPropertyWithoutIndexWriteOnly() { Assert.Throws<ArgumentException>("property", () => Expression.Property(Expression.Default(typeof(UnreadableIndexableClass)), typeof(UnreadableIndexableClass).GetProperty("Item"))); } [Fact] public static void Property_NullProperty_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("property", () => Expression.Property(null, (PropertyInfo)null)); Assert.Throws<ArgumentNullException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), (string)null)); } [Fact] public static void Property_NullType_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("type", () => Expression.Property(Expression.Constant(new PC()), null, "AProperty")); } [Fact] public static void Property_StaticProperty_NonNullExpression_ThrowsArgumentException() { Expression expression = Expression.Constant(new PC()); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC), nameof(PC.SI))); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)))); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)).GetGetMethod())); Assert.Throws<ArgumentException>("expression", () => Expression.MakeMemberAccess(expression, typeof(PC).GetProperty(nameof(PC.SI)))); } [Fact] public static void Property_InstanceProperty_NullExpression_ThrowsArgumentException() { Assert.Throws<ArgumentNullException>("expression", () => Expression.Property(null, "propertyName")); Assert.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC), nameof(PC.II))); Assert.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC).GetProperty(nameof(PC.II)))); Assert.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(PC).GetProperty(nameof(PC.II)).GetGetMethod())); Assert.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(null, typeof(PC).GetProperty(nameof(PC.II)))); } [Fact] public static void Property_ExpressionNotReadable_ThrowsArgumentException() { Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, "fieldName")); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC), nameof(PC.SI))); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)))); Assert.Throws<ArgumentException>("expression", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.SI)).GetGetMethod())); } [Fact] public static void Property_ExpressionNotTypeOfDeclaringType_ThrowsArgumentException() { Expression expression = Expression.Constant(new FC()); Assert.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC), nameof(PC.II))); Assert.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.II)))); Assert.Throws<ArgumentException>("property", () => Expression.Property(expression, typeof(PC).GetProperty(nameof(PC.II)).GetGetMethod())); Assert.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(expression, typeof(PC).GetProperty(nameof(PC.II)))); } [Fact] public static void Property_NoSuchPropertyName_ThrowsArgumentException() { Assert.Throws<ArgumentException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), "NoSuchProperty")); Assert.Throws<ArgumentException>("propertyName", () => Expression.Property(Expression.Constant(new PC()), typeof(PC), "NoSuchProperty")); } [Fact] public static void Property_NullPropertyAccessor_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("propertyAccessor", () => Expression.Property(Expression.Constant(new PC()), (MethodInfo)null)); } [Fact] public static void Property_GenericPropertyAccessor_ThrowsArgumentException() { Assert.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(GenericClass<>).GetProperty(nameof(GenericClass<string>.Property)).GetGetMethod())); Assert.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.GenericMethod)))); Assert.Throws<ArgumentException>("property", () => Expression.Property(null, typeof(GenericClass<>).GetProperty(nameof(GenericClass<string>.Property)))); } [Fact] public static void Property_PropertyAccessorNotFromProperty_ThrowsArgumentException() { Assert.Throws<ArgumentException>("propertyAccessor", () => Expression.Property(null, typeof(NonGenericClass).GetMethod(nameof(NonGenericClass.StaticMethod)))); } [Fact] public static void Property_ByRefStaticAccess_ThrowsArgumentException() { Assert.Throws<ArgumentException>(() => Expression.Property(null, typeof(NonGenericClass).MakeByRefType(), nameof(NonGenericClass.NonGenericProperty))); } [Fact] public static void PropertyOrField_NullExpression_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("expression", () => Expression.PropertyOrField(null, "APropertyOrField")); } [Fact] public static void PropertyOrField_ExpressionNotReadable_ThrowsArgumentNullException() { Expression expression = Expression.Property(null, typeof(Unreadable<string>), nameof(Unreadable<string>.WriteOnly)); Assert.Throws<ArgumentException>("expression", () => Expression.PropertyOrField(expression, "APropertyOrField")); } [Fact] public static void PropertyOrField_NoSuchPropertyOrField_ThrowsArgumentException() { Expression expression = Expression.Constant(new PC()); Assert.Throws<ArgumentException>("propertyOrFieldName", () => Expression.PropertyOrField(expression, "NoSuchPropertyOrField")); } [Fact] public static void MakeMemberAccess_NullMember_ThrowsArgumentNullExeption() { Assert.Throws<ArgumentNullException>("member", () => Expression.MakeMemberAccess(Expression.Constant(new PC()), null)); } [Fact] public static void MakeMemberAccess_MemberNotFieldOrProperty_ThrowsArgumentExeption() { MemberInfo member = typeof(NonGenericClass).GetEvent("Event"); Assert.Throws<ArgumentException>("member", () => Expression.MakeMemberAccess(Expression.Constant(new PC()), member)); } [Fact] public static void Property_NoGetOrSetAccessors_ThrowsArgumentException() { AssemblyBuilder assembly = AssemblyBuilder.DefineDynamicAssembly(new AssemblyName("Name"), AssemblyBuilderAccess.Run); ModuleBuilder module = assembly.DefineDynamicModule("Module"); TypeBuilder type = module.DefineType("Type"); PropertyBuilder property = type.DefineProperty("Property", PropertyAttributes.None, typeof(void), new Type[0]); TypeInfo createdType = type.CreateTypeInfo(); PropertyInfo createdProperty = createdType.DeclaredProperties.First(); Expression expression = Expression.Constant(Activator.CreateInstance(createdType.AsType())); Assert.Throws<ArgumentException>("property", () => Expression.Property(expression, createdProperty)); Assert.Throws<ArgumentException>("property", () => Expression.Property(expression, createdProperty.Name)); Assert.Throws<ArgumentException>("property", () => Expression.PropertyOrField(expression, createdProperty.Name)); Assert.Throws<ArgumentException>("property", () => Expression.MakeMemberAccess(expression, createdProperty)); } [Fact] public static void ToStringTest() { MemberExpression e1 = Expression.Property(null, typeof(DateTime).GetProperty(nameof(DateTime.Now))); Assert.Equal("DateTime.Now", e1.ToString()); MemberExpression e2 = Expression.Property(Expression.Parameter(typeof(DateTime), "d"), typeof(DateTime).GetProperty(nameof(DateTime.Year))); Assert.Equal("d.Year", e2.ToString()); } [Fact] public static void UpdateSameResturnsSame() { var exp = Expression.Constant(new PS {II = 42}); var pro = Expression.Property(exp, nameof(PS.II)); Assert.Same(pro, pro.Update(exp)); } [Fact] public static void UpdateStaticResturnsSame() { var pro = Expression.Property(null, typeof(PS), nameof(PS.SI)); Assert.Same(pro, pro.Update(null)); } [Fact] public static void UpdateDifferentResturnsDifferent() { var pro = Expression.Property(Expression.Constant(new PS {II = 42}), nameof(PS.II)); Assert.NotSame(pro, pro.Update(Expression.Constant(new PS {II = 42}))); } } }
// 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. // throw in catch handler using System; using System.IO; namespace TestUtil { // This class implements a string writer that writes to a string buffer and a // given text writer, which allows echoing the written string if stdout is // specified as the text writer. public class StringRecorder : StringWriter { private TextWriter _outStream; private int _outLimit; // maximum output size limit in characters private bool _bufferIsFull; // if set, stop writting/recording output // Constructs a new StringRecorder that writes to the given TextWriter. public StringRecorder(TextWriter ostream, int olimit) { if (ostream == null) { throw new ArgumentNullException("ostream", "Output stream cannot be null."); } this._outStream = ostream; this._outLimit = olimit; this._bufferIsFull = false; } public StringRecorder(TextWriter ostream) : this(ostream, 0) { } // Only these three methods need to be overridden in order to override // all different overloads of Write/WriteLine methods. public override void Write(char c) { if (!this._bufferIsFull) { _outStream.Write(c); base.Write(c); this.CheckOverflow(); } } public override void Write(string val) { if (!this._bufferIsFull) { _outStream.Write(val); base.Write(val); this.CheckOverflow(); } } public override void Write(char[] buffer, int index, int count) { if (!this._bufferIsFull) { _outStream.Write(buffer, index, count); base.Write(buffer, index, count); this.CheckOverflow(); } } protected void CheckOverflow() { if (this._outLimit > 0 && this.ToString().Length > this._outLimit) { this._bufferIsFull = true; this._outStream.WriteLine("ERROR: Output exceeded maximum limit, extra output will be discarded!"); } } } // This class represents a test log. It allows for redirecting both stdout // and stderr of the test to StringRecorder objects. The redirected output // can then be compared to expected output supplied to the class // constructor. public class TestLog { const int SUCC_RET_CODE = 100; const int FAIL_RET_CODE = 1; const int OUTPUT_LIMIT_FACTOR = 100; const string IGNORE_STR = "#IGNORE#"; protected string expectedOut; protected string expectedError; protected TextWriter stdOut; protected TextWriter stdError; protected StringWriter testOut; protected StringWriter testError; public TestLog() : this(null, null) { } public TestLog(object expOut) : this(expOut, null) { } // Creates a new TestLog and set both expected output, and // expected error to supplied values. public TestLog(object expOut, object expError) { this.expectedOut = expOut == null ? String.Empty : expOut.ToString(); this.expectedError = expError == null ? String.Empty : expError.ToString(); this.stdOut = System.Console.Out; this.stdError = System.Console.Error; this.testOut = new StringRecorder(this.stdOut, this.expectedOut != null ? this.expectedOut.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); this.testError = new StringRecorder(this.stdError, this.expectedError != null ? this.expectedError.ToString().Length * OUTPUT_LIMIT_FACTOR : 0); } // Start recoding by redirecting both stdout and stderr to // string recorders. public void StartRecording() { System.Console.SetOut(this.testOut); System.Console.SetError(this.testError); } // Stop recording by resetting both stdout and stderr to their // initial values. public void StopRecording() { // For now we disable the ability of stop recoding, so that we still recoed until the program exits. // This issue came up with finally being called twice. The first time we stop recoding and from this // point on we loose all output. // System.Console.SetOut(this.stdOut); // System.Console.SetError(this.stdError); } // Returns true if both expected output and expected error are // identical to actual output and actual error; false otherwise. protected bool Identical() { return this.testOut.ToString().Equals(this.expectedOut) && this.testError.ToString().Equals(this.expectedError); } // Display differences between expected output and actual output. protected string Diff() { string result = String.Empty; if (!this.testOut.ToString().Equals(this.expectedOut)) { string newLine = this.testOut.NewLine; string delimStr = newLine[0].ToString(); string[] actualLines = ((this.ActualOutput.Trim()).Replace(newLine, delimStr)).Split(delimStr.ToCharArray()); string[] expectedLines = ((this.ExpectedOutput.Trim()).Replace(newLine, delimStr)).Split(delimStr.ToCharArray()); int commonLineCount = actualLines.Length < expectedLines.Length ? actualLines.Length : expectedLines.Length; bool identical = true; for (int i = 0; i < commonLineCount && identical; ++i) { string actualLine = actualLines[i]; string expectedLine = expectedLines[i]; bool similar = true; while (!actualLine.Equals(expectedLine) && similar) { bool ignoreMode = false; while (expectedLine.StartsWith(IGNORE_STR)) { expectedLine = expectedLine.Substring(IGNORE_STR.Length); ignoreMode = true; } int nextIgnore = expectedLine.IndexOf(IGNORE_STR); if (nextIgnore > 0) { string expectedToken = expectedLine.Substring(0, nextIgnore); int at = actualLine.IndexOf(expectedToken); similar = (at == 0) || (ignoreMode && at > 0); expectedLine = expectedLine.Substring(nextIgnore); actualLine = similar ? actualLine.Substring(at + expectedToken.Length) : actualLine; } else { similar = (ignoreMode && actualLine.EndsWith(expectedLine)) || actualLine.Equals(expectedLine); expectedLine = String.Empty; actualLine = String.Empty; } } if (!similar) { result += ("< " + expectedLines[i] + newLine); result += "---" + newLine; result += ("> " + actualLines[i] + newLine); identical = false; } } if (identical) { for (int i = commonLineCount; i < expectedLines.Length; ++i) { result += ("< " + expectedLines[i] + newLine); } for (int i = commonLineCount; i < actualLines.Length; ++i) { result += ("< " + actualLines[i] + newLine); } } } return result; } // Verifies test output and error strings. If identical it returns // successful return code; otherwise it prints expected output and // diff results, and it returns failed result code. public int VerifyOutput() { int retCode = -1; string diff = this.Diff(); if (String.Empty.Equals(diff)) { // this.stdOut.WriteLine(); // this.stdOut.WriteLine("PASSED"); retCode = SUCC_RET_CODE; } else { this.stdOut.WriteLine(); this.stdOut.WriteLine("FAILED!"); this.stdOut.WriteLine(); this.stdOut.WriteLine("[EXPECTED OUTPUT]"); this.stdOut.WriteLine(this.ExpectedOutput); this.stdOut.WriteLine("[DIFF RESULT]"); this.stdOut.WriteLine(diff); retCode = FAIL_RET_CODE; } return retCode; } // Returns actual test output. public string ActualOutput { get { return this.testOut.ToString(); } } // Returns actual test error. public string ActualError { get { return this.testError.ToString(); } } // Returns expected test output. public string ExpectedOutput { get { return this.expectedOut.ToString(); } } // Returns expected test error. public string ExpectedError { get { return this.expectedError.ToString(); } } } }
using System; using System.Data; //using System.Windows.Forms; using System.Text; using System.ComponentModel; namespace Provider.VistaDB { /// <summary> /// VistaDBSQL class for managing V-SQL query statements. /// </summary> internal abstract class VistaDBSQLConnection: IDisposable { protected string dataSource; protected string database; protected CypherType cypher; protected string password; protected bool exclusive; protected bool readOnly; protected bool opened; protected VistaDBSQLQuery[] queries; protected int cultureID; protected int clusterSize; protected bool caseSensitivity; protected string databaseDescription; protected object syncRoot = new object(); /// <summary> /// Constructor. /// </summary> public VistaDBSQLConnection() { this.dataSource = ""; this.database = ""; this.cypher = CypherType.None; this.password = ""; this.exclusive = false; this.readOnly = false; this.opened = false; this.queries = new VistaDBSQLQuery[0]; this.cultureID = 0; this.clusterSize = 0; this.caseSensitivity = false; this.databaseDescription = ""; } public abstract void Dispose(); /// <summary> /// Open a database connection to a VistaDB database. /// </summary> /// <returns></returns> public abstract void OpenDatabaseConnection(); /// <summary> /// Close an active database connection. /// </summary> public virtual void CloseDatabaseConnection() { lock(this.syncRoot) { for(int i = 0; i < this.queries.Length; i++) { this.queries[i].Close(); this.queries[i].FreeQuery(); } } } protected abstract VistaDBSQLQuery CreateSQLQuery(); /// <summary> /// Create new query for this connection. /// </summary> /// <returns></returns> public VistaDBSQLQuery NewSQLQuery() { VistaDBSQLQuery query; VistaDBSQLQuery[] newQueries; query = CreateSQLQuery(); lock(this.syncRoot) { newQueries = new VistaDBSQLQuery[queries.Length + 1]; for(int i = 0; i < queries.Length; i++ ) { newQueries[i] = this.queries[i]; } this.queries = newQueries; this.queries[queries.GetUpperBound(0)] = query; } return query; } public bool DropQuery(VistaDBSQLQuery query) { int indexQuery = -1; VistaDBSQLQuery[] newQueries; lock(this.syncRoot) { for(int i = 0; i < queries.Length; i++) { if( this.queries[i] == query ) { indexQuery = i; break; } } if(indexQuery < 0) return false; this.queries[indexQuery].Close(); this.queries[indexQuery].FreeQuery(); newQueries = new VistaDBSQLQuery[this.queries.Length - 1]; for(int i = 0; i < newQueries.Length; i++) { if( i < indexQuery ) newQueries[i] = this.queries[i]; else newQueries[i] = this.queries[i + 1]; } this.queries = newQueries; } return true; } /// <summary> /// Begin a transaction. Transactions may be nested. /// </summary> public abstract bool BeginTransaction(); /// <summary> /// Commit an active transaction. Transactions may be nested. /// </summary> public abstract bool CommitTransaction(); /// <summary> /// Rollback the active transaction. Transactions may be nested. /// </summary> public abstract void RollbackTransaction(); /// <summary> /// Gets or sets the data source. /// </summary> public virtual string DataSource { get { return this.dataSource; } set { this.dataSource = value; } } /// <summary> /// Gets or sets the database name /// </summary> public string Database { get { return this.database; } set { this.database = value; } } /// <summary> /// Gets or sets the database password. /// </summary> public string Password { get { return this.password; } set { this.password = value; } } /// <summary> /// Gets or sets the database encryption type, or Cypher type. /// </summary> public CypherType Cypher { get { return this.cypher; } set { this.cypher = value; } } /// <summary> /// Gets or sets if a database is to be opened in exclusive mode. Required for altering the database schema. /// </summary> public bool Exclusive { get { return this.exclusive; } set { this.exclusive = value; } } /// <summary> /// Gets or sets if a database is to be opened in readonly mode. /// </summary> public bool ReadOnly { get { return this.readOnly; } set { this.readOnly = value; } } public int CultureID { get { return this.cultureID; } } public int ClusterSize { get { return this.clusterSize; } } public bool CaseSensitivity { get { return this.caseSensitivity; } } public string DatabaseDescription { get { return this.databaseDescription; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using ServiceStack.Text.Common; namespace ServiceStack.Text { internal class CsvDictionaryWriter { public static void WriteRow(TextWriter writer, IEnumerable<string> row) { if (writer == null) return; //AOT var ranOnce = false; foreach (var field in row) { CsvWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); writer.Write(field.ToCsvField()); } writer.Write(CsvConfig.RowSeparatorString); } public static void WriteObjectRow(TextWriter writer, IEnumerable<object> row) { if (writer == null) return; //AOT var ranOnce = false; foreach (var field in row) { CsvWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); writer.Write(field.ToCsvField()); } writer.Write(CsvConfig.RowSeparatorString); } public static void Write(TextWriter writer, IEnumerable<KeyValuePair<string, object>> records) { if (records == null) return; //AOT var requireHeaders = !CsvConfig<IEnumerable<KeyValuePair<string, object>>>.OmitHeaders; if (requireHeaders) { var keys = records.Select(x => x.Key); WriteRow(writer, keys); } var values = records.Select(x => x.Value); WriteObjectRow(writer, values); } public static void Write(TextWriter writer, IEnumerable<KeyValuePair<string, string>> records) { if (records == null) return; //AOT var requireHeaders = !CsvConfig<IEnumerable<KeyValuePair<string, string>>>.OmitHeaders; if (requireHeaders) { var keys = records.Select(x => x.Key); WriteRow(writer, keys); } var values = records.Select(x => x.Value); WriteObjectRow(writer, values); } public static void Write(TextWriter writer, IEnumerable<IDictionary<string, object>> records) { if (records == null) return; //AOT var requireHeaders = !CsvConfig<Dictionary<string, object>>.OmitHeaders; foreach (var record in records) { if (requireHeaders) { if (record != null) WriteRow(writer, record.Keys); requireHeaders = false; } if (record != null) WriteObjectRow(writer, record.Values); } } public static void Write(TextWriter writer, IEnumerable<IDictionary<string, string>> records) { if (records == null) return; //AOT var allKeys = new HashSet<string>(); var cachedRecords = new List<IDictionary<string, string>>(); foreach (var record in records) { foreach (var key in record.Keys) { if (!allKeys.Contains(key)) { allKeys.Add(key); } } cachedRecords.Add(record); } var headers = allKeys.OrderBy(key => key).ToList(); if (!CsvConfig<Dictionary<string, string>>.OmitHeaders) { WriteRow(writer, headers); } foreach (var cachedRecord in cachedRecords) { var fullRecord = headers.ConvertAll(header => cachedRecord.ContainsKey(header) ? cachedRecord[header] : null); WriteRow(writer, fullRecord); } } } public static class CsvWriter { public static bool HasAnyEscapeChars(string value) { return !string.IsNullOrEmpty(value) && (CsvConfig.EscapeStrings.Any(value.Contains) || value[0] == JsWriter.ListStartChar || value[0] == JsWriter.MapStartChar); } internal static void WriteItemSeperatorIfRanOnce(TextWriter writer, ref bool ranOnce) { if (ranOnce) writer.Write(CsvConfig.ItemSeperatorString); else ranOnce = true; } } public class CsvWriter<T> { public const char DelimiterChar = ','; public static List<string> Headers { get; set; } internal static List<GetMemberDelegate<T>> PropertyGetters; private static readonly WriteObjectDelegate OptimizedWriter; static CsvWriter() { if (typeof(T) == typeof(string)) { OptimizedWriter = (w, o) => WriteRow(w, (IEnumerable<string>)o); return; } Reset(); } internal static void Reset() { Headers = new List<string>(); PropertyGetters = new List<GetMemberDelegate<T>>(); foreach (var propertyInfo in TypeConfig<T>.Properties) { if (!propertyInfo.CanRead || propertyInfo.GetGetMethod(nonPublic:true) == null) continue; if (!TypeSerializer.CanCreateFromString(propertyInfo.PropertyType)) continue; PropertyGetters.Add(propertyInfo.CreateGetter<T>()); var propertyName = propertyInfo.Name; var dcsDataMemberName = propertyInfo.GetDataMemberName(); if (dcsDataMemberName != null) propertyName = dcsDataMemberName; Headers.Add(propertyName); } } internal static void ConfigureCustomHeaders(Dictionary<string, string> customHeadersMap) { Reset(); for (var i = Headers.Count - 1; i >= 0; i--) { var oldHeader = Headers[i]; if (!customHeadersMap.TryGetValue(oldHeader, out var newHeaderValue)) { Headers.RemoveAt(i); PropertyGetters.RemoveAt(i); } else { Headers[i] = newHeaderValue.EncodeJsv(); } } } private static List<string> GetSingleRow(IEnumerable<T> records, Type recordType) { var row = new List<string>(); foreach (var value in records) { var strValue = recordType == typeof(string) ? value as string : TypeSerializer.SerializeToString(value); row.Add(strValue); } return row; } public static List<List<string>> GetRows(IEnumerable<T> records) { var rows = new List<List<string>>(); if (records == null) return rows; if (typeof(T).IsValueType || typeof(T) == typeof(string)) { rows.Add(GetSingleRow(records, typeof(T))); return rows; } foreach (var record in records) { var row = new List<string>(); foreach (var propertyGetter in PropertyGetters) { var value = propertyGetter(record) ?? ""; var valueStr = value as string; var strValue = valueStr ?? TypeSerializer.SerializeToString(value); row.Add(strValue); } rows.Add(row); } return rows; } public static void WriteObject(TextWriter writer, object records) { if (writer == null) return; //AOT Write(writer, (IEnumerable<T>)records); } public static void WriteObjectRow(TextWriter writer, object record) { if (writer == null) return; //AOT WriteRow(writer, (T)record); } public static void Write(TextWriter writer, IEnumerable<T> records) { if (writer == null) return; //AOT if (typeof(T) == typeof(Dictionary<string, string>) || typeof(T) == typeof(IDictionary<string, string>)) { CsvDictionaryWriter.Write(writer, (IEnumerable<IDictionary<string, string>>)records); return; } if (typeof(T).IsAssignableFrom(typeof(Dictionary<string, object>))) //also does `object` { var dynamicList = records.Select(x => x.ToObjectDictionary()).ToList(); CsvDictionaryWriter.Write(writer, dynamicList); return; } if (OptimizedWriter != null) { OptimizedWriter(writer, records); return; } if (!CsvConfig<T>.OmitHeaders && Headers.Count > 0) { var ranOnce = false; foreach (var header in Headers) { CsvWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); writer.Write(header); } writer.Write(CsvConfig.RowSeparatorString); } if (records == null) return; if (typeof(T).IsValueType || typeof(T) == typeof(string)) { var singleRow = GetSingleRow(records, typeof(T)); WriteRow(writer, singleRow); return; } var row = new string[Headers.Count]; foreach (var record in records) { for (var i = 0; i < PropertyGetters.Count; i++) { var propertyGetter = PropertyGetters[i]; var value = propertyGetter(record) ?? ""; var strValue = value is string ? (string)value : TypeSerializer.SerializeToString(value).StripQuotes(); row[i] = strValue; } WriteRow(writer, row); } } public static void WriteRow(TextWriter writer, T row) { if (writer == null) return; //AOT if (row is IEnumerable<KeyValuePair<string, object>> kvps) { CsvDictionaryWriter.Write(writer, kvps); } else if (row is IEnumerable<KeyValuePair<string, string>> kvpStrings) { CsvDictionaryWriter.Write(writer, kvpStrings); } else { Write(writer, new[] { row }); } } public static void WriteRow(TextWriter writer, IEnumerable<string> row) { if (writer == null) return; //AOT var ranOnce = false; foreach (var field in row) { CsvWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); writer.Write(field.ToCsvField()); } writer.Write(CsvConfig.RowSeparatorString); } public static void Write(TextWriter writer, IEnumerable<List<string>> rows) { if (writer == null) return; //AOT if (Headers.Count > 0) { var ranOnce = false; foreach (var header in Headers) { CsvWriter.WriteItemSeperatorIfRanOnce(writer, ref ranOnce); writer.Write(header); } writer.Write(CsvConfig.RowSeparatorString); } foreach (var row in rows) { WriteRow(writer, row); } } } }
namespace System.Windows.Forms.DataVisualization.Charting.Utilities { using System.Drawing; /// <summary> /// Helper class that creates a histogram chart. Histogram is a data /// distribution chart which shows how many values, from the data series, /// are inside each segment interval. /// /// You can define how many intervals you want to have using the SegmentIntervalNumber /// field or the exact length of the interval using the SegmentIntervalWidth /// field. Actual segment interval number can be slightly different due /// to the automatic interval rounding. /// </summary> class HistogramChartHelper { #region Fields /// <summary> /// Number of class intervals the data range is devided in. /// This property only has affect when "SegmentIntervalWidth" is /// set to double.NaN. /// </summary> public int SegmentIntervalNumber = 20; /// <summary> /// Histogram class interval width. Setting this value to "double.NaN" /// will result in automatic width calculation based on the data range /// and number of required interval specified in "SegmentIntervalNumber". /// </summary> public double SegmentIntervalWidth = double.NaN; /// <summary> /// Indicates that percent frequency should be shown on the right axis /// </summary> public bool ShowPercentOnSecondaryYAxis = true; #endregion // Fields #region Methods /// <summary> /// Creates a histogram chart. /// </summary> /// <param name="chartControl">Chart control reference.</param> /// <param name="dataSeriesName">Name of the series which stores the original data.</param> /// <param name="histogramSeriesName">Name of the histogram series.</param> public void CreateHistogram( Chart chartControl, string dataSeriesName, string histogramSeriesName) { // Validate input if(chartControl == null) { throw(new ArgumentNullException("chartControl")); } if(chartControl.Series.IndexOf(dataSeriesName) < 0) { throw(new ArgumentException("Series with name'" + dataSeriesName + "' was not found.", "dataSeriesName")); } // Make data series invisible chartControl.Series[dataSeriesName].Enabled = false; // Check if histogram series exsists Series histogramSeries = null; if(chartControl.Series.IndexOf(histogramSeriesName) < 0) { // Add new series histogramSeries = chartControl.Series.Add(histogramSeriesName); // Set new series chart type and other attributes histogramSeries.ChartType = SeriesChartType.Column; histogramSeries.BorderColor = Color.Black; histogramSeries.BorderWidth = 1; histogramSeries.BorderDashStyle = ChartDashStyle.Solid; } else { histogramSeries = chartControl.Series[histogramSeriesName]; histogramSeries.Points.Clear(); } // Get data series minimum and maximum values double minValue = double.MaxValue; double maxValue = double.MinValue; int pointCount = 0; foreach(DataPoint dataPoint in chartControl.Series[dataSeriesName].Points) { // Process only non-empty data points if(!dataPoint.IsEmpty) { if(dataPoint.YValues[0] > maxValue) { maxValue = dataPoint.YValues[0]; } if(dataPoint.YValues[0] < minValue) { minValue = dataPoint.YValues[0]; } ++pointCount; } } // Calculate interval width if it's not set if(double.IsNaN(this.SegmentIntervalWidth)) { this.SegmentIntervalWidth = (maxValue - minValue) / SegmentIntervalNumber; this.SegmentIntervalWidth = RoundInterval(this.SegmentIntervalWidth); } // Round minimum and maximum values minValue = Math.Floor( minValue / this.SegmentIntervalWidth ) * this.SegmentIntervalWidth; maxValue = Math.Ceiling( maxValue / this.SegmentIntervalWidth ) * this.SegmentIntervalWidth; // Create histogram series points double currentPosition = minValue; for(currentPosition = minValue; currentPosition <= maxValue; currentPosition+=this.SegmentIntervalWidth) { // Count all points from data series that are in current interval int count = 0; foreach(DataPoint dataPoint in chartControl.Series[dataSeriesName].Points) { if(!dataPoint.IsEmpty) { double endPosition = currentPosition + this.SegmentIntervalWidth; if(dataPoint.YValues[0] >= currentPosition && dataPoint.YValues[0] < endPosition) { ++count; } // Last segment includes point values on both segment boundaries else if(endPosition >= maxValue) { if(dataPoint.YValues[0] >= currentPosition && dataPoint.YValues[0] <= endPosition) { ++count; } } } } // Add data point into the histogram series histogramSeries.Points.AddXY(currentPosition + this.SegmentIntervalWidth / 2.0, count); } // Adjust series attributes histogramSeries["PointWidth"] = "1"; // Adjust chart area ChartArea chartArea = chartControl.ChartAreas[histogramSeries.ChartArea]; chartArea.AxisY.Title = "Frequency"; chartArea.AxisX.Minimum = minValue; chartArea.AxisX.Maximum = maxValue; // Set axis interval based on the histogram class interval // and do not allow more than 10 labels on the axis. double axisInterval = this.SegmentIntervalWidth; while( (maxValue - minValue) / axisInterval > 10.0) { axisInterval *= 2.0; } chartArea.AxisX.Interval = axisInterval; // Set chart area secondary Y axis chartArea.AxisY2.Enabled = AxisEnabled.Auto; if(this.ShowPercentOnSecondaryYAxis) { chartArea.RecalculateAxesScale(); chartArea.AxisY2.Enabled = AxisEnabled.True; chartArea.AxisY2.LabelStyle.Format = "P0"; chartArea.AxisY2.MajorGrid.Enabled = false; chartArea.AxisY2.Title = "Percent of Total"; chartArea.AxisY2.Minimum = 0; chartArea.AxisY2.Maximum = chartArea.AxisY.Maximum / ( pointCount / 100.0 ); double minStep = (chartArea.AxisY2.Maximum > 20.0) ? 5.0 : 1.0; chartArea.AxisY2.Interval = Math.Ceiling( (chartArea.AxisY2.Maximum / 5.0 / minStep) ) * minStep; } } /// <summary> /// Helper method which rounds specified axsi interval. /// </summary> /// <param name="interval">Calculated axis interval.</param> /// <returns>Rounded axis interval.</returns> internal double RoundInterval( double interval ) { // If the interval is zero return error if( interval == 0.0 ) { throw( new ArgumentOutOfRangeException("interval", "Interval can not be zero.")); } // If the real interval is > 1.0 double step = -1; double tempValue = interval; while( tempValue > 1.0 ) { step ++; tempValue = tempValue / 10.0; if( step > 1000 ) { throw( new InvalidOperationException( "Auto interval error due to invalid point values or axis minimum/maximum." ) ); } } // If the real interval is < 1.0 tempValue = interval; if( tempValue < 1.0 ) { step = 0; } while( tempValue < 1.0 ) { step --; tempValue = tempValue * 10.0; if( step < -1000 ) { throw( new InvalidOperationException( "Auto interval error due to invalid point values or axis minimum/maximum." ) ); } } double tempDiff = interval / Math.Pow( 10.0, step ); if( tempDiff < 3.0 ) { tempDiff = 2.0; } else if( tempDiff < 7.0 ) { tempDiff = 5.0; } else { tempDiff = 10.0; } // Make a correction of the real interval return tempDiff * Math.Pow( 10.0, step ); } #endregion // Methods } }
using System; using System.Collections.Generic; using KSP.Localization; using UnityEngine; namespace Starstrider42.CustomAsteroids { /// <summary> /// Singleton class storing raw asteroid data. /// </summary> /// <remarks>TODO: Clean up this class.</remarks> internal class PopulationLoader { /// <summary>The set of loaded AsteroidSet objects.</summary> readonly List<AsteroidSet> asteroidPops; /// <summary> /// Creates an empty solar system. Does not throw exceptions. /// </summary> PopulationLoader () { asteroidPops = new List<AsteroidSet> (); } /// <summary> /// Factory method obtaining Custom Asteroids settings from KSP config state. /// </summary> /// /// <returns>A newly constructed PopulationLoader object containing a full list /// of all valid asteroid groups in asteroid config files.</returns> /// /// <exception cref="TypeInitializationException">Thrown if the PopulationLoader /// object could not be constructed. The program is in a consistent state in the event of /// an exception.</exception> internal static PopulationLoader load () { try { // Start with an empty population list PopulationLoader allPops = new PopulationLoader (); // Search for populations in all config files UrlDir.UrlConfig [] configList = GameDatabase.Instance.GetConfigs ("AsteroidSets"); foreach (UrlDir.UrlConfig curSet in configList) { foreach (ConfigNode curNode in curSet.config.nodes) { #if DEBUG Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogConfig", curNode)); #endif try { AsteroidSet pop = null; switch (curNode.name) { case "ASTEROIDGROUP": pop = new Population (); break; case "INTERCEPT": pop = new Flyby (); break; case "DEFAULT": #pragma warning disable 0618 // DefaultAsteroids is deprecated pop = new DefaultAsteroids (); #pragma warning restore 0618 break; // silently ignore any other nodes present } if (pop != null) { ConfigNode.LoadObjectFromConfig (pop, curNode); allPops.asteroidPops.Add (pop); } } catch (Exception e) { var nodeName = curNode.GetValue ("name"); var error = Localizer.Format ( "#autoLOC_CustomAsteroids_ErrorLoadGroup", nodeName); Debug.LogError ($"[CustomAsteroids]: " + error); Debug.LogException (e); Util.errorToPlayer (e, error); } // Attempt to parse remaining populations } } #if DEBUG foreach (AsteroidSet x in allPops.asteroidPops) { Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogLoadGroup", x)); } #endif if (allPops.asteroidPops.Count == 0) { Debug.LogWarning ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_ErrorNoConfig1")); ScreenMessages.PostScreenMessage ( Localizer.Format ("#autoLOC_CustomAsteroids_ErrorNoConfig1") + "\n" + Localizer.Format ("#autoLOC_CustomAsteroids_ErrorNoConfig2"), 10.0f, ScreenMessageStyle.UPPER_CENTER); } return allPops; } catch (Exception e) { throw new TypeInitializationException ( "Starstrider42.CustomAsteroids.PopulationLoader", e); } } /// <summary> /// Randomly selects an asteroid set. The selection is weighted by the spawn rate of /// each population; a set with a rate of 2.0 is twice as likely to be chosen as one /// with a rate of 1.0. /// </summary> /// <returns>A reference to the selected asteroid set. Shall not be null.</returns> /// /// <exception cref="InvalidOperationException">Thrown if there are no sets from /// which to choose, or if all spawn rates are zero, or if any rate is negative</exception> internal AsteroidSet drawAsteroidSet () { try { var bins = new List<Tuple<AsteroidSet, double>> (); foreach (AsteroidSet x in asteroidPops) { bins.Add (Tuple.Create (x, x.getSpawnRate ())); } return RandomDist.weightedSample (bins); } catch (ArgumentException e) { throw new InvalidOperationException ( Localizer.Format ("#autoLOC_CustomAsteroids_ErrorNoGroup"), e); } } /// <summary> /// Returns the total spawn rate of all asteroid sets. Does not throw exceptions. /// </summary> /// <returns>The sum of all spawn rates for all sets, in asteroids per day.</returns> /// <remarks>The rate can be affected by populations' situational modifiers, and may be zero.</remarks> internal double getTotalRate () { double total = 0.0; foreach (AsteroidSet x in asteroidPops) { total += x.getSpawnRate (); } return total; } /// <summary> /// Debug function for traversing node tree. The indicated node and all nodes beneath it /// are printed, in depth-first order. /// </summary> /// <param name="node">The top-level node of the tree to be printed.</param> static void printNode (ConfigNode node) { Debug.Log ("printNode: NODE = " + node.name); foreach (ConfigNode.Value x in node.values) { Debug.Log ("printNode: " + x.name + " -> " + x.value); } foreach (ConfigNode x in node.nodes) { printNode (x); } } } /// <summary> /// Contains settings for asteroids that aren't affected by Custom Asteroids. /// </summary> /// <remarks>To avoid breaking the persistence code, DefaultAsteroids may not have /// subclasses.</remarks> /// /// @deprecated Deprecated in favor of <see cref="Flyby"/>; to be removed in version 2.0.0. [Obsolete ("DefaultAsteroids will be removed in 2.0.0; use Flyby instead.")] internal sealed class DefaultAsteroids : AsteroidSet { /// <summary>The name of the group.</summary> [Persistent] string name; /// <summary>The name of asteroids with unmodified orbits.</summary> [Persistent] string title; /// <summary>The rate, in asteroids per day, at which asteroids appear on stock /// orbits.</summary> [Persistent] double spawnRate; /// <summary>Relative ocurrence rates of asteroid classes.</summary> [Persistent (name = "asteroidTypes", collectionIndex = "key")] readonly Proportions<string> classRatios; /// <summary> /// Sets default settings for asteroids with unmodified orbits. The object is initialized /// to a state in which it will not be expected to generate orbits. Does not throw /// exceptions. /// </summary> internal DefaultAsteroids () { name = "default"; title = Localizer.GetStringByTag ("#autoLOC_6001923"); spawnRate = 0.0; classRatios = new Proportions<string> (new [] { "1.0 PotatoRoid" }); } public string drawAsteroidType () { try { return AsteroidManager.drawAsteroidType (classRatios); } catch (InvalidOperationException e) { Util.errorToPlayer (e, Localizer.Format ( "#autoLOC_CustomAsteroids_ErrorNoClass", name)); Debug.LogException (e); return "PotatoRoid"; } } /// <summary> /// Returns the sizeCurve used by the stock spawner as of KSP 1.0.5. This corresponds to /// the following size distribution: 12% class A, 13% class B, 50% class C, 13% class D, /// and 12% class E. /// </summary> private static readonly FloatCurve stockSizeCurve = new FloatCurve (new [] { new Keyframe(0.0f, 0.0f, 1.5f, 1.5f), new Keyframe(0.3f, 0.45f, 0.875f, 0.875f), new Keyframe(0.7f, 0.55f, 0.875f, 0.875f), new Keyframe(1.0f, 1.0f, 1.5f, 1.5f) }); public UntrackedObjectClass drawAsteroidSize () { // Asteroids appear to be hardcoded to be from size A to E, even though there are more classes now return (UntrackedObjectClass)(int) (stockSizeCurve.Evaluate ((float) RandomDist.drawUniform (0.0, 1.0)) * 5); } /// <summary>The length of an Earth day, in seconds.</summary> private const double SECONDS_PER_EARTH_DAY = 24.0 * 3600.0; public Tuple<double, double> drawTrackingTime () { Tuple<float, float> trackTimes = AsteroidManager.getOptions ().getUntrackedTimes (); double lifetime = RandomDist.drawUniform (trackTimes.Item1, trackTimes.Item2) * SECONDS_PER_EARTH_DAY; double maxLifetime = trackTimes.Item2 * SECONDS_PER_EARTH_DAY; return Tuple.Create (lifetime, maxLifetime); } public double getSpawnRate () { return spawnRate; } public string getName () { return name; } public string getAsteroidName () { return title; } public string getCometOrbit () { return "intermediate"; } public bool getUseCometName () { return true; } /// <summary> /// Returns a <see cref="string"/> that represents the current object. /// </summary> /// <returns>A simple string identifying the object.</returns> /// /// <seealso cref="object.ToString()"/> public override string ToString () { return getName (); } /// <summary> /// Generates a random orbit in as similar a manner to stock as possible. /// </summary> /// <returns>The orbit of a randomly selected member of the population.</returns> /// /// <exception cref="InvalidOperationException">Thrown if cannot produce stockalike /// orbits. The program will be in a consistent state in the event of an exception.</exception> public Orbit drawOrbit () { CelestialBody kerbin = FlightGlobals.Bodies.Find (body => body.isHomeWorld); CelestialBody dres = FlightGlobals.Bodies.Find (body => body.name.Equals ("Dres")); if (dres != null && reachedBody (dres) && RandomDist.drawUniform (0.0, 1.0) < 0.2) { // Drestroids double a = RandomDist.drawLogUniform (0.55, 0.65) * dres.sphereOfInfluence; double e = RandomDist.drawRayleigh (0.005); double i = RandomDist.drawRayleigh (0.005); // lAn takes care of negative inclinations double lAn = RandomDist.drawAngle (); double aPe = RandomDist.drawAngle (); double mEp = Math.PI / 180.0 * RandomDist.drawAngle (); double epoch = Planetarium.GetUniversalTime (); Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogOrbit", a, e, i, aPe, lAn, mEp, epoch)); return new Orbit (i, e, a, lAn, aPe, mEp, epoch, dres); } if (kerbin != null) { // Kerbin interceptors double delay = RandomDist.drawUniform (12.5, 55.0); Debug.Log ("[CustomAsteroids]: " + Localizer.Format ("#autoLOC_CustomAsteroids_LogDefault", delay)); return Orbit.CreateRandomOrbitFlyBy (kerbin, delay); } throw new InvalidOperationException ( Localizer.Format ("#autoLOC_CustomAsteroids_ErrorDefaultNoKerbin")); } /// <summary> /// Determines whether a body was already visited. /// </summary> /// <remarks>Borrowed from Kopernicus.</remarks> /// /// <param name="body">The celestial body whose exploration status needs to be tested.</param> /// <returns><c>true</c>, if <c>body</c> was reached, <c>false</c> otherwise.</returns> static bool reachedBody (CelestialBody body) { KSPAchievements.CelestialBodySubtree bodyTree = ProgressTracking.Instance.GetBodyTree (body.name); return bodyTree != null && bodyTree.IsReached; } } }