context
stringlengths
2.52k
185k
gt
stringclasses
1 value
namespace Microsoft.WindowsAzure.Management.HDInsight.Framework.Rest { using System; using System.Collections.Generic; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using System.Linq; using System.Reflection; using Microsoft.HDInsight.Net.Http.Formatting; /// <summary> /// An abstract class to inherit from to write a rest proxy against a service interface. /// internal class DeploymentServiceProxy : RestProxy&lt;IDeploymentService &gt;. /// </summary> /// <typeparam name="TServiceInterface">The type of the service interface for which you need the proxy for.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1012:AbstractTypesShouldNotHaveConstructors", Justification = "This is so that the concrete types can have them.")] public abstract class HttpRestClient<TServiceInterface> { private readonly Uri _baseServiceUri; private readonly IDictionary<string, HttpRequestParameters> _methodToRequestParametersMap = new Dictionary<string, HttpRequestParameters>(); private readonly HttpRestClientConfiguration _configuration; /// <summary> /// Gets the base service URI. /// </summary> /// <value>The base service URI.</value> public Uri BaseServiceUri { get { return this._baseServiceUri; } } /// <summary> /// Gets the configuration. /// </summary> /// <value> /// The configuration. /// </value> public HttpRestClientConfiguration Configuration { get { return this._configuration; } } private static string GetUniqueInterfaceMethodSignature(MethodInfo info) { var allNames = new List<string>(); allNames.Add(info.Name); allNames.AddRange(info.GetParameters().Select(pInfo => pInfo.ParameterType.FullName)); return string.Join("_", allNames); } private static IDictionary<string, HttpRequestParameters> BuildInterfaceMethodToParametersDictionary() { IEnumerable<MethodInfo> interfaceMethods = typeof(TServiceInterface).GetMethods() .Where(method => HttpRestInterfaceValidator.ValidateInterfaceMethod(method)); Dictionary<string, HttpRequestParameters> dictionary = interfaceMethods.ToDictionary( GetUniqueInterfaceMethodSignature, HttpRequestParameters.FromMethodInfo); return dictionary; } /// <summary> /// Initializes a new instance of the <see cref="HttpRestClient{TServiceInterface}"/> class. /// </summary> /// <param name="baseUri">The base URI.</param> /// <param name="configuration">The configuration.</param> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1062:Validate arguments of public methods", Justification = "Validated", MessageId = "0")] public HttpRestClient(Uri baseUri, HttpRestClientConfiguration configuration) { Contract.Requires<ArgumentNullException>(baseUri != null); Contract.Requires<ArgumentNullException>(baseUri.IsAbsoluteUri); Contract.Requires<ArgumentException>(baseUri.Scheme.Equals(Uri.UriSchemeHttp) || baseUri.Scheme.Equals(Uri.UriSchemeHttps)); this._baseServiceUri = baseUri; this._methodToRequestParametersMap = BuildInterfaceMethodToParametersDictionary(); this._configuration = configuration; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "No need")] private HttpRequestMessage CreateHttpRequestMessage(HttpRequestParameters parameters, MethodInfo method, out CancellationToken cancellationToken, object[] methodArgumentsInOrder) { List<string> parameterNamesBoundToUri; var requestUri = parameters.BindUri(this._baseServiceUri, method, methodArgumentsInOrder, out parameterNamesBoundToUri, out cancellationToken); HttpRequestMessage requestMessage = new HttpRequestMessage(new HttpMethod(parameters.HttpMethod), requestUri); //The arguments when not used for uri binding either the request body or the cancellation token // the request body is serialized into the stream as the request body if (methodArgumentsInOrder.Length > parameterNamesBoundToUri.Count) { //This ordered as they appear in the method signature var parameterInfos = method.GetParameters(); for (int i = 0; i < parameterInfos.Length; i++) { var parameterName = parameterInfos[i].Name; if ( !parameterNamesBoundToUri.Any( paramName => paramName.Equals(parameterName, StringComparison.OrdinalIgnoreCase))) { if (parameterInfos[i].ParameterType != typeof(CancellationToken)) { //Pick the unbound argument for request stream data object dataToSerialize = methodArgumentsInOrder[i]; //serialize the data using the specified serializer into the request message requestMessage.Content = new ObjectContent(dataToSerialize.GetType(), dataToSerialize, parameters.RequestFormatter.RequestFormatter); } } } } foreach (var formatter in parameters.ResponseFormatter.ResponseFormatters) { foreach (var mediaType in formatter.SupportedMediaTypes) { requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType.MediaType)); } } return requestMessage; } /// <summary> /// Creates the HTTP client by chaining all the handlers found in the interface method attributes and the http /// client configuration. /// </summary> /// <param name="parameters">The parameters.</param> /// <returns>An instance of HttpClient.</returns> private HttpClient CreateHttpClient(HttpRequestParameters parameters) { HttpMessageHandler rootHandler = this.Configuration.RootHandler; if (parameters.CutomMessageProcessingHandlers.Any()) { IList<DelegatingHandler> handlers = parameters.CutomMessageProcessingHandlers.Select(c => c.CreateHandler()).ToList(); for (int i = 0; i < handlers.Count - 1; i++) { handlers[i].InnerHandler = handlers[i + 1]; } handlers.Last().InnerHandler = this.Configuration.RootHandler; rootHandler = handlers.First(); } else { rootHandler = this.Configuration.RootHandler; } return new HttpClient(rootHandler, false); } /// <summary> /// Creates the and invoke rest request for caller based of its interface implementation. /// </summary> /// <typeparam name="T">The return type.</typeparam> /// <param name="classMethod">The class verb.</param> /// <param name="methodArgumentsInOrder">The verb arguments in order.</param> /// <returns>A task.</returns> private async Task<T> InvokeHttpRestRequest<T>(MethodInfo classMethod, object[] methodArgumentsInOrder) { Contract.Requires<ArgumentNullException>(methodArgumentsInOrder != null); //Transform the reflected attributes from the method //Pull that information from the cache we created on construction var requestParametersFromMethod = this._methodToRequestParametersMap[GetUniqueInterfaceMethodSignature(classMethod)]; Type returnType = null; if (classMethod.ReturnType.IsGenericType && classMethod.ReturnType.BaseType == typeof(Task)) { returnType = classMethod.ReturnType.GetGenericArguments().Single(); } else if (classMethod.ReturnType == typeof(void) || classMethod.ReturnType == typeof(Task)) { returnType = typeof(void); } else { returnType = classMethod.ReturnType; } T retVal = default(T); for (int attempt = 1;; attempt++) { Exception lastException = null; TimeSpan delay = TimeSpan.MinValue; //Create the request message from the request parameters,i.e. set the headers and serialize the request CancellationToken cancellationToken; var requestMessage = this.CreateHttpRequestMessage(requestParametersFromMethod, classMethod, out cancellationToken, methodArgumentsInOrder); HttpClient client = this.CreateHttpClient(requestParametersFromMethod); client.Timeout = this.Configuration.HttpRequestTimeout; try { using (var resp = await client.SendAsync(requestMessage, cancellationToken)) { if (returnType != typeof(void)) { retVal = (T)await resp.Content.ReadAsAsync(returnType, requestParametersFromMethod.ResponseFormatter.ResponseFormatters); return retVal; } return default(T); } } catch (Exception e) { if (e is OperationCanceledException) { throw; } lastException = e; if (!this.Configuration.RetryPolicy.ShouldRetry(e, attempt, out delay)) { throw; } } if (lastException != null) { await Task.Delay(delay); } } } /// <summary> /// Creates and invokes the rest request for caller based of its interface definition. /// </summary> /// <param name="orderedArgumentsOfTheParentMethod">The ordered arguments of the parent verb.</param> /// <returns>A task.</returns> /// <remarks>Please be sure to dispose the HttpWebResponseObject after you are done with it.</remarks> protected Task<T> CreateAndInvokeRestRequestForParentMethodAsync<T>(params object[] orderedArgumentsOfTheParentMethod) { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); //Get parent from the stackframe MethodInfo classMethod = (MethodInfo)stackFrame.GetMethod(); return this.InvokeHttpRestRequest<T>(classMethod, orderedArgumentsOfTheParentMethod); } /// <summary> /// Creates and invokes the rest request for caller based of its interface definition. /// </summary> /// <param name="orderedArgumentsOfTheParentMethod">The ordered arguments of the parent verb.</param> /// <returns>A task.</returns> /// <remarks>Please be sure to dispose the HttpWebResponseObject after you are done with it.</remarks> protected Task CreateAndInvokeRestRequestForParentMethodAsync(params object[] orderedArgumentsOfTheParentMethod) { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); //Get parent from the stackframe MethodInfo classMethod = (MethodInfo)stackFrame.GetMethod(); return this.InvokeHttpRestRequest<object>(classMethod, orderedArgumentsOfTheParentMethod); } /// <summary> /// Creates and invokes the rest request for caller based of its interface definition. /// </summary> /// <param name="orderedArgumentsOfTheParentMethod">The ordered arguments of the parent verb.</param> /// <returns>A task.</returns> /// <remarks>Please be sure to dispose the HttpWebResponseObject after you are done with it.</remarks> protected object CreateAndInvokeRestRequestForParentMethod(params object[] orderedArgumentsOfTheParentMethod) { StackTrace stackTrace = new StackTrace(); StackFrame stackFrame = stackTrace.GetFrame(1); //Get parent from the stackframe MethodInfo classMethod = (MethodInfo)stackFrame.GetMethod(); return this.InvokeHttpRestRequest<object>(classMethod, orderedArgumentsOfTheParentMethod).GetAwaiter().GetResult(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Xml.Linq; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace System { public static partial class PlatformDetection { public static bool IsWindowsIoTCore => false; public static bool IsWindows => false; public static bool IsWindows7 => false; public static bool IsWindows8x => false; public static bool IsWindows10Version1607OrGreater => false; public static bool IsWindows10Version1703OrGreater => false; public static bool IsWindows10Version1709OrGreater => false; public static bool IsNotOneCoreUAP => true; public static bool IsInAppContainer => false; public static int WindowsVersion => -1; public static bool IsCentos6 => IsDistroAndVersion("centos", 6); public static bool IsOpenSUSE => IsDistroAndVersion("opensuse"); public static bool IsUbuntu => IsDistroAndVersion("ubuntu"); public static bool IsDebian => IsDistroAndVersion("debian"); public static bool IsDebian8 => IsDistroAndVersion("debian", 8); public static bool IsUbuntu1404 => IsDistroAndVersion("ubuntu", 14, 4); public static bool IsUbuntu1604 => IsDistroAndVersion("ubuntu", 16, 4); public static bool IsUbuntu1704 => IsDistroAndVersion("ubuntu", 17, 4); public static bool IsUbuntu1710 => IsDistroAndVersion("ubuntu", 17, 10); public static bool IsTizen => IsDistroAndVersion("tizen"); public static bool IsFedora => IsDistroAndVersion("fedora"); public static bool IsWindowsNanoServer => false; public static bool IsWindowsServerCore => false; public static bool IsWindowsAndElevated => false; // RedHat family covers RedHat and CentOS public static bool IsRedHatFamily => IsRedHatFamilyAndVersion(); public static bool IsNotRedHatFamily => !IsRedHatFamily; public static bool IsRedHatFamily6 => IsRedHatFamilyAndVersion(6); public static bool IsNotRedHatFamily6 => !IsRedHatFamily6; public static bool IsRedHatFamily7 => IsRedHatFamilyAndVersion(7); public static bool IsNotFedoraOrRedHatFamily => !IsFedora && !IsRedHatFamily; public static Version OSXVersion { get; } = ToVersion(Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.OperatingSystemVersion); public static Version OpenSslVersion => RuntimeInformation.IsOSPlatform(OSPlatform.Linux) ? Interop.OpenSsl.OpenSslVersion : throw new PlatformNotSupportedException(); public static string GetDistroVersionString() { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { return "OSX Version=" + s_osxProductVersion.ToString(); } DistroInfo v = GetDistroInfo(); return "Distro=" + v.Id + " VersionId=" + v.VersionId; } private static readonly Version s_osxProductVersion = GetOSXProductVersion(); public static bool IsMacOsHighSierraOrHigher { get; } = IsOSX && (s_osxProductVersion.Major > 10 || (s_osxProductVersion.Major == 10 && s_osxProductVersion.Minor >= 13)); private static readonly Version s_icuVersion = GetICUVersion(); public static Version ICUVersion => s_icuVersion; private static Version GetICUVersion() { int ver = GlobalizationNative_GetICUVersion(); return new Version( ver & 0xFF, (ver >> 8) & 0xFF, (ver >> 16) & 0xFF, ver >> 24); } static Version ToVersion(string versionString) { if (versionString.IndexOf('.') != -1) return new Version(versionString); // minor version is required by Version // let's default it to 0 return new Version(int.Parse(versionString), 0); } private static DistroInfo GetDistroInfo() => new DistroInfo() { Id = Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.OperatingSystem, VersionId = ToVersion(Microsoft.DotNet.PlatformAbstractions.RuntimeEnvironment.OperatingSystemVersion) }; private static bool IsRedHatFamilyAndVersion(int major = -1, int minor = -1, int build = -1, int revision = -1) { return IsDistroAndVersion((distro) => distro == "rhel" || distro == "centos", major, minor, build, revision); } /// <summary> /// Get whether the OS platform matches the given Linux distro and optional version. /// </summary> /// <param name="distroId">The distribution id.</param> /// <param name="versionId">The distro version. If omitted, compares the distro only.</param> /// <returns>Whether the OS platform matches the given Linux distro and optional version.</returns> private static bool IsDistroAndVersion(string distroId, int major = -1, int minor = -1, int build = -1, int revision = -1) { return IsDistroAndVersion((distro) => distro == distroId, major, minor, build, revision); } private static bool IsDistroAndVersion(Predicate<string> distroPredicate, int major = -1, int minor = -1, int build = -1, int revision = -1) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { DistroInfo v = GetDistroInfo(); if (distroPredicate(v.Id) && VersionEquivalentWith(major, minor, build, revision, v.VersionId)) { return true; } } return false; } private static bool VersionEquivalentWith(int major, int minor, int build, int revision, Version actualVersionId) { return (major == -1 || major == actualVersionId.Major) && (minor == -1 || minor == actualVersionId.Minor) && (build == -1 || build == actualVersionId.Build) && (revision == -1 || revision == actualVersionId.Revision); } private static Version GetOSXProductVersion() { try { if (IsOSX) { // <plist version="1.0"> // <dict> // <key>ProductBuildVersion</key> // <string>17A330h</string> // <key>ProductCopyright</key> // <string>1983-2017 Apple Inc.</string> // <key>ProductName</key> // <string>Mac OS X</string> // <key>ProductUserVisibleVersion</key> // <string>10.13</string> // <key>ProductVersion</key> // <string>10.13</string> // </dict> // </plist> XElement dict = XDocument.Load("/System/Library/CoreServices/SystemVersion.plist").Root.Element("dict"); if (dict != null) { foreach (XElement key in dict.Elements("key")) { if ("ProductVersion".Equals(key.Value)) { XElement stringElement = key.NextNode as XElement; if (stringElement != null && stringElement.Name.LocalName.Equals("string")) { string versionString = stringElement.Value; if (versionString != null) { return Version.Parse(versionString); } } } } } } } catch { } // In case of exception or couldn't get the version return new Version(0, 0, 0); } [DllImport("libc", SetLastError = true)] private static extern int sysctlbyname(string ctlName, byte[] oldp, ref IntPtr oldpLen, byte[] newp, IntPtr newpLen); [DllImport("libc", SetLastError = true)] internal static extern unsafe uint geteuid(); [DllImport("System.Globalization.Native", SetLastError = true)] private static extern int GlobalizationNative_GetICUVersion(); public static bool IsSuperUser => geteuid() == 0; private struct DistroInfo { public string Id { get; set; } public Version VersionId { get; set; } } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// Pay Methods Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class PEPMDataSet : EduHubDataSet<PEPM> { /// <inheritdoc /> public override string Name { get { return "PEPM"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal PEPMDataSet(EduHubContext Context) : base(Context) { Index_BSB = new Lazy<NullDictionary<string, IReadOnlyList<PEPM>>>(() => this.ToGroupedNullDictionary(i => i.BSB)); Index_CODE = new Lazy<Dictionary<string, IReadOnlyList<PEPM>>>(() => this.ToGroupedDictionary(i => i.CODE)); Index_TID = new Lazy<Dictionary<int, PEPM>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="PEPM" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="PEPM" /> fields for each CSV column header</returns> internal override Action<PEPM, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<PEPM, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "CODE": mapper[i] = (e, v) => e.CODE = v; break; case "NAME": mapper[i] = (e, v) => e.NAME = v; break; case "PAYMODE": mapper[i] = (e, v) => e.PAYMODE = v; break; case "REFERENCE_NO": mapper[i] = (e, v) => e.REFERENCE_NO = v; break; case "CHQ_NO": mapper[i] = (e, v) => e.CHQ_NO = v; break; case "DAMOUNT": mapper[i] = (e, v) => e.DAMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "BANK": mapper[i] = (e, v) => e.BANK = v; break; case "BSB": mapper[i] = (e, v) => e.BSB = v; break; case "ACCOUNT_NO": mapper[i] = (e, v) => e.ACCOUNT_NO = v; break; case "AMOUNT": mapper[i] = (e, v) => e.AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "FLAG": mapper[i] = (e, v) => e.FLAG = v; break; case "TRBATCH": mapper[i] = (e, v) => e.TRBATCH = v == null ? (int?)null : int.Parse(v); break; case "EFT_CREATED": mapper[i] = (e, v) => e.EFT_CREATED = v; break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="PEPM" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="PEPM" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="PEPM" /> entities</param> /// <returns>A merged <see cref="IEnumerable{PEPM}"/> of entities</returns> internal override IEnumerable<PEPM> ApplyDeltaEntities(IEnumerable<PEPM> Entities, List<PEPM> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<NullDictionary<string, IReadOnlyList<PEPM>>> Index_BSB; private Lazy<Dictionary<string, IReadOnlyList<PEPM>>> Index_CODE; private Lazy<Dictionary<int, PEPM>> Index_TID; #endregion #region Index Methods /// <summary> /// Find PEPM by BSB field /// </summary> /// <param name="BSB">BSB value used to find PEPM</param> /// <returns>List of related PEPM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PEPM> FindByBSB(string BSB) { return Index_BSB.Value[BSB]; } /// <summary> /// Attempt to find PEPM by BSB field /// </summary> /// <param name="BSB">BSB value used to find PEPM</param> /// <param name="Value">List of related PEPM entities</param> /// <returns>True if the list of related PEPM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByBSB(string BSB, out IReadOnlyList<PEPM> Value) { return Index_BSB.Value.TryGetValue(BSB, out Value); } /// <summary> /// Attempt to find PEPM by BSB field /// </summary> /// <param name="BSB">BSB value used to find PEPM</param> /// <returns>List of related PEPM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PEPM> TryFindByBSB(string BSB) { IReadOnlyList<PEPM> value; if (Index_BSB.Value.TryGetValue(BSB, out value)) { return value; } else { return null; } } /// <summary> /// Find PEPM by CODE field /// </summary> /// <param name="CODE">CODE value used to find PEPM</param> /// <returns>List of related PEPM entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PEPM> FindByCODE(string CODE) { return Index_CODE.Value[CODE]; } /// <summary> /// Attempt to find PEPM by CODE field /// </summary> /// <param name="CODE">CODE value used to find PEPM</param> /// <param name="Value">List of related PEPM entities</param> /// <returns>True if the list of related PEPM entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByCODE(string CODE, out IReadOnlyList<PEPM> Value) { return Index_CODE.Value.TryGetValue(CODE, out Value); } /// <summary> /// Attempt to find PEPM by CODE field /// </summary> /// <param name="CODE">CODE value used to find PEPM</param> /// <returns>List of related PEPM entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<PEPM> TryFindByCODE(string CODE) { IReadOnlyList<PEPM> value; if (Index_CODE.Value.TryGetValue(CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find PEPM by TID field /// </summary> /// <param name="TID">TID value used to find PEPM</param> /// <returns>Related PEPM entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PEPM FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find PEPM by TID field /// </summary> /// <param name="TID">TID value used to find PEPM</param> /// <param name="Value">Related PEPM entity</param> /// <returns>True if the related PEPM entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out PEPM Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find PEPM by TID field /// </summary> /// <param name="TID">TID value used to find PEPM</param> /// <returns>Related PEPM entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public PEPM TryFindByTID(int TID) { PEPM value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a PEPM table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[PEPM]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[PEPM]( [TID] int IDENTITY NOT NULL, [CODE] varchar(10) NOT NULL, [NAME] varchar(30) NULL, [PAYMODE] varchar(2) NULL, [REFERENCE_NO] varchar(20) NULL, [CHQ_NO] varchar(10) NULL, [DAMOUNT] money NULL, [BANK] varchar(12) NULL, [BSB] varchar(6) NULL, [ACCOUNT_NO] varchar(15) NULL, [AMOUNT] money NULL, [FLAG] varchar(1) NULL, [TRBATCH] int NULL, [EFT_CREATED] varchar(1) NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [PEPM_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE NONCLUSTERED INDEX [PEPM_Index_BSB] ON [dbo].[PEPM] ( [BSB] ASC ); CREATE CLUSTERED INDEX [PEPM_Index_CODE] ON [dbo].[PEPM] ( [CODE] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PEPM]') AND name = N'PEPM_Index_BSB') ALTER INDEX [PEPM_Index_BSB] ON [dbo].[PEPM] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PEPM]') AND name = N'PEPM_Index_TID') ALTER INDEX [PEPM_Index_TID] ON [dbo].[PEPM] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PEPM]') AND name = N'PEPM_Index_BSB') ALTER INDEX [PEPM_Index_BSB] ON [dbo].[PEPM] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[PEPM]') AND name = N'PEPM_Index_TID') ALTER INDEX [PEPM_Index_TID] ON [dbo].[PEPM] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="PEPM"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="PEPM"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<PEPM> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[PEPM] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the PEPM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the PEPM data set</returns> public override EduHubDataSetDataReader<PEPM> GetDataSetDataReader() { return new PEPMDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the PEPM data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the PEPM data set</returns> public override EduHubDataSetDataReader<PEPM> GetDataSetDataReader(List<PEPM> Entities) { return new PEPMDataReader(new EduHubDataSetLoadedReader<PEPM>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class PEPMDataReader : EduHubDataSetDataReader<PEPM> { public PEPMDataReader(IEduHubDataSetReader<PEPM> Reader) : base (Reader) { } public override int FieldCount { get { return 17; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // CODE return Current.CODE; case 2: // NAME return Current.NAME; case 3: // PAYMODE return Current.PAYMODE; case 4: // REFERENCE_NO return Current.REFERENCE_NO; case 5: // CHQ_NO return Current.CHQ_NO; case 6: // DAMOUNT return Current.DAMOUNT; case 7: // BANK return Current.BANK; case 8: // BSB return Current.BSB; case 9: // ACCOUNT_NO return Current.ACCOUNT_NO; case 10: // AMOUNT return Current.AMOUNT; case 11: // FLAG return Current.FLAG; case 12: // TRBATCH return Current.TRBATCH; case 13: // EFT_CREATED return Current.EFT_CREATED; case 14: // LW_DATE return Current.LW_DATE; case 15: // LW_TIME return Current.LW_TIME; case 16: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // NAME return Current.NAME == null; case 3: // PAYMODE return Current.PAYMODE == null; case 4: // REFERENCE_NO return Current.REFERENCE_NO == null; case 5: // CHQ_NO return Current.CHQ_NO == null; case 6: // DAMOUNT return Current.DAMOUNT == null; case 7: // BANK return Current.BANK == null; case 8: // BSB return Current.BSB == null; case 9: // ACCOUNT_NO return Current.ACCOUNT_NO == null; case 10: // AMOUNT return Current.AMOUNT == null; case 11: // FLAG return Current.FLAG == null; case 12: // TRBATCH return Current.TRBATCH == null; case 13: // EFT_CREATED return Current.EFT_CREATED == null; case 14: // LW_DATE return Current.LW_DATE == null; case 15: // LW_TIME return Current.LW_TIME == null; case 16: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // CODE return "CODE"; case 2: // NAME return "NAME"; case 3: // PAYMODE return "PAYMODE"; case 4: // REFERENCE_NO return "REFERENCE_NO"; case 5: // CHQ_NO return "CHQ_NO"; case 6: // DAMOUNT return "DAMOUNT"; case 7: // BANK return "BANK"; case 8: // BSB return "BSB"; case 9: // ACCOUNT_NO return "ACCOUNT_NO"; case 10: // AMOUNT return "AMOUNT"; case 11: // FLAG return "FLAG"; case 12: // TRBATCH return "TRBATCH"; case 13: // EFT_CREATED return "EFT_CREATED"; case 14: // LW_DATE return "LW_DATE"; case 15: // LW_TIME return "LW_TIME"; case 16: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "CODE": return 1; case "NAME": return 2; case "PAYMODE": return 3; case "REFERENCE_NO": return 4; case "CHQ_NO": return 5; case "DAMOUNT": return 6; case "BANK": return 7; case "BSB": return 8; case "ACCOUNT_NO": return 9; case "AMOUNT": return 10; case "FLAG": return 11; case "TRBATCH": return 12; case "EFT_CREATED": return 13; case "LW_DATE": return 14; case "LW_TIME": return 15; case "LW_USER": return 16; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
using System; using System.Globalization; using System.Collections.Generic; using Sasoma.Utils; using Sasoma.Microdata.Interfaces; using Sasoma.Languages.Core; using Sasoma.Microdata.Properties; namespace Sasoma.Microdata.Types { /// <summary> /// Residence type: Single-family home. /// </summary> public class SingleFamilyResidence_Core : TypeCore, IResidence { public SingleFamilyResidence_Core() { this._TypeId = 241; this._Id = "SingleFamilyResidence"; this._Schema_Org_Url = "http://schema.org/SingleFamilyResidence"; string label = ""; GetLabel(out label, "SingleFamilyResidence", typeof(SingleFamilyResidence_Core)); this._Label = label; this._Ancestors = new int[]{266,206,227}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{227}; this._Properties = new int[]{67,108,143,229,5,10,49,85,91,98,115,135,159,199,196}; } /// <summary> /// Physical address of the item. /// </summary> private Address_Core address; public Address_Core Address { get { return address; } set { address = value; SetPropertyInstance(address); } } /// <summary> /// The overall rating, based on a collection of reviews or ratings, of the item. /// </summary> private Properties.AggregateRating_Core aggregateRating; public Properties.AggregateRating_Core AggregateRating { get { return aggregateRating; } set { aggregateRating = value; SetPropertyInstance(aggregateRating); } } /// <summary> /// The basic containment relation between places. /// </summary> private ContainedIn_Core containedIn; public ContainedIn_Core ContainedIn { get { return containedIn; } set { containedIn = value; SetPropertyInstance(containedIn); } } /// <summary> /// A short description of the item. /// </summary> private Description_Core description; public Description_Core Description { get { return description; } set { description = value; SetPropertyInstance(description); } } /// <summary> /// Upcoming or past events associated with this place or organization. /// </summary> private Events_Core events; public Events_Core Events { get { return events; } set { events = value; SetPropertyInstance(events); } } /// <summary> /// The fax number. /// </summary> private FaxNumber_Core faxNumber; public FaxNumber_Core FaxNumber { get { return faxNumber; } set { faxNumber = value; SetPropertyInstance(faxNumber); } } /// <summary> /// The geo coordinates of the place. /// </summary> private Geo_Core geo; public Geo_Core Geo { get { return geo; } set { geo = value; SetPropertyInstance(geo); } } /// <summary> /// URL of an image of the item. /// </summary> private Image_Core image; public Image_Core Image { get { return image; } set { image = value; SetPropertyInstance(image); } } /// <summary> /// A count of a specific user interactions with this item\u2014for example, <code>20 UserLikes</code>, <code>5 UserComments</code>, or <code>300 UserDownloads</code>. The user interaction type should be one of the sub types of <a href=\http://schema.org/UserInteraction\>UserInteraction</a>. /// </summary> private InteractionCount_Core interactionCount; public InteractionCount_Core InteractionCount { get { return interactionCount; } set { interactionCount = value; SetPropertyInstance(interactionCount); } } /// <summary> /// A URL to a map of the place. /// </summary> private Maps_Core maps; public Maps_Core Maps { get { return maps; } set { maps = value; SetPropertyInstance(maps); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <summary> /// Photographs of this place. /// </summary> private Photos_Core photos; public Photos_Core Photos { get { return photos; } set { photos = value; SetPropertyInstance(photos); } } /// <summary> /// Review of the item. /// </summary> private Reviews_Core reviews; public Reviews_Core Reviews { get { return reviews; } set { reviews = value; SetPropertyInstance(reviews); } } /// <summary> /// The telephone number. /// </summary> private Telephone_Core telephone; public Telephone_Core Telephone { get { return telephone; } set { telephone = value; SetPropertyInstance(telephone); } } /// <summary> /// URL of the item. /// </summary> private Properties.URL_Core uRL; public Properties.URL_Core URL { get { return uRL; } set { uRL = value; SetPropertyInstance(uRL); } } } }
/* ==================================================================== Licensed To the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file To You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed To in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.SS.Formula { using System; using System.Text; using System.Collections; using NPOI.SS.Util; internal class BookSheetKey { private int _bookIndex; private int _sheetIndex; public BookSheetKey(int bookIndex, int sheetIndex) { _bookIndex = bookIndex; _sheetIndex = sheetIndex; } public override int GetHashCode() { return _bookIndex * 17 + _sheetIndex; } public override bool Equals(Object obj) { BookSheetKey other = (BookSheetKey)obj; return _bookIndex == other._bookIndex && _sheetIndex == other._sheetIndex; } } /** * Optimisation - compacts many blank cell references used by a single formula. * * @author Josh Micich */ internal class FormulaUsedBlankCellSet { private class BlankCellSheetGroup { private IList _rectangleGroups; private int _currentRowIndex; private int _firstColumnIndex; private int _lastColumnIndex; private BlankCellRectangleGroup _currentRectangleGroup; public BlankCellSheetGroup() { _rectangleGroups = new ArrayList(); _currentRowIndex = -1; } public void AddCell(int rowIndex, int columnIndex) { if (_currentRowIndex == -1) { _currentRowIndex = rowIndex; _firstColumnIndex = columnIndex; _lastColumnIndex = columnIndex; } else { if (_currentRowIndex == rowIndex && _lastColumnIndex + 1 == columnIndex) { _lastColumnIndex = columnIndex; } else { // cell does not fit on end of current row if (_currentRectangleGroup == null) { _currentRectangleGroup = new BlankCellRectangleGroup(_currentRowIndex, _firstColumnIndex, _lastColumnIndex); } else { if (!_currentRectangleGroup.AcceptRow(_currentRowIndex, _firstColumnIndex, _lastColumnIndex)) { _rectangleGroups.Add(_currentRectangleGroup); _currentRectangleGroup = new BlankCellRectangleGroup(_currentRowIndex, _firstColumnIndex, _lastColumnIndex); } } _currentRowIndex = rowIndex; _firstColumnIndex = columnIndex; _lastColumnIndex = columnIndex; } } } public bool ContainsCell(int rowIndex, int columnIndex) { for (int i = _rectangleGroups.Count - 1; i >= 0; i--) { BlankCellRectangleGroup bcrg = (BlankCellRectangleGroup)_rectangleGroups[i]; if (bcrg.ContainsCell(rowIndex, columnIndex)) { return true; } } if (_currentRectangleGroup != null && _currentRectangleGroup.ContainsCell(rowIndex, columnIndex)) { return true; } if (_currentRowIndex != -1 && _currentRowIndex == rowIndex) { if (_firstColumnIndex <= columnIndex && columnIndex <= _lastColumnIndex) { return true; } } return false; } } private class BlankCellRectangleGroup { private int _firstRowIndex; private int _firstColumnIndex; private int _lastColumnIndex; private int _lastRowIndex; public BlankCellRectangleGroup(int firstRowIndex, int firstColumnIndex, int lastColumnIndex) { _firstRowIndex = firstRowIndex; _firstColumnIndex = firstColumnIndex; _lastColumnIndex = lastColumnIndex; _lastRowIndex = firstRowIndex; } public bool ContainsCell(int rowIndex, int columnIndex) { if (columnIndex < _firstColumnIndex) { return false; } if (columnIndex > _lastColumnIndex) { return false; } if (rowIndex < _firstRowIndex) { return false; } if (rowIndex > _lastRowIndex) { return false; } return true; } public bool AcceptRow(int rowIndex, int firstColumnIndex, int lastColumnIndex) { if (firstColumnIndex != _firstColumnIndex) { return false; } if (lastColumnIndex != _lastColumnIndex) { return false; } if (rowIndex != _lastRowIndex + 1) { return false; } _lastRowIndex = rowIndex; return true; } public override String ToString() { StringBuilder sb = new StringBuilder(64); CellReference crA = new CellReference(_firstRowIndex, _firstColumnIndex, false, false); CellReference crB = new CellReference(_lastRowIndex, _lastColumnIndex, false, false); sb.Append(GetType().Name); sb.Append(" [").Append(crA.FormatAsString()).Append(':').Append(crB.FormatAsString()).Append("]"); return sb.ToString(); } } private Hashtable _sheetGroupsByBookSheet; public FormulaUsedBlankCellSet() { _sheetGroupsByBookSheet = new Hashtable(); } public void AddCell(int bookIndex, int sheetIndex, int rowIndex, int columnIndex) { BlankCellSheetGroup sbcg = GetSheetGroup(bookIndex, sheetIndex); sbcg.AddCell(rowIndex, columnIndex); } private BlankCellSheetGroup GetSheetGroup(int bookIndex, int sheetIndex) { BookSheetKey key = new BookSheetKey(bookIndex, sheetIndex); BlankCellSheetGroup result = (BlankCellSheetGroup)_sheetGroupsByBookSheet[key]; if (result == null) { result = new BlankCellSheetGroup(); _sheetGroupsByBookSheet[key]= result; } return result; } public bool ContainsCell(BookSheetKey key, int rowIndex, int columnIndex) { BlankCellSheetGroup bcsg = (BlankCellSheetGroup)_sheetGroupsByBookSheet[key]; if (bcsg == null) { return false; } return bcsg.ContainsCell(rowIndex, columnIndex); } public bool IsEmpty { get { return _sheetGroupsByBookSheet.Count == 0; } } } }
using System; using System.IO; using System.Collections; using System.Diagnostics; using System.Net; using System.Net.Sockets; using System.Threading; namespace LumiSoft.Net { /// <summary> /// This is base class for Socket and Session based servers. /// </summary> public class SocketServer : System.ComponentModel.Component { private Socket m_pListner = null; protected Hashtable m_pSessions = null; private ArrayList m_pQueuedConnections = null; private bool m_Running = false; private System.Timers.Timer m_pTimer = null; private IPEndPoint m_pIPEndPoint = null; private string m_HostName = ""; private int m_SessionIdleTimeOut = 30000; private int m_MaxConnections = 1000; private int m_MaxBadCommands = 8; private bool m_LogCmds = false; #region Events declarations /// <summary> /// Occurs when server or session has system error(unhandled error). /// </summary> public event ErrorEventHandler SysError = null; #endregion /// <summary> /// Default constructor. /// </summary> public SocketServer() { m_pSessions = new Hashtable(); m_pQueuedConnections = new ArrayList(); m_pTimer = new System.Timers.Timer(15000); m_pIPEndPoint = new IPEndPoint(IPAddress.Any,25); m_HostName = System.Net.Dns.GetHostName(); m_pTimer.AutoReset = true; m_pTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.m_pTimer_Elapsed); } #region method Dispose /// <summary> /// Clean up any resources being used and stops server. /// </summary> public new void Dispose() { base.Dispose(); StopServer(); } #endregion #region method StartServer /// <summary> /// Starts server. /// </summary> public void StartServer() { if(!m_Running){ m_Running = true; // Start accepting ang queueing connections Thread tr = new Thread(new ThreadStart(this.StartProcCons)); tr.Start(); // Start proccessing queued connections Thread trSessionCreator = new Thread(new ThreadStart(this.StartProcQueuedCons)); trSessionCreator.Start(); m_pTimer.Enabled = true; } } #endregion #region method StopServer /// <summary> /// Stops server. NOTE: Active sessions aren't cancled. /// </summary> public void StopServer() { if(m_Running && m_pListner != null){ // Stop accepting new connections m_pListner.Close(); m_pListner = null; // Wait queued connections to be proccessed, there won't be new queued connections, // because Listner socket is closed. Thread.Sleep(100); m_Running = false; } } #endregion #region method StartProcCons /// <summary> /// Starts proccessiong incoming connections (Accepts and queues connections). /// </summary> private void StartProcCons() { try{ m_pListner = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); m_pListner.Bind(m_pIPEndPoint); m_pListner.Listen(500); // Accept connections and queue them while(m_Running){ // We have reached maximum connection limit if(m_pSessions.Count > m_MaxConnections){ // Wait while some active connectins are closed while(m_pSessions.Count > m_MaxConnections){ Thread.Sleep(100); } } // Wait incoming connection Socket s = m_pListner.Accept(); // Add session to queue lock(m_pQueuedConnections){ m_pQueuedConnections.Add(s); } } } catch(SocketException x){ // Socket listening stopped, happens when StopServer is called. // We need just skip this error. if(x.ErrorCode == 10004){ } else{ OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:",x); } } catch(Exception x){ OnSysError("WE MUST NEVER REACH HERE !!! StartProcCons:",x); } } #endregion #region method StartProcQueuedCons /// <summary> /// Starts queueed connections proccessing (Creates and starts session foreach connection). /// </summary> private void StartProcQueuedCons() { try{ while(m_Running){ // Get copy of queued connections, because we must release lock as soon as possible, // because no new connections can be added when m_pQueueSessions is locked. Socket[] connections = null; lock(m_pQueuedConnections){ connections = new Socket[m_pQueuedConnections.Count]; m_pQueuedConnections.CopyTo(connections); // Clear queue we have copy of entries m_pQueuedConnections.Clear(); } // Start sessions for(int i=0;i<connections.Length;i++){ // If session throws exception, handle it here or all queue is lost try{ InitNewSession(connections[i]); } catch(Exception x){ OnSysError("StartProcQueuedCons InitNewSession():",x); } } // If there few new connections to proccess, delay proccessing. We need to it // because if there is few or none connections proccess, while loop takes too much CPU. if(m_pQueuedConnections.Count < 10){ Thread.Sleep(50); } } } catch(Exception x){ OnSysError("WE MUST NEVER REACH HERE !!! StartProcQueuedCons:",x); } } #endregion #region method AddSession /// <summary> /// /// </summary> /// <param name="session"></param> internal protected void AddSession(object session) { lock(m_pSessions){ m_pSessions.Add(session.GetHashCode(),session); } } #endregion #region method RemoveSession /// <summary> /// /// </summary> /// <param name="session"></param> internal protected void RemoveSession(object session) { lock(m_pSessions){ m_pSessions.Remove(session.GetHashCode()); } } #endregion #region method OnSysError /// <summary> /// /// </summary> /// <param name="text"></param> /// <param name="x"></param> internal protected void OnSysError(string text,Exception x) { if(this.SysError != null){ this.SysError(this,new Error_EventArgs(x,new StackTrace())); } } #endregion #region method OnSessionTimeoutTimer /// <summary> /// This method must get timedout sessions and end them. /// </summary> private void OnSessionTimeoutTimer() { try{ // Close/Remove timed out sessions lock(m_pSessions){ ISocketServerSession[] sessions = new ISocketServerSession[m_pSessions.Count]; m_pSessions.Values.CopyTo(sessions,0); // Loop sessions and and call OnSessionTimeout() for timed out sessions. for(int i=0;i<sessions.Length;i++){ // If session throws exception, handle it here or next sessions timouts are not handled. try{ // Session timed out if(DateTime.Now > sessions[i].SessionLastDataTime.AddMilliseconds(this.SessionIdleTimeOut)){ sessions[i].OnSessionTimeout(); } } catch(Exception x){ OnSysError("OnTimer:",x); } } } } catch(Exception x){ OnSysError("WE MUST NEVER REACH HERE !!! OnTimer:",x); } } #endregion #region method m_pTimer_Elapsed private void m_pTimer_Elapsed(object sender,System.Timers.ElapsedEventArgs e) { OnSessionTimeoutTimer(); /* try{ // Close/Remove timed out sessions lock(m_pSessions){ SMTP_Session[] sessions = new SMTP_Session[m_pSessions.Count]; m_pSessions.Values.CopyTo(sessions,0); // Loop sessions and and call OnSessionTimeout() for timed out sessions. for(int i=0;i<sessions.Length;i++){ // If session throws exception, handle it here or next sessions timouts are not handled. try{ // Session timed out if(DateTime.Now > sessions[i].SessionLastDataTime.AddMilliseconds(m_SessionIdleTimeOut)){ sessions[i].OnSessionTimeout(); } } catch(Exception x){ OnSysError("OnTimer:",x); } } } } catch(Exception x){ OnSysError("WE MUST NEVER REACH HERE !!! OnTimer:",x); }*/ } #endregion #region virtual method InitNewSession /// <summary> /// Initialize and start new session here. Session isn't added to session list automatically, /// session must add itself to server session list by calling AddSession(). /// </summary> /// <param name="socket">Connected client socket.</param> protected virtual void InitNewSession(Socket socket) { } #endregion #region Properties Implementation /// <summary> /// Gets or sets which IP address to listen. /// </summary> [Obsolete("Use IPEndPoint instead !")] public string IpAddress { get{ return IPEndPoint.Address.ToString(); } set{ if(value.ToLower().IndexOf("all") > -1){ IPEndPoint.Address = IPAddress.Any; } else{ IPEndPoint.Address = IPAddress.Parse(value); } } } /// <summary> /// Gets or sets which port to listen. /// </summary> [Obsolete("Use IPEndPoint instead !")] public int Port { get{ return IPEndPoint.Port; } set{ IPEndPoint.Port = value; } } /// <summary> /// Gets or sets maximum session threads. /// </summary> [Obsolete("Use MaxConnections instead !")] public int Threads { get{ return MaxConnections; } set{ MaxConnections = value; } } /// <summary> /// Command idle timeout in milliseconds. /// </summary> [Obsolete("Not used any more, now there is only one time out (SessionIdleTimeOut).")] public int CommandIdleTimeOut { get{ return 60000; } set{ } } //------------------------------------------------------------- /// <summary> /// Gets or sets IPEndPoint server to listen. NOTE: If server running and changeing IPEndPoint, server will be restarted automatically. /// </summary> public IPEndPoint IPEndPoint { get{ return m_pIPEndPoint; } set{ if(value != null && !m_pIPEndPoint.Equals(value)){ m_pIPEndPoint = value; // We need to restart server to take effect IP or Port change if(m_Running){ StopServer(); StartServer(); } } } } /// <summary> /// Gets or sets maximum allowed connections. /// </summary> public int MaxConnections { get{ return m_MaxConnections; } set{ m_MaxConnections = value; } } /// <summary> /// Runs and stops server. /// </summary> public bool Enabled { get{ return m_Running; } set{ if(value != m_Running & !this.DesignMode){ if(value){ StartServer(); } else{ StopServer(); } } } } /// <summary> /// Gets or sets if to log commands. /// </summary> public bool LogCommands { get{ return m_LogCmds; } set{ m_LogCmds = value; } } /// <summary> /// Session idle timeout in milliseconds. /// </summary> public int SessionIdleTimeOut { get{ return m_SessionIdleTimeOut; } set{ m_SessionIdleTimeOut = value; } } /// <summary> /// Gets or sets maximum bad commands allowed to session. /// </summary> public int MaxBadCommands { get{ return m_MaxBadCommands; } set{ m_MaxBadCommands = value; } } /// <summary> /// Gets or set host name that is reported to clients. /// </summary> public string HostName { get{ return m_HostName; } set{ if(value.Length > 0){ m_HostName = value; } } } /// <summary> /// Gets active sessions. /// </summary> public Hashtable Sessions { get{ return m_pSessions; } } #endregion } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using osu.Framework.Allocation; using osu.Framework.Bindables; using osu.Framework.Extensions.ObjectExtensions; using osu.Game.Beatmaps; using osu.Game.Database; using osu.Game.Online.Spectator; using osu.Game.Replays; using osu.Game.Rulesets; using osu.Game.Scoring; using osu.Game.Users; namespace osu.Game.Screens.Spectate { /// <summary> /// A <see cref="OsuScreen"/> which spectates one or more users. /// </summary> public abstract class SpectatorScreen : OsuScreen { protected IReadOnlyList<int> UserIds => userIds; private readonly List<int> userIds = new List<int>(); [Resolved] private BeatmapManager beatmaps { get; set; } [Resolved] private RulesetStore rulesets { get; set; } [Resolved] private SpectatorClient spectatorClient { get; set; } [Resolved] private UserLookupCache userLookupCache { get; set; } private readonly IBindableDictionary<int, SpectatorState> playingUserStates = new BindableDictionary<int, SpectatorState>(); private readonly Dictionary<int, User> userMap = new Dictionary<int, User>(); private readonly Dictionary<int, GameplayState> gameplayStates = new Dictionary<int, GameplayState>(); private IBindable<WeakReference<BeatmapSetInfo>> managerUpdated; /// <summary> /// Creates a new <see cref="SpectatorScreen"/>. /// </summary> /// <param name="userIds">The users to spectate.</param> protected SpectatorScreen(params int[] userIds) { this.userIds.AddRange(userIds); } protected override void LoadComplete() { base.LoadComplete(); getAllUsers().ContinueWith(users => Schedule(() => { foreach (var u in users.Result) userMap[u.Id] = u; playingUserStates.BindTo(spectatorClient.PlayingUserStates); playingUserStates.BindCollectionChanged(onPlayingUserStatesChanged, true); managerUpdated = beatmaps.ItemUpdated.GetBoundCopy(); managerUpdated.BindValueChanged(beatmapUpdated); foreach (var (id, _) in userMap) spectatorClient.WatchUser(id); })); } private Task<User[]> getAllUsers() { var userLookupTasks = new List<Task<User>>(); foreach (var u in userIds) { userLookupTasks.Add(userLookupCache.GetUserAsync(u).ContinueWith(task => { if (!task.IsCompletedSuccessfully) return null; return task.Result; })); } return Task.WhenAll(userLookupTasks); } private void beatmapUpdated(ValueChangedEvent<WeakReference<BeatmapSetInfo>> e) { if (!e.NewValue.TryGetTarget(out var beatmapSet)) return; foreach (var (userId, _) in userMap) { if (!playingUserStates.TryGetValue(userId, out var userState)) continue; if (beatmapSet.Beatmaps.Any(b => b.OnlineBeatmapID == userState.BeatmapID)) updateGameplayState(userId); } } private void onPlayingUserStatesChanged(object sender, NotifyDictionaryChangedEventArgs<int, SpectatorState> e) { switch (e.Action) { case NotifyDictionaryChangedAction.Add: foreach (var (userId, state) in e.NewItems.AsNonNull()) onUserStateAdded(userId, state); break; case NotifyDictionaryChangedAction.Remove: foreach (var (userId, _) in e.OldItems.AsNonNull()) onUserStateRemoved(userId); break; case NotifyDictionaryChangedAction.Replace: foreach (var (userId, _) in e.OldItems.AsNonNull()) onUserStateRemoved(userId); foreach (var (userId, state) in e.NewItems.AsNonNull()) onUserStateAdded(userId, state); break; } } private void onUserStateAdded(int userId, SpectatorState state) { if (state.RulesetID == null || state.BeatmapID == null) return; if (!userMap.ContainsKey(userId)) return; Schedule(() => OnUserStateChanged(userId, state)); updateGameplayState(userId); } private void onUserStateRemoved(int userId) { if (!userMap.ContainsKey(userId)) return; if (!gameplayStates.TryGetValue(userId, out var gameplayState)) return; gameplayState.Score.Replay.HasReceivedAllFrames = true; gameplayStates.Remove(userId); Schedule(() => EndGameplay(userId)); } private void updateGameplayState(int userId) { Debug.Assert(userMap.ContainsKey(userId)); var user = userMap[userId]; var spectatorState = playingUserStates[userId]; var resolvedRuleset = rulesets.AvailableRulesets.FirstOrDefault(r => r.ID == spectatorState.RulesetID)?.CreateInstance(); if (resolvedRuleset == null) return; var resolvedBeatmap = beatmaps.QueryBeatmap(b => b.OnlineBeatmapID == spectatorState.BeatmapID); if (resolvedBeatmap == null) return; var score = new Score { ScoreInfo = new ScoreInfo { Beatmap = resolvedBeatmap, User = user, Mods = spectatorState.Mods.Select(m => m.ToMod(resolvedRuleset)).ToArray(), Ruleset = resolvedRuleset.RulesetInfo, }, Replay = new Replay { HasReceivedAllFrames = false }, }; var gameplayState = new GameplayState(score, resolvedRuleset, beatmaps.GetWorkingBeatmap(resolvedBeatmap)); gameplayStates[userId] = gameplayState; Schedule(() => StartGameplay(userId, gameplayState)); } /// <summary> /// Invoked when a spectated user's state has changed. /// </summary> /// <param name="userId">The user whose state has changed.</param> /// <param name="spectatorState">The new state.</param> protected abstract void OnUserStateChanged(int userId, [NotNull] SpectatorState spectatorState); /// <summary> /// Starts gameplay for a user. /// </summary> /// <param name="userId">The user to start gameplay for.</param> /// <param name="gameplayState">The gameplay state.</param> protected abstract void StartGameplay(int userId, [NotNull] GameplayState gameplayState); /// <summary> /// Ends gameplay for a user. /// </summary> /// <param name="userId">The user to end gameplay for.</param> protected abstract void EndGameplay(int userId); /// <summary> /// Stops spectating a user. /// </summary> /// <param name="userId">The user to stop spectating.</param> protected void RemoveUser(int userId) { onUserStateRemoved(userId); userIds.Remove(userId); userMap.Remove(userId); spectatorClient.StopWatchingUser(userId); } protected override void Dispose(bool isDisposing) { base.Dispose(isDisposing); if (spectatorClient != null) { foreach (var (userId, _) in userMap) spectatorClient.StopWatchingUser(userId); } managerUpdated?.UnbindAll(); } } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using EncompassRest.Loans.Enums; namespace EncompassRest.Loans { /// <summary> /// ClosingDisclosure3 /// </summary> public sealed partial class ClosingDisclosure3 : DirtyExtensibleObject, IIdentifiable { private DirtyValue<decimal?>? _actualLECD3TotalClosingCostJFromLatestRec; private DirtyValue<decimal?>? _actualLECD3TotalPayoffsAndPaymentsKFromLatestRec; private DirtyValue<decimal?>? _actualLELoanAmountFromLatestRec; private DirtyValue<decimal?>? _actualLenderCredits; private DirtyValue<decimal?>? _actualSTDLEAdjustmentAndOtherCreditsFromLatestRec; private DirtyValue<decimal?>? _actualSTDLEClosingCostFinancedFromLatestRec; private DirtyValue<decimal?>? _actualSTDLEDepositFromLatestRec; private DirtyValue<decimal?>? _actualSTDLEDownPaymentFromLatestRec; private DirtyValue<decimal?>? _actualSTDLEFundForBorrowerFromLatestRec; private DirtyValue<decimal?>? _actualSTDLESellerCredits; private DirtyValue<decimal?>? _actualSTDLESellerCreditsFromLatestRec; private DirtyValue<decimal?>? _actualSTDLETotalClosingCostJ; private DirtyValue<decimal?>? _actualSTDLETotalClosingCostJFromLatestRec; private DirtyValue<string?>? _adjustments061; private DirtyValue<decimal?>? _adjustments062; private DirtyValue<string?>? _adjustments071; private DirtyValue<decimal?>? _adjustments072; private DirtyValue<string?>? _adjustments101; private DirtyValue<decimal?>? _adjustments102; private DirtyValue<string?>? _adjustments111; private DirtyValue<decimal?>? _adjustments112; private DirtyValue<string?>? _adjustments151; private DirtyValue<decimal?>? _adjustments152; private DirtyValue<string?>? _adjustments81; private DirtyValue<decimal?>? _adjustments82; private DirtyValue<string?>? _adjustments91; private DirtyValue<decimal?>? _adjustments92; private DirtyValue<string?>? _adjustmentsforItemsPaidbySellerinAdvance161; private DirtyValue<decimal?>? _adjustmentsforItemsPaidbySellerinAdvance162; private DirtyValue<string?>? _aLTCashToCloseDidChangeCol; private DirtyValue<decimal?>? _aLTCashToCloseRemark; private DirtyValue<string?>? _aLTClosingCostBeforeClosingDidChangeCol; private DirtyValue<decimal?>? _aLTLegalLimit; private DirtyValue<string?>? _aLTLoanAmountDidChangeCol; private DirtyValue<StringEnumValue<IncreasedOrDecreased>>? _aLTLoanAmountIncDecRemark; private DirtyValue<string?>? _aLTTotalClosingCostDidChangeCol; private DirtyValue<StringEnumValue<TotalClosingCostRemark>>? _aLTTotalClosingCostRemark; private DirtyValue<string?>? _aLTTotalPayoffsDidChangeCol; private DirtyValue<decimal?>? _cash; private DirtyValue<decimal?>? _cashToClose; private DirtyValue<decimal?>? _cD3CashToClose; private DirtyValue<string?>? _cD3CashToCloseFromToBorrower; private DirtyValue<decimal?>? _cD3ClosingCostsPaidBeforeClosing; private DirtyValue<decimal?>? _cD3TotalClosingCostJ; private DirtyValue<decimal?>? _cD3TotalPayoffsAndPaymentsK; private DirtyValue<decimal?>? _closingCostsPaidAtClosing; private DirtyValue<decimal?>? _closingCostsPaidatClosingJ; private DirtyValue<string?>? _duefromSelleratClosing111; private DirtyValue<decimal?>? _duefromSelleratClosing112; private DirtyValue<string?>? _duefromSelleratClosing121; private DirtyValue<decimal?>? _duefromSelleratClosing122; private DirtyValue<string?>? _duefromSelleratClosing131; private DirtyValue<decimal?>? _duefromSelleratClosing132; private DirtyValue<string?>? _dueToSellerAtClosing61; private DirtyValue<decimal?>? _dueToSellerAtClosing62; private DirtyValue<string?>? _dueToSellerAtClosing71; private DirtyValue<decimal?>? _dueToSellerAtClosing72; private DirtyValue<string?>? _dueToSellerAtClosing81; private DirtyValue<decimal?>? _dueToSellerAtClosing82; private DirtyValue<bool?>? _excludeBorrowerClosingCosts; private DirtyValue<decimal?>? _finalCashToClose; private DirtyValue<string?>? _fromToBorrower; private DirtyValue<string?>? _fromToSeller; private DirtyValue<string?>? _id; private DirtyValue<decimal?>? _lECD3CashToClose; private DirtyValue<string?>? _lECD3CashToCloseFromToBorrower; private DirtyValue<decimal?>? _lECD3ClosingCostsPaidBeforeClosing; private DirtyValue<decimal?>? _lECD3TotalClosingCostJ; private DirtyValue<decimal?>? _lECD3TotalPayoffsAndPaymentsK; private DirtyValue<decimal?>? _lELoanAmount; private DirtyValue<decimal?>? _liabilityAmount1; private DirtyValue<decimal?>? _liabilityAmount10; private DirtyValue<decimal?>? _liabilityAmount11; private DirtyValue<decimal?>? _liabilityAmount12; private DirtyValue<decimal?>? _liabilityAmount13; private DirtyValue<decimal?>? _liabilityAmount14; private DirtyValue<decimal?>? _liabilityAmount15; private DirtyValue<decimal?>? _liabilityAmount2; private DirtyValue<decimal?>? _liabilityAmount3; private DirtyValue<decimal?>? _liabilityAmount4; private DirtyValue<decimal?>? _liabilityAmount5; private DirtyValue<decimal?>? _liabilityAmount6; private DirtyValue<decimal?>? _liabilityAmount7; private DirtyValue<decimal?>? _liabilityAmount8; private DirtyValue<decimal?>? _liabilityAmount9; private DirtyValue<string?>? _liabilityTo1; private DirtyValue<string?>? _liabilityTo10; private DirtyValue<string?>? _liabilityTo11; private DirtyValue<string?>? _liabilityTo12; private DirtyValue<string?>? _liabilityTo13; private DirtyValue<string?>? _liabilityTo14; private DirtyValue<string?>? _liabilityTo15; private DirtyValue<string?>? _liabilityTo2; private DirtyValue<string?>? _liabilityTo3; private DirtyValue<string?>? _liabilityTo4; private DirtyValue<string?>? _liabilityTo5; private DirtyValue<string?>? _liabilityTo6; private DirtyValue<string?>? _liabilityTo7; private DirtyValue<string?>? _liabilityTo8; private DirtyValue<string?>? _liabilityTo9; private DirtyValue<decimal?>? _liabilityTotal; private DirtyValue<decimal?>? _loanAmount; private DirtyValue<bool?>? _newVerbiageDisclosed; private DirtyValue<decimal?>? _nonUCDTotalAdjustmentsAndOtherCredits; private DirtyValue<bool?>? _omitFromPrintSellersTransaction; private DirtyValue<string?>? _otherCredits61; private DirtyValue<decimal?>? _otherCredits62; private DirtyValue<string?>? _otherCredits71; private DirtyValue<decimal?>? _otherCredits72; private DirtyValue<decimal?>? _priorToleranceCureAmount; private DirtyValue<StringEnumValue<STDAdjustmentAndOtherCreditsRemark>>? _sTDAdjustmentAndOtherCreditsRemark; private DirtyValue<string?>? _sTDAdjustmentsDidChangeCol; private DirtyValue<string?>? _sTDClosingCostFinancedDidChangeCol; private DirtyValue<string?>? _sTDDepositDidChangeCol; private DirtyValue<StringEnumValue<IncreasedOrDecreased>>? _sTDDepositIncDecRemark; private DirtyValue<string?>? _sTDDownPaymentDidChangeCol; private DirtyValue<StringEnumValue<IncreasedOrDecreased>>? _sTDDownPaymentIncDecRemark; private DirtyValue<StringEnumValue<STDDownPaymentSectionRemark>>? _sTDDownPaymentSectionRemark; private DirtyValue<decimal?>? _sTDFinalAdjustmentAndOtherCredits; private DirtyValue<decimal?>? _sTDFinalCashToClose; private DirtyValue<decimal?>? _sTDFinalCD3ClosingCostsPaidBeforeClosing; private DirtyValue<decimal?>? _sTDFinalClosingCostFinanced; private DirtyValue<decimal?>? _sTDFinalDeposit; private DirtyValue<decimal?>? _sTDFinalDownPayment; private DirtyValue<decimal?>? _sTDFinalFundForBorrower; private DirtyValue<decimal?>? _sTDFinalSellerCredits; private DirtyValue<decimal?>? _sTDFinalTotalClosingCostJ; private DirtyValue<string?>? _sTDFundsForBorrowerDidChangeCol; private DirtyValue<StringEnumValue<IncreasedOrDecreased>>? _sTDFundsForBorrowerIncDecRemark; private DirtyValue<decimal?>? _sTDLEAdjustmentAndOtherCredits; private DirtyValue<decimal?>? _sTDLECashToClose; private DirtyValue<decimal?>? _sTDLECD3ClosingCostsPaidBeforeClosing; private DirtyValue<decimal?>? _sTDLEClosingCostFinanced; private DirtyValue<decimal?>? _sTDLEDeposit; private DirtyValue<decimal?>? _sTDLEDownPayment; private DirtyValue<decimal?>? _sTDLEFundForBorrower; private DirtyValue<decimal?>? _sTDLegalLimit; private DirtyValue<decimal?>? _sTDLESellerCredits; private DirtyValue<decimal?>? _sTDLETotalClosingCostJ; private DirtyValue<string?>? _sTDSellerCreditsDidChangeCol; private DirtyValue<StringEnumValue<IncreasedOrDecreased>>? _sTDSellerCreditsIncDecRemark; private DirtyValue<string?>? _sTDTotalClosingCostBeforeClosingDidChangeCol; private DirtyValue<string?>? _sTDTotalClosingCostDidChangeCol; private DirtyValue<StringEnumValue<TotalClosingCostRemark>>? _sTDTotalClosingCostRemark; private DirtyValue<decimal?>? _totalAdjustmentsAndOtherCredits; private DirtyValue<decimal?>? _totalDuefromBorrowerAtClosing; private DirtyValue<decimal?>? _totalDuefromSelleratClosingN; private DirtyValue<decimal?>? _totalDuetoSelleratClosingM; private DirtyValue<decimal?>? _totalFromK; private DirtyValue<decimal?>? _totalFromL; private DirtyValue<decimal?>? _totalFromM; private DirtyValue<decimal?>? _totalFromN; private DirtyValue<decimal?>? _totalPaidAlreadybyoronBehalfofBoroweratClosing; private DirtyValue<decimal?>? _totalPurchasePayoffsIncluded; private DirtyList<UCDDetail>? _uCDDetails; private DirtyValue<decimal?>? _uCDKSubTotal; private DirtyValue<decimal?>? _uCDLSubTotal; private DirtyValue<decimal?>? _uCDTotalAdjustmentsAndOtherCredits; /// <summary> /// Decimal Value of Alternate LE CD3 Total Closing Costs J From Latest Disclosure Tracking Log [CD3.XH88] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualLECD3TotalClosingCostJFromLatestRec { get => _actualLECD3TotalClosingCostJFromLatestRec; set => SetField(ref _actualLECD3TotalClosingCostJFromLatestRec, value); } /// <summary> /// Decimal Value of Alternate LE CD3 Total Payoffs And Payments K From Latest Disclosure Tracking Log [CD3.XH90] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualLECD3TotalPayoffsAndPaymentsKFromLatestRec { get => _actualLECD3TotalPayoffsAndPaymentsKFromLatestRec; set => SetField(ref _actualLECD3TotalPayoffsAndPaymentsKFromLatestRec, value); } /// <summary> /// Decimal Value of Alternate LE Loan Amount From Latest Disclosure Tracking Log [CD3.XH87] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualLELoanAmountFromLatestRec { get => _actualLELoanAmountFromLatestRec; set => SetField(ref _actualLELoanAmountFromLatestRec, value); } /// <summary> /// ClosingDisclosure3 ActualLenderCredits /// </summary> public decimal? ActualLenderCredits { get => _actualLenderCredits; set => SetField(ref _actualLenderCredits, value); } /// <summary> /// Decimal Value of STD LE Adjustments And Other Credits From Latest Disclosure Tracking Log [CD3.XH100] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLEAdjustmentAndOtherCreditsFromLatestRec { get => _actualSTDLEAdjustmentAndOtherCreditsFromLatestRec; set => SetField(ref _actualSTDLEAdjustmentAndOtherCreditsFromLatestRec, value); } /// <summary> /// Decimal Value of STD LE Closing Costs Financed From Latest Disclosure Tracking Log [CD3.XH95] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLEClosingCostFinancedFromLatestRec { get => _actualSTDLEClosingCostFinancedFromLatestRec; set => SetField(ref _actualSTDLEClosingCostFinancedFromLatestRec, value); } /// <summary> /// Decimal Value of STD LE Deposit From Latest Disclosure Tracking Log [CD3.XH97] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLEDepositFromLatestRec { get => _actualSTDLEDepositFromLatestRec; set => SetField(ref _actualSTDLEDepositFromLatestRec, value); } /// <summary> /// Decimal Value of STD LE Down Payment From Latest Disclosure Tracking Log [CD3.XH96] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLEDownPaymentFromLatestRec { get => _actualSTDLEDownPaymentFromLatestRec; set => SetField(ref _actualSTDLEDownPaymentFromLatestRec, value); } /// <summary> /// Decimal Value of STD LE Funds For Borrower From Latest Disclosure Tracking Log [CD3.XH98] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLEFundForBorrowerFromLatestRec { get => _actualSTDLEFundForBorrowerFromLatestRec; set => SetField(ref _actualSTDLEFundForBorrowerFromLatestRec, value); } /// <summary> /// ClosingDisclosure3 ActualSTDLESellerCredits /// </summary> public decimal? ActualSTDLESellerCredits { get => _actualSTDLESellerCredits; set => SetField(ref _actualSTDLESellerCredits, value); } /// <summary> /// Decimal Value of STD LE Seller Credits From Latest Disclosure Tracking Log [CD3.XH99] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLESellerCreditsFromLatestRec { get => _actualSTDLESellerCreditsFromLatestRec; set => SetField(ref _actualSTDLESellerCreditsFromLatestRec, value); } /// <summary> /// ClosingDisclosure3 ActualSTDLETotalClosingCostJ /// </summary> public decimal? ActualSTDLETotalClosingCostJ { get => _actualSTDLETotalClosingCostJ; set => SetField(ref _actualSTDLETotalClosingCostJ, value); } /// <summary> /// Decimal Value of STD LE Total Closing Costs J From Latest Disclosure Tracking Log [CD3.XH93] /// </summary> [LoanFieldProperty(ReadOnly = true)] public decimal? ActualSTDLETotalClosingCostJFromLatestRec { get => _actualSTDLETotalClosingCostJFromLatestRec; set => SetField(ref _actualSTDLETotalClosingCostJFromLatestRec, value); } /// <summary> /// Adjustments06_1 [CD3.X2] /// </summary> public string? Adjustments061 { get => _adjustments061; set => SetField(ref _adjustments061, value); } /// <summary> /// Adjustments06_2 [CD3.X3] /// </summary> public decimal? Adjustments062 { get => _adjustments062; set => SetField(ref _adjustments062, value); } /// <summary> /// Adjustments07_1 [CD3.X4] /// </summary> public string? Adjustments071 { get => _adjustments071; set => SetField(ref _adjustments071, value); } /// <summary> /// Adjustments07_2 [CD3.X5] /// </summary> public decimal? Adjustments072 { get => _adjustments072; set => SetField(ref _adjustments072, value); } /// <summary> /// Adjustments10_1 [CD3.X17] /// </summary> public string? Adjustments101 { get => _adjustments101; set => SetField(ref _adjustments101, value); } /// <summary> /// Adjustments10_2 [CD3.X18] /// </summary> public decimal? Adjustments102 { get => _adjustments102; set => SetField(ref _adjustments102, value); } /// <summary> /// Adjustments11_1 [CD3.X19] /// </summary> public string? Adjustments111 { get => _adjustments111; set => SetField(ref _adjustments111, value); } /// <summary> /// Adjustments11_2 [CD3.X20] /// </summary> public decimal? Adjustments112 { get => _adjustments112; set => SetField(ref _adjustments112, value); } /// <summary> /// Adjustments15_1 [CD3.X6] /// </summary> public string? Adjustments151 { get => _adjustments151; set => SetField(ref _adjustments151, value); } /// <summary> /// Adjustments15_2 [CD3.X7] /// </summary> public decimal? Adjustments152 { get => _adjustments152; set => SetField(ref _adjustments152, value); } /// <summary> /// Adjustments8_1 [CD3.X13] /// </summary> public string? Adjustments81 { get => _adjustments81; set => SetField(ref _adjustments81, value); } /// <summary> /// Adjustments8_2 [CD3.X14] /// </summary> public decimal? Adjustments82 { get => _adjustments82; set => SetField(ref _adjustments82, value); } /// <summary> /// Adjustments9_1 [CD3.X15] /// </summary> public string? Adjustments91 { get => _adjustments91; set => SetField(ref _adjustments91, value); } /// <summary> /// Adjustments9_2 [CD3.X16] /// </summary> public decimal? Adjustments92 { get => _adjustments92; set => SetField(ref _adjustments92, value); } /// <summary> /// AdjustmentsforItemsPaidbySellerinAdvance16_1 [CD3.X30] /// </summary> public string? AdjustmentsforItemsPaidbySellerinAdvance161 { get => _adjustmentsforItemsPaidbySellerinAdvance161; set => SetField(ref _adjustmentsforItemsPaidbySellerinAdvance161, value); } /// <summary> /// AdjustmentsforItemsPaidbySellerinAdvance16_2 [CD3.X31] /// </summary> public decimal? AdjustmentsforItemsPaidbySellerinAdvance162 { get => _adjustmentsforItemsPaidbySellerinAdvance162; set => SetField(ref _adjustmentsforItemsPaidbySellerinAdvance162, value); } /// <summary> /// ALT Cash To Close Did Change Col [CD3.X122] /// </summary> public string? ALTCashToCloseDidChangeCol { get => _aLTCashToCloseDidChangeCol; set => SetField(ref _aLTCashToCloseDidChangeCol, value); } /// <summary> /// ALT Cash To Close Remark [CD3.X133] /// </summary> public decimal? ALTCashToCloseRemark { get => _aLTCashToCloseRemark; set => SetField(ref _aLTCashToCloseRemark, value); } /// <summary> /// ALT CLosing Cost Before Did Change Col [CD3.X120] /// </summary> public string? ALTClosingCostBeforeClosingDidChangeCol { get => _aLTClosingCostBeforeClosingDidChangeCol; set => SetField(ref _aLTClosingCostBeforeClosingDidChangeCol, value); } /// <summary> /// ALT Legal Limit [CD3.X132] /// </summary> public decimal? ALTLegalLimit { get => _aLTLegalLimit; set => SetField(ref _aLTLegalLimit, value); } /// <summary> /// ALT Loan Amount Did Change Col [CD3.X118] /// </summary> public string? ALTLoanAmountDidChangeCol { get => _aLTLoanAmountDidChangeCol; set => SetField(ref _aLTLoanAmountDidChangeCol, value); } /// <summary> /// ALT Loan Amount IncDec Remark [CD3.X130] /// </summary> public StringEnumValue<IncreasedOrDecreased> ALTLoanAmountIncDecRemark { get => _aLTLoanAmountIncDecRemark; set => SetField(ref _aLTLoanAmountIncDecRemark, value); } /// <summary> /// ALT Total Closing Cost Did Change Col [CD3.X119] /// </summary> public string? ALTTotalClosingCostDidChangeCol { get => _aLTTotalClosingCostDidChangeCol; set => SetField(ref _aLTTotalClosingCostDidChangeCol, value); } /// <summary> /// ALT Total Closing Cost Remark [CD3.X131] /// </summary> public StringEnumValue<TotalClosingCostRemark> ALTTotalClosingCostRemark { get => _aLTTotalClosingCostRemark; set => SetField(ref _aLTTotalClosingCostRemark, value); } /// <summary> /// ALT Total Payoffs Did Change Col [CD3.X121] /// </summary> public string? ALTTotalPayoffsDidChangeCol { get => _aLTTotalPayoffsDidChangeCol; set => SetField(ref _aLTTotalPayoffsDidChangeCol, value); } /// <summary> /// Cash [CD3.X40] /// </summary> public decimal? Cash { get => _cash; set => SetField(ref _cash, value); } /// <summary> /// Cash To Close [CD3.X23] /// </summary> public decimal? CashToClose { get => _cashToClose; set => SetField(ref _cashToClose, value); } /// <summary> /// CD3 Cash To Close [CD3.X85] /// </summary> public decimal? CD3CashToClose { get => _cD3CashToClose; set => SetField(ref _cD3CashToClose, value); } /// <summary> /// CD3 Cash To Close From To Borrower [CD3.X86] /// </summary> public string? CD3CashToCloseFromToBorrower { get => _cD3CashToCloseFromToBorrower; set => SetField(ref _cD3CashToCloseFromToBorrower, value); } /// <summary> /// CD3 Closing Costs Paid Before Closing [CD3.X83] /// </summary> public decimal? CD3ClosingCostsPaidBeforeClosing { get => _cD3ClosingCostsPaidBeforeClosing; set => SetField(ref _cD3ClosingCostsPaidBeforeClosing, value); } /// <summary> /// CD3 Total Closing Cost J [CD3.X82] /// </summary> public decimal? CD3TotalClosingCostJ { get => _cD3TotalClosingCostJ; set => SetField(ref _cD3TotalClosingCostJ, value); } /// <summary> /// CD3 Total Payoffs And Payments K [CD3.X84] /// </summary> public decimal? CD3TotalPayoffsAndPaymentsK { get => _cD3TotalPayoffsAndPaymentsK; set => SetField(ref _cD3TotalPayoffsAndPaymentsK, value); } /// <summary> /// Closing Costs Paid At Closing [CD3.X1] /// </summary> public decimal? ClosingCostsPaidAtClosing { get => _closingCostsPaidAtClosing; set => SetField(ref _closingCostsPaidAtClosing, value); } /// <summary> /// Closing Costs Paid at Closing J [CD3.X46] /// </summary> public decimal? ClosingCostsPaidatClosingJ { get => _closingCostsPaidatClosingJ; set => SetField(ref _closingCostsPaidatClosingJ, value); } /// <summary> /// DuefromSelleratClosing11_1 [CD3.X32] /// </summary> public string? DuefromSelleratClosing111 { get => _duefromSelleratClosing111; set => SetField(ref _duefromSelleratClosing111, value); } /// <summary> /// DuefromSelleratClosing11_2 [CD3.X33] /// </summary> public decimal? DuefromSelleratClosing112 { get => _duefromSelleratClosing112; set => SetField(ref _duefromSelleratClosing112, value); } /// <summary> /// DuefromSelleratClosing12_1 [CD3.X34] /// </summary> public string? DuefromSelleratClosing121 { get => _duefromSelleratClosing121; set => SetField(ref _duefromSelleratClosing121, value); } /// <summary> /// DuefromSelleratClosing12_2 [CD3.X35] /// </summary> public decimal? DuefromSelleratClosing122 { get => _duefromSelleratClosing122; set => SetField(ref _duefromSelleratClosing122, value); } /// <summary> /// DuefromSelleratClosing13_1 [CD3.X36] /// </summary> public string? DuefromSelleratClosing131 { get => _duefromSelleratClosing131; set => SetField(ref _duefromSelleratClosing131, value); } /// <summary> /// DuefromSelleratClosing13_2 [CD3.X37] /// </summary> public decimal? DuefromSelleratClosing132 { get => _duefromSelleratClosing132; set => SetField(ref _duefromSelleratClosing132, value); } /// <summary> /// DueToSellerAtClosing6_1 [CD3.X24] /// </summary> public string? DueToSellerAtClosing61 { get => _dueToSellerAtClosing61; set => SetField(ref _dueToSellerAtClosing61, value); } /// <summary> /// DueToSellerAtClosing6_2 [CD3.X25] /// </summary> public decimal? DueToSellerAtClosing62 { get => _dueToSellerAtClosing62; set => SetField(ref _dueToSellerAtClosing62, value); } /// <summary> /// DueToSellerAtClosing7_1 [CD3.X26] /// </summary> public string? DueToSellerAtClosing71 { get => _dueToSellerAtClosing71; set => SetField(ref _dueToSellerAtClosing71, value); } /// <summary> /// DueToSellerAtClosing7_2 [CD3.X27] /// </summary> public decimal? DueToSellerAtClosing72 { get => _dueToSellerAtClosing72; set => SetField(ref _dueToSellerAtClosing72, value); } /// <summary> /// DueToSellerAtClosing8_1 [CD3.X28] /// </summary> public string? DueToSellerAtClosing81 { get => _dueToSellerAtClosing81; set => SetField(ref _dueToSellerAtClosing81, value); } /// <summary> /// DueToSellerAtClosing8_2 [CD3.X29] /// </summary> public decimal? DueToSellerAtClosing82 { get => _dueToSellerAtClosing82; set => SetField(ref _dueToSellerAtClosing82, value); } /// <summary> /// Exclude Borrower Closing Costs [CD3.X137] /// </summary> public bool? ExcludeBorrowerClosingCosts { get => _excludeBorrowerClosingCosts; set => SetField(ref _excludeBorrowerClosingCosts, value); } /// <summary> /// Closing disclosure - Final Cash To Close [CD3.X45] /// </summary> public decimal? FinalCashToClose { get => _finalCashToClose; set => SetField(ref _finalCashToClose, value); } /// <summary> /// From To Borrower [CD3.X48] /// </summary> public string? FromToBorrower { get => _fromToBorrower; set => SetField(ref _fromToBorrower, value); } /// <summary> /// From To Seller [CD3.X49] /// </summary> public string? FromToSeller { get => _fromToSeller; set => SetField(ref _fromToSeller, value); } /// <summary> /// ClosingDisclosure3 Id /// </summary> public string? Id { get => _id; set => SetField(ref _id, value); } /// <summary> /// LE CD3 Cash To Close [CD3.X91] /// </summary> public decimal? LECD3CashToClose { get => _lECD3CashToClose; set => SetField(ref _lECD3CashToClose, value); } /// <summary> /// LE CD3 Cash To Close From To Borrower [CD3.X92] /// </summary> public string? LECD3CashToCloseFromToBorrower { get => _lECD3CashToCloseFromToBorrower; set => SetField(ref _lECD3CashToCloseFromToBorrower, value); } /// <summary> /// LE CD3 Closing Costs Paid Before Closing [CD3.X89] /// </summary> public decimal? LECD3ClosingCostsPaidBeforeClosing { get => _lECD3ClosingCostsPaidBeforeClosing; set => SetField(ref _lECD3ClosingCostsPaidBeforeClosing, value); } /// <summary> /// LE CD3 Total Closing Cost J [CD3.X88] /// </summary> public decimal? LECD3TotalClosingCostJ { get => _lECD3TotalClosingCostJ; set => SetField(ref _lECD3TotalClosingCostJ, value); } /// <summary> /// LE CD3 Total Payoffs And Payments K [CD3.X90] /// </summary> public decimal? LECD3TotalPayoffsAndPaymentsK { get => _lECD3TotalPayoffsAndPaymentsK; set => SetField(ref _lECD3TotalPayoffsAndPaymentsK, value); } /// <summary> /// LE Loan Amount [CD3.X87] /// </summary> public decimal? LELoanAmount { get => _lELoanAmount; set => SetField(ref _lELoanAmount, value); } /// <summary> /// Liability Amount 1 [CD3.X65] /// </summary> public decimal? LiabilityAmount1 { get => _liabilityAmount1; set => SetField(ref _liabilityAmount1, value); } /// <summary> /// Liability Amount 10 [CD3.X74] /// </summary> public decimal? LiabilityAmount10 { get => _liabilityAmount10; set => SetField(ref _liabilityAmount10, value); } /// <summary> /// Liability Amount 11 [CD3.X75] /// </summary> public decimal? LiabilityAmount11 { get => _liabilityAmount11; set => SetField(ref _liabilityAmount11, value); } /// <summary> /// Liability Amount 12 [CD3.X76] /// </summary> public decimal? LiabilityAmount12 { get => _liabilityAmount12; set => SetField(ref _liabilityAmount12, value); } /// <summary> /// Liability Amount 13 [CD3.X77] /// </summary> public decimal? LiabilityAmount13 { get => _liabilityAmount13; set => SetField(ref _liabilityAmount13, value); } /// <summary> /// Liability Amount 14 [CD3.X78] /// </summary> public decimal? LiabilityAmount14 { get => _liabilityAmount14; set => SetField(ref _liabilityAmount14, value); } /// <summary> /// Liability Amount 15 [CD3.X79] /// </summary> public decimal? LiabilityAmount15 { get => _liabilityAmount15; set => SetField(ref _liabilityAmount15, value); } /// <summary> /// Liability Amount 3 [CD3.X66] /// </summary> public decimal? LiabilityAmount2 { get => _liabilityAmount2; set => SetField(ref _liabilityAmount2, value); } /// <summary> /// Liability Amount 3 [CD3.X67] /// </summary> public decimal? LiabilityAmount3 { get => _liabilityAmount3; set => SetField(ref _liabilityAmount3, value); } /// <summary> /// Liability Amount 4 [CD3.X68] /// </summary> public decimal? LiabilityAmount4 { get => _liabilityAmount4; set => SetField(ref _liabilityAmount4, value); } /// <summary> /// Liability Amount 5 [CD3.X69] /// </summary> public decimal? LiabilityAmount5 { get => _liabilityAmount5; set => SetField(ref _liabilityAmount5, value); } /// <summary> /// Liability Amount 6 [CD3.X70] /// </summary> public decimal? LiabilityAmount6 { get => _liabilityAmount6; set => SetField(ref _liabilityAmount6, value); } /// <summary> /// Liability Amount 7 [CD3.X71] /// </summary> public decimal? LiabilityAmount7 { get => _liabilityAmount7; set => SetField(ref _liabilityAmount7, value); } /// <summary> /// Liability Amount 8 [CD3.X72] /// </summary> public decimal? LiabilityAmount8 { get => _liabilityAmount8; set => SetField(ref _liabilityAmount8, value); } /// <summary> /// Liability Amount 9 [CD3.X73] /// </summary> public decimal? LiabilityAmount9 { get => _liabilityAmount9; set => SetField(ref _liabilityAmount9, value); } /// <summary> /// Liability To 1 [CD3.X50] /// </summary> public string? LiabilityTo1 { get => _liabilityTo1; set => SetField(ref _liabilityTo1, value); } /// <summary> /// Liability To 10 [CD3.X59] /// </summary> public string? LiabilityTo10 { get => _liabilityTo10; set => SetField(ref _liabilityTo10, value); } /// <summary> /// Liability To 11 [CD3.X60] /// </summary> public string? LiabilityTo11 { get => _liabilityTo11; set => SetField(ref _liabilityTo11, value); } /// <summary> /// Liability To 12 [CD3.X61] /// </summary> public string? LiabilityTo12 { get => _liabilityTo12; set => SetField(ref _liabilityTo12, value); } /// <summary> /// Liability To 13 [CD3.X62] /// </summary> public string? LiabilityTo13 { get => _liabilityTo13; set => SetField(ref _liabilityTo13, value); } /// <summary> /// Liability To 14 [CD3.X63] /// </summary> public string? LiabilityTo14 { get => _liabilityTo14; set => SetField(ref _liabilityTo14, value); } /// <summary> /// Liability To 15 [CD3.X64] /// </summary> public string? LiabilityTo15 { get => _liabilityTo15; set => SetField(ref _liabilityTo15, value); } /// <summary> /// Liability To 3 [CD3.X51] /// </summary> public string? LiabilityTo2 { get => _liabilityTo2; set => SetField(ref _liabilityTo2, value); } /// <summary> /// Liability To 3 [CD3.X52] /// </summary> public string? LiabilityTo3 { get => _liabilityTo3; set => SetField(ref _liabilityTo3, value); } /// <summary> /// Liability To 4 [CD3.X53] /// </summary> public string? LiabilityTo4 { get => _liabilityTo4; set => SetField(ref _liabilityTo4, value); } /// <summary> /// Liability To 5 [CD3.X54] /// </summary> public string? LiabilityTo5 { get => _liabilityTo5; set => SetField(ref _liabilityTo5, value); } /// <summary> /// Liability To 6 [CD3.X55] /// </summary> public string? LiabilityTo6 { get => _liabilityTo6; set => SetField(ref _liabilityTo6, value); } /// <summary> /// Liability To 7 [CD3.X56] /// </summary> public string? LiabilityTo7 { get => _liabilityTo7; set => SetField(ref _liabilityTo7, value); } /// <summary> /// Liability To 8 [CD3.X57] /// </summary> public string? LiabilityTo8 { get => _liabilityTo8; set => SetField(ref _liabilityTo8, value); } /// <summary> /// Liability To 9 [CD3.X58] /// </summary> public string? LiabilityTo9 { get => _liabilityTo9; set => SetField(ref _liabilityTo9, value); } /// <summary> /// Liability Total [CD3.X80] /// </summary> public decimal? LiabilityTotal { get => _liabilityTotal; set => SetField(ref _liabilityTotal, value); } /// <summary> /// Loan Amount [CD3.X81] /// </summary> public decimal? LoanAmount { get => _loanAmount; set => SetField(ref _loanAmount, value); } /// <summary> /// New Verbiage Disclosed [CD3.X1542] /// </summary> public bool? NewVerbiageDisclosed { get => _newVerbiageDisclosed; set => SetField(ref _newVerbiageDisclosed, value); } /// <summary> /// Non UCD Total Adjustments And Other Credits [CD3.X1505] /// </summary> public decimal? NonUCDTotalAdjustmentsAndOtherCredits { get => _nonUCDTotalAdjustmentsAndOtherCredits; set => SetField(ref _nonUCDTotalAdjustmentsAndOtherCredits, value); } /// <summary> /// Omit from Print Seller's Transaction [CD3.X138] /// </summary> public bool? OmitFromPrintSellersTransaction { get => _omitFromPrintSellersTransaction; set => SetField(ref _omitFromPrintSellersTransaction, value); } /// <summary> /// OtherCredits6_1 [CD3.X9] /// </summary> public string? OtherCredits61 { get => _otherCredits61; set => SetField(ref _otherCredits61, value); } /// <summary> /// OtherCredits6_2 [CD3.X10] /// </summary> public decimal? OtherCredits62 { get => _otherCredits62; set => SetField(ref _otherCredits62, value); } /// <summary> /// OtherCredits7_1 [CD3.X11] /// </summary> public string? OtherCredits71 { get => _otherCredits71; set => SetField(ref _otherCredits71, value); } /// <summary> /// OtherCredits7_2 [CD3.X12] /// </summary> public decimal? OtherCredits72 { get => _otherCredits72; set => SetField(ref _otherCredits72, value); } /// <summary> /// Prior Tolerance Cure Amount [CD3.X135] /// </summary> public decimal? PriorToleranceCureAmount { get => _priorToleranceCureAmount; set => SetField(ref _priorToleranceCureAmount, value); } /// <summary> /// STD Adjustment And Other Credits Remark [CD3.X136] /// </summary> public StringEnumValue<STDAdjustmentAndOtherCreditsRemark> STDAdjustmentAndOtherCreditsRemark { get => _sTDAdjustmentAndOtherCreditsRemark; set => SetField(ref _sTDAdjustmentAndOtherCreditsRemark, value); } /// <summary> /// STD Adjustments Did Change Col [CD3.X117] /// </summary> public string? STDAdjustmentsDidChangeCol { get => _sTDAdjustmentsDidChangeCol; set => SetField(ref _sTDAdjustmentsDidChangeCol, value); } /// <summary> /// STD Closing Cost Financed Did Change Col [CD3.X134] /// </summary> public string? STDClosingCostFinancedDidChangeCol { get => _sTDClosingCostFinancedDidChangeCol; set => SetField(ref _sTDClosingCostFinancedDidChangeCol, value); } /// <summary> /// STD Deposit Did Change Col [CD3.X114] /// </summary> public string? STDDepositDidChangeCol { get => _sTDDepositDidChangeCol; set => SetField(ref _sTDDepositDidChangeCol, value); } /// <summary> /// STD Deposit IncDec Remark [CD3.X126] /// </summary> public StringEnumValue<IncreasedOrDecreased> STDDepositIncDecRemark { get => _sTDDepositIncDecRemark; set => SetField(ref _sTDDepositIncDecRemark, value); } /// <summary> /// STD Down Payment Did Change Col [CD3.X113] /// </summary> public string? STDDownPaymentDidChangeCol { get => _sTDDownPaymentDidChangeCol; set => SetField(ref _sTDDownPaymentDidChangeCol, value); } /// <summary> /// STD Down Payment IncDec Remark [CD3.X124] /// </summary> public StringEnumValue<IncreasedOrDecreased> STDDownPaymentIncDecRemark { get => _sTDDownPaymentIncDecRemark; set => SetField(ref _sTDDownPaymentIncDecRemark, value); } /// <summary> /// STD Down Payment Section Remark [CD3.X125] /// </summary> public StringEnumValue<STDDownPaymentSectionRemark> STDDownPaymentSectionRemark { get => _sTDDownPaymentSectionRemark; set => SetField(ref _sTDDownPaymentSectionRemark, value); } /// <summary> /// STD Final Adjustment And Other Credits [CD3.X109] /// </summary> public decimal? STDFinalAdjustmentAndOtherCredits { get => _sTDFinalAdjustmentAndOtherCredits; set => SetField(ref _sTDFinalAdjustmentAndOtherCredits, value); } /// <summary> /// STD Final Cash To Close [CD3.X110] /// </summary> public decimal? STDFinalCashToClose { get => _sTDFinalCashToClose; set => SetField(ref _sTDFinalCashToClose, value); } /// <summary> /// STD Final CD3 Closing Costs Paid Before Closing [CD3.X103] /// </summary> public decimal? STDFinalCD3ClosingCostsPaidBeforeClosing { get => _sTDFinalCD3ClosingCostsPaidBeforeClosing; set => SetField(ref _sTDFinalCD3ClosingCostsPaidBeforeClosing, value); } /// <summary> /// STD Final Closing Cost Financed [CD3.X104] /// </summary> public decimal? STDFinalClosingCostFinanced { get => _sTDFinalClosingCostFinanced; set => SetField(ref _sTDFinalClosingCostFinanced, value); } /// <summary> /// STD Final Deposit [CD3.X106] /// </summary> public decimal? STDFinalDeposit { get => _sTDFinalDeposit; set => SetField(ref _sTDFinalDeposit, value); } /// <summary> /// STD Final Down Payment [CD3.X105] /// </summary> public decimal? STDFinalDownPayment { get => _sTDFinalDownPayment; set => SetField(ref _sTDFinalDownPayment, value); } /// <summary> /// STD Final Fund For Borrower [CD3.X107] /// </summary> public decimal? STDFinalFundForBorrower { get => _sTDFinalFundForBorrower; set => SetField(ref _sTDFinalFundForBorrower, value); } /// <summary> /// STD Final Seller Credits [CD3.X108] /// </summary> public decimal? STDFinalSellerCredits { get => _sTDFinalSellerCredits; set => SetField(ref _sTDFinalSellerCredits, value); } /// <summary> /// STD Final Total Closing Cost J [CD3.X102] /// </summary> public decimal? STDFinalTotalClosingCostJ { get => _sTDFinalTotalClosingCostJ; set => SetField(ref _sTDFinalTotalClosingCostJ, value); } /// <summary> /// STD Funds for Borrower Did Change Col [CD3.X115] /// </summary> public string? STDFundsForBorrowerDidChangeCol { get => _sTDFundsForBorrowerDidChangeCol; set => SetField(ref _sTDFundsForBorrowerDidChangeCol, value); } /// <summary> /// STD Funds For Borrower IncDec Remark [CD3.X127] /// </summary> public StringEnumValue<IncreasedOrDecreased> STDFundsForBorrowerIncDecRemark { get => _sTDFundsForBorrowerIncDecRemark; set => SetField(ref _sTDFundsForBorrowerIncDecRemark, value); } /// <summary> /// STD LE Adjustmen And Other Credits [CD3.X100] /// </summary> public decimal? STDLEAdjustmentAndOtherCredits { get => _sTDLEAdjustmentAndOtherCredits; set => SetField(ref _sTDLEAdjustmentAndOtherCredits, value); } /// <summary> /// STD LE Cash To Close [CD3.X101] /// </summary> public decimal? STDLECashToClose { get => _sTDLECashToClose; set => SetField(ref _sTDLECashToClose, value); } /// <summary> /// STD LE CD3 Closing Costs Paid Before Closing [CD3.X94] /// </summary> public decimal? STDLECD3ClosingCostsPaidBeforeClosing { get => _sTDLECD3ClosingCostsPaidBeforeClosing; set => SetField(ref _sTDLECD3ClosingCostsPaidBeforeClosing, value); } /// <summary> /// STD LE Closing Cost Financed [CD3.X95] /// </summary> public decimal? STDLEClosingCostFinanced { get => _sTDLEClosingCostFinanced; set => SetField(ref _sTDLEClosingCostFinanced, value); } /// <summary> /// STD LE Deposit [CD3.X97] /// </summary> public decimal? STDLEDeposit { get => _sTDLEDeposit; set => SetField(ref _sTDLEDeposit, value); } /// <summary> /// STD LE Down Payment [CD3.X96] /// </summary> public decimal? STDLEDownPayment { get => _sTDLEDownPayment; set => SetField(ref _sTDLEDownPayment, value); } /// <summary> /// STD LE Fund For Borrower [CD3.X98] /// </summary> public decimal? STDLEFundForBorrower { get => _sTDLEFundForBorrower; set => SetField(ref _sTDLEFundForBorrower, value); } /// <summary> /// Tolerance Cure [CD3.X129] /// </summary> public decimal? STDLegalLimit { get => _sTDLegalLimit; set => SetField(ref _sTDLegalLimit, value); } /// <summary> /// STD LE Seller Credits [CD3.X99] /// </summary> public decimal? STDLESellerCredits { get => _sTDLESellerCredits; set => SetField(ref _sTDLESellerCredits, value); } /// <summary> /// STD LE Total Closing Cost J [CD3.X93] /// </summary> public decimal? STDLETotalClosingCostJ { get => _sTDLETotalClosingCostJ; set => SetField(ref _sTDLETotalClosingCostJ, value); } /// <summary> /// STD Seller Credits Did Change Col [CD3.X116] /// </summary> public string? STDSellerCreditsDidChangeCol { get => _sTDSellerCreditsDidChangeCol; set => SetField(ref _sTDSellerCreditsDidChangeCol, value); } /// <summary> /// STD Seller Credits IncDec Remark [CD3.X128] /// </summary> public StringEnumValue<IncreasedOrDecreased> STDSellerCreditsIncDecRemark { get => _sTDSellerCreditsIncDecRemark; set => SetField(ref _sTDSellerCreditsIncDecRemark, value); } /// <summary> /// STD Total Closing Cost Before CLosing Did Change Col [CD3.X112] /// </summary> public string? STDTotalClosingCostBeforeClosingDidChangeCol { get => _sTDTotalClosingCostBeforeClosingDidChangeCol; set => SetField(ref _sTDTotalClosingCostBeforeClosingDidChangeCol, value); } /// <summary> /// STD Total Closing Cost Did Change Col [CD3.X111] /// </summary> public string? STDTotalClosingCostDidChangeCol { get => _sTDTotalClosingCostDidChangeCol; set => SetField(ref _sTDTotalClosingCostDidChangeCol, value); } /// <summary> /// STD Total Closing Cost Remark [CD3.X123] /// </summary> public StringEnumValue<TotalClosingCostRemark> STDTotalClosingCostRemark { get => _sTDTotalClosingCostRemark; set => SetField(ref _sTDTotalClosingCostRemark, value); } /// <summary> /// Total Adjustments And Other Credits [CD3.X1506] /// </summary> public decimal? TotalAdjustmentsAndOtherCredits { get => _totalAdjustmentsAndOtherCredits; set => SetField(ref _totalAdjustmentsAndOtherCredits, value); } /// <summary> /// Total Due from Borrower At Closing [CD3.X21] /// </summary> public decimal? TotalDuefromBorrowerAtClosing { get => _totalDuefromBorrowerAtClosing; set => SetField(ref _totalDuefromBorrowerAtClosing, value); } /// <summary> /// Total Due from Seller at Closing N [CD3.X39] /// </summary> public decimal? TotalDuefromSelleratClosingN { get => _totalDuefromSelleratClosingN; set => SetField(ref _totalDuefromSelleratClosingN, value); } /// <summary> /// Total Due to Seller at Closing M [CD3.X38] /// </summary> public decimal? TotalDuetoSelleratClosingM { get => _totalDuetoSelleratClosingM; set => SetField(ref _totalDuetoSelleratClosingM, value); } /// <summary> /// Total From K [CD3.X41] /// </summary> public decimal? TotalFromK { get => _totalFromK; set => SetField(ref _totalFromK, value); } /// <summary> /// Total From L [CD3.X42] /// </summary> public decimal? TotalFromL { get => _totalFromL; set => SetField(ref _totalFromL, value); } /// <summary> /// Total From M [CD3.X43] /// </summary> public decimal? TotalFromM { get => _totalFromM; set => SetField(ref _totalFromM, value); } /// <summary> /// Total From N [CD3.X44] /// </summary> public decimal? TotalFromN { get => _totalFromN; set => SetField(ref _totalFromN, value); } /// <summary> /// Total Paid Already by or on Behalf of Borower at Closing [CD3.X22] /// </summary> public decimal? TotalPaidAlreadybyoronBehalfofBoroweratClosing { get => _totalPaidAlreadybyoronBehalfofBoroweratClosing; set => SetField(ref _totalPaidAlreadybyoronBehalfofBoroweratClosing, value); } /// <summary> /// Total Purchase Payoffs Included [CD3.X1543] /// </summary> public decimal? TotalPurchasePayoffsIncluded { get => _totalPurchasePayoffsIncluded; set => SetField(ref _totalPurchasePayoffsIncluded, value); } /// <summary> /// ClosingDisclosure3 UCDDetails /// </summary> [AllowNull] public IList<UCDDetail> UCDDetails { get => GetField(ref _uCDDetails); set => SetField(ref _uCDDetails, value); } /// <summary> /// UCD K Line Subtotal [CD3.X1502] /// </summary> public decimal? UCDKSubTotal { get => _uCDKSubTotal; set => SetField(ref _uCDKSubTotal, value); } /// <summary> /// UCD K Line Subtotal [CD3.X1503] /// </summary> public decimal? UCDLSubTotal { get => _uCDLSubTotal; set => SetField(ref _uCDLSubTotal, value); } /// <summary> /// UCD Total Adjustments And Other Credits [CD3.X1504] /// </summary> public decimal? UCDTotalAdjustmentsAndOtherCredits { get => _uCDTotalAdjustmentsAndOtherCredits; set => SetField(ref _uCDTotalAdjustmentsAndOtherCredits, value); } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using KnxNetCore.Knx.Telegrams; namespace KnxNetCore.Knx { internal class Serializer { // TODO: accept cEMI protocol only. // TODO: Do not accept extended frames. private static readonly Dictionary<ushort, Func<KnxTelegramHeader, byte[], KnxTelegramPayload>> PayloadFactories = new Dictionary<ushort, Func<KnxTelegramHeader, byte[], KnxTelegramPayload>> { {0x206, ParseConnectResponse}, {0x208, ParseConnectionStateResponse}, {0x209, ParseDisconnectRequest}, {0x420, ParseTunnelingRequest}, {0x421, ParseTunnelingAcknowledge} }; public static void Serialize(KnxTelegramHeader knxTelegramHeader, MemoryStream stream) { stream.WriteByte(knxTelegramHeader.HeaderLength); stream.WriteByte(knxTelegramHeader.ProtocolVersion); stream.WriteByte((byte)(knxTelegramHeader.ServiceType >> 8)); stream.WriteByte((byte)(knxTelegramHeader.ServiceType & 255)); stream.WriteByte((byte)(knxTelegramHeader.TotalLength >> 8)); stream.WriteByte((byte)(knxTelegramHeader.TotalLength & 255)); } public static void Serialize(KnxConnectRequest knxConnectRequest, MemoryStream stream) { stream.SetLength(0); stream.Seek(6, SeekOrigin.Begin); Serialize(knxConnectRequest.IpEndPoint, stream); Serialize(knxConnectRequest.IpEndPoint, stream); stream.WriteByte(4); stream.WriteByte(4); stream.WriteByte(2); stream.WriteByte(0); stream.Seek(0, SeekOrigin.Begin); var header = new KnxTelegramHeader(6, 0x10, 0x205, (ushort)stream.Length); Serialize(header, stream); } public static void Serialize(KnxConnectionStateRequest knxConnectionStateRequest, MemoryStream stream) { stream.SetLength(0); stream.Seek(6, SeekOrigin.Begin); stream.WriteByte(knxConnectionStateRequest.ChannelId); stream.WriteByte(0); Serialize(knxConnectionStateRequest.EndPoint, stream); stream.Seek(0, SeekOrigin.Begin); var header = new KnxTelegramHeader(6, 0x10, 0x207, (ushort)stream.Length); Serialize(header, stream); } public static void Serialize(KnxTunnelingRequest knxTunnelingRequest, MemoryStream memoryStream) { memoryStream.SetLength(0); memoryStream.Seek(6, SeekOrigin.Begin); SerializeCommonConnectionHeader(knxTunnelingRequest.ChannelId, knxTunnelingRequest.SequenceNumber, memoryStream); Serialize(knxTunnelingRequest.CemiFrame, memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); var header = new KnxTelegramHeader(6, 0x10, 0x420, (ushort)memoryStream.Length); Serialize(header, memoryStream); } private static void SerializeCommonConnectionHeader(byte channelId, byte sequenceNumber, MemoryStream memoryStream) { memoryStream.WriteByte(4); // Length memoryStream.WriteByte(channelId); memoryStream.WriteByte(sequenceNumber); memoryStream.WriteByte(0); // Reserved } public static void Serialize(KnxTunnelingAcknowledge knxTunnelingAcknowledge, MemoryStream memoryStream) { memoryStream.SetLength(0); memoryStream.Seek(6, SeekOrigin.Begin); SerializeCommonConnectionHeader(knxTunnelingAcknowledge.ChannelId, knxTunnelingAcknowledge.SequenceNumber, memoryStream); memoryStream.Seek(0, SeekOrigin.Begin); var header = new KnxTelegramHeader(6, 0x10, 0x421, (ushort)memoryStream.Length); Serialize(header, memoryStream); } public static void Serialize(CemiFrame cemiFrame, MemoryStream memoryStream) { memoryStream.WriteByte((byte)cemiFrame.MessageCode); memoryStream.WriteByte(0); // No additional data memoryStream.WriteByte((byte)cemiFrame.Control1); memoryStream.WriteByte((byte)cemiFrame.Control2); memoryStream.WriteByte(0); // Source Address will be filled out by gateway memoryStream.WriteByte(0); var destinationAddressAsUShort = cemiFrame.DestinationAddress.AsUShort; memoryStream.WriteByte((byte)(destinationAddressAsUShort >> 8)); memoryStream.WriteByte((byte)(destinationAddressAsUShort & 255)); memoryStream.WriteByte(cemiFrame.DataLength); memoryStream.WriteByte((byte)(cemiFrame.Apdu >> 8)); memoryStream.WriteByte((byte)cemiFrame.Apdu); if (cemiFrame.Data.Count != 0) { memoryStream.Write(cemiFrame.Data.Array, cemiFrame.Data.Offset, cemiFrame.Data.Count); } } public static void Serialize(IPEndPoint ipEndPoint, MemoryStream stream) { // Serialize "Host Protocol Address Information" (HPAI) if (ipEndPoint.Address.GetAddressBytes().Length != 4) { throw new ArgumentException(string.Format("Cannot serialize IP Address {0}", ipEndPoint.Address)); } stream.WriteByte(8); // Length stream.WriteByte(1); // Protocol Type stream.Write(ipEndPoint.Address.GetAddressBytes(), 0, 4); stream.WriteByte((byte)(ipEndPoint.Port >> 8)); stream.WriteByte((byte)ipEndPoint.Port); } private static ushort ToUInt16(byte[] buffer, int startIndex) { return (ushort)((buffer[startIndex] << 8) + buffer[startIndex + 1]); } internal static KnxTelegramHeader ParseKnxTelegramHeader(byte[] buffer) { if (buffer.Length < 6) { throw new ArgumentException(string.Format("Supplied buffer smaller than required header size ({0})", buffer.Length)); } var knxTelegram = new KnxTelegramHeader(buffer[0], buffer[1], ToUInt16(buffer, 2), ToUInt16(buffer, 4)); if (knxTelegram.HeaderLength != 6) { throw new ArgumentException(string.Format("Header length is not 6 but {0}", knxTelegram.HeaderLength)); } if (knxTelegram.ProtocolVersion != 0x10) { throw new ArgumentException(string.Format("ProtocolVersion is not 0x10 but {0}", knxTelegram.ProtocolVersion)); } return knxTelegram; } internal static KnxTelegramPayload ParseKnxTelegram(KnxTelegramHeader header, byte[] buffer) { if (!PayloadFactories.ContainsKey(header.ServiceType)) { throw new ArgumentException(string.Format("Do not know how to deserialize service type: {0}", header.ServiceType)); } return PayloadFactories[header.ServiceType](header, buffer); } private static KnxTelegramPayload ParseDisconnectRequest(KnxTelegramHeader arg1, byte[] arg2) { if (arg2.Length < 8) { throw new ArgumentException(string.Format("Supplied buffer smaller than required size ({0})", arg2.Length)); } return new KnxDisconnectRequest(arg2[6], arg2[7]); } private static KnxTelegramPayload ParseTunnelingRequest(KnxTelegramHeader arg1, byte[] arg2) { var dataLength = arg2[18] & 15; var cemiFrame = new CemiFrame( (CemiFrame.MessageCodes) arg2[10], (CemiFrame.Control1Flags)arg2[12], (CemiFrame.Control2Flags)arg2[13], IndividualAddress.FromUShort((ushort)((arg2[14] << 8) + arg2[15])), GroupAddress.FromUShort((ushort)((arg2[16] << 8) + arg2[17])), arg2[18], (ushort)((arg2[19] << 8) + arg2[20]), new ArraySegment<byte>(arg2, 21, dataLength == 0 ? 0 : dataLength - 1)); // protect against unknown datagrams with datalength = 0 return new KnxTunnelingRequest(arg2[7], arg2[8], cemiFrame); } private static KnxTelegramPayload ParseTunnelingAcknowledge(KnxTelegramHeader arg1, byte[] arg2) { if (arg2.Length < 8) { throw new ArgumentException(string.Format("Supplied buffer smaller than required size ({0})", arg2.Length)); } return new KnxTunnelingAcknowledge(arg2[7], arg2[8]); } private static KnxTelegramPayload ParseConnectionStateResponse(KnxTelegramHeader arg1, byte[] arg2) { if (arg2.Length < 8) { throw new ArgumentException(string.Format("Supplied buffer smaller than required size ({0})", arg2.Length)); } return new KnxConnectionStateResponse(arg2[6], (KnxConnectionStateResponse.StatusCodes)arg2[7]); } private static KnxTelegramPayload ParseConnectResponse(KnxTelegramHeader arg1, byte[] arg2) { if (arg2.Length < 8) { throw new ArgumentException(string.Format("Supplied buffer smaller than required size ({0})", arg2.Length)); } return new KnxConnectResponse(arg2[6], (KnxConnectResponse.StatusCodes)arg2[7]); } } }
/* * 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 Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Services.Connectors.SimianGrid; using OpenSim.Services.Interfaces; using System; using System.Collections.Generic; using System.Reflection; namespace OpenSim.Services.Connectors { public class HGAssetServiceConnector : IAssetService { private static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); private Dictionary<string, IAssetService> m_connectors = new Dictionary<string, IAssetService>(); private Dictionary<IAssetService, object> m_endpointSerializer = new Dictionary<IAssetService, object>(); public HGAssetServiceConnector(IConfigSource source) { IConfig moduleConfig = source.Configs["Modules"]; if (moduleConfig != null) { // string name = moduleConfig.GetString("AssetServices", ""); IConfig assetConfig = source.Configs["AssetService"]; if (assetConfig == null) { m_log.Error("[HG ASSET SERVICE]: AssetService missing from OpenSim.ini"); return; } m_log.Info("[HG ASSET SERVICE]: HG asset service enabled"); } } public virtual bool[] AssetsExist(string[] ids) { // This method is a bit complicated because it works even if the assets belong to different // servers; that requires sending separate requests to each server. // Group the assets by the server they belong to var url2assets = new Dictionary<string, List<AssetAndIndex>>(); for (int i = 0; i < ids.Length; i++) { string url = string.Empty; string assetID = string.Empty; if (Util.ParseForeignAssetID(ids[i], out url, out assetID)) { if (!url2assets.ContainsKey(url)) url2assets.Add(url, new List<AssetAndIndex>()); url2assets[url].Add(new AssetAndIndex(UUID.Parse(assetID), i)); } } // Query each of the servers in turn bool[] exist = new bool[ids.Length]; foreach (string url in url2assets.Keys) { IAssetService connector = GetConnector(url); lock (EndPointLock(connector)) { List<AssetAndIndex> curAssets = url2assets[url]; string[] assetIDs = curAssets.ConvertAll(a => a.assetID.ToString()).ToArray(); bool[] curExist = connector.AssetsExist(assetIDs); int i = 0; foreach (AssetAndIndex ai in curAssets) { exist[ai.index] = curExist[i]; ++i; } } } return exist; } public bool Delete(string id) { return false; } public AssetBase Get(string id) { string url = string.Empty; string assetID = string.Empty; if (Util.ParseForeignAssetID(id, out url, out assetID)) { IAssetService connector = GetConnector(url); return connector.Get(assetID); } return null; } public bool Get(string id, Object sender, AssetRetrieved handler) { string url = string.Empty; string assetID = string.Empty; if (Util.ParseForeignAssetID(id, out url, out assetID)) { IAssetService connector = GetConnector(url); return connector.Get(assetID, sender, handler); } return false; } public AssetBase GetCached(string id) { string url = string.Empty; string assetID = string.Empty; if (Util.ParseForeignAssetID(id, out url, out assetID)) { IAssetService connector = GetConnector(url); return connector.GetCached(assetID); } return null; } public byte[] GetData(string id) { return null; } public AssetMetadata GetMetadata(string id) { string url = string.Empty; string assetID = string.Empty; if (Util.ParseForeignAssetID(id, out url, out assetID)) { IAssetService connector = GetConnector(url); return connector.GetMetadata(assetID); } return null; } public string Store(AssetBase asset) { string url = string.Empty; string assetID = string.Empty; if (Util.ParseForeignAssetID(asset.ID, out url, out assetID)) { IAssetService connector = GetConnector(url); // Restore the assetID to a simple UUID asset.ID = assetID; lock (EndPointLock(connector)) return connector.Store(asset); } return String.Empty; } public bool UpdateContent(string id, byte[] data) { return false; } private object EndPointLock(IAssetService connector) { lock (m_endpointSerializer) { object eplock = null; if (!m_endpointSerializer.TryGetValue(connector, out eplock)) { eplock = new object(); m_endpointSerializer.Add(connector, eplock); // m_log.WarnFormat("[WEB UTIL] add a new host to end point serializer {0}",endpoint); } return eplock; } } private IAssetService GetConnector(string url) { IAssetService connector = null; lock (m_connectors) { if (m_connectors.ContainsKey(url)) { connector = m_connectors[url]; } else { // Still not as flexible as I would like this to be, // but good enough for now string connectorType = new HeloServicesConnector(url).Helo(); m_log.DebugFormat("[HG ASSET SERVICE]: HELO returned {0}", connectorType); if (connectorType == "opensim-simian") { connector = new SimianAssetServiceConnector(url); } else connector = new AssetServicesConnector(url); m_connectors.Add(url, connector); } } return connector; } private struct AssetAndIndex { public UUID assetID; public int index; public AssetAndIndex(UUID assetID, int index) { this.assetID = assetID; this.index = index; } } } }
// 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.Diagnostics; using System.Linq; using System.Reflection; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableSortedDictionaryBuilderTest : ImmutableDictionaryBuilderTestBase { [Fact] public void CreateBuilder() { var builder = ImmutableSortedDictionary.CreateBuilder<string, string>(); Assert.NotNull(builder); builder = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal); Assert.Same(StringComparer.Ordinal, builder.KeyComparer); Assert.Same(EqualityComparer<string>.Default, builder.ValueComparer); builder = ImmutableSortedDictionary.CreateBuilder<string, string>(StringComparer.Ordinal, StringComparer.OrdinalIgnoreCase); Assert.Same(StringComparer.Ordinal, builder.KeyComparer); Assert.Same(StringComparer.OrdinalIgnoreCase, builder.ValueComparer); } [Fact] public void ToBuilder() { var builder = ImmutableSortedDictionary<int, string>.Empty.ToBuilder(); builder.Add(3, "3"); builder.Add(5, "5"); Assert.Equal(2, builder.Count); Assert.True(builder.ContainsKey(3)); Assert.True(builder.ContainsKey(5)); Assert.False(builder.ContainsKey(7)); var set = builder.ToImmutable(); Assert.Equal(builder.Count, set.Count); builder.Add(8, "8"); Assert.Equal(3, builder.Count); Assert.Equal(2, set.Count); Assert.True(builder.ContainsKey(8)); Assert.False(set.ContainsKey(8)); } [Fact] public void BuilderFromMap() { var set = ImmutableSortedDictionary<int, string>.Empty.Add(1, "1"); var builder = set.ToBuilder(); Assert.True(builder.ContainsKey(1)); builder.Add(3, "3"); builder.Add(5, "5"); Assert.Equal(3, builder.Count); Assert.True(builder.ContainsKey(3)); Assert.True(builder.ContainsKey(5)); Assert.False(builder.ContainsKey(7)); var set2 = builder.ToImmutable(); Assert.Equal(builder.Count, set2.Count); Assert.True(set2.ContainsKey(1)); builder.Add(8, "8"); Assert.Equal(4, builder.Count); Assert.Equal(3, set2.Count); Assert.True(builder.ContainsKey(8)); Assert.False(set.ContainsKey(8)); Assert.False(set2.ContainsKey(8)); } [Fact] public void SeveralChanges() { var mutable = ImmutableSortedDictionary<int, string>.Empty.ToBuilder(); var immutable1 = mutable.ToImmutable(); Assert.Same(immutable1, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); mutable.Add(1, "a"); var immutable2 = mutable.ToImmutable(); Assert.NotSame(immutable1, immutable2); //, "Mutating the collection did not reset the Immutable property."); Assert.Same(immutable2, mutable.ToImmutable()); //, "The Immutable property getter is creating new objects without any differences."); Assert.Equal(1, immutable2.Count); } [Fact] public void AddRange() { var builder = ImmutableSortedDictionary.Create<string, int>().ToBuilder(); builder.AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 } }); Assert.Equal(2, builder.Count); Assert.Equal(1, builder["a"]); Assert.Equal(2, builder["b"]); } [Fact] public void RemoveRange() { var builder = ImmutableSortedDictionary.Create<string, int>() .AddRange(new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } }) .ToBuilder(); Assert.Equal(3, builder.Count); builder.RemoveRange(new[] { "a", "b" }); Assert.Equal(1, builder.Count); Assert.Equal(3, builder["c"]); } [Fact] public void EnumerateBuilderWhileMutating() { var builder = ImmutableSortedDictionary<int, string>.Empty .AddRange(Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null))) .ToBuilder(); Assert.Equal( Enumerable.Range(1, 10).Select(n => new KeyValuePair<int, string>(n, null)), builder); var enumerator = builder.GetEnumerator(); Assert.True(enumerator.MoveNext()); builder.Add(11, null); // Verify that a new enumerator will succeed. Assert.Equal( Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)), builder); // Try enumerating further with the previous enumerable now that we've changed the collection. Assert.Throws<InvalidOperationException>(() => enumerator.MoveNext()); enumerator.Reset(); enumerator.MoveNext(); // resetting should fix the problem. // Verify that by obtaining a new enumerator, we can enumerate all the contents. Assert.Equal( Enumerable.Range(1, 11).Select(n => new KeyValuePair<int, string>(n, null)), builder); } [Fact] public void BuilderReusesUnchangedImmutableInstances() { var collection = ImmutableSortedDictionary<int, string>.Empty.Add(1, null); var builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // no changes at all. builder.Add(2, null); var newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. collection = collection.Clear(); // now start with an empty collection builder = collection.ToBuilder(); Assert.Same(collection, builder.ToImmutable()); // again, no changes at all. builder.ValueComparer = StringComparer.OrdinalIgnoreCase; // now, force the builder to clear its cache newImmutable = builder.ToImmutable(); Assert.NotSame(collection, newImmutable); // first ToImmutable with changes should be a new instance. Assert.Same(newImmutable, builder.ToImmutable()); // second ToImmutable without changes should be the same instance. } [Fact] public void ContainsValue() { var map = ImmutableSortedDictionary.Create<string, int>().Add("five", 5); var builder = map.ToBuilder(); Assert.True(builder.ContainsValue(5)); Assert.False(builder.ContainsValue(4)); } [Fact] public void Clear() { var builder = ImmutableSortedDictionary.Create<string, int>().ToBuilder(); builder.Add("five", 5); Assert.Equal(1, builder.Count); builder.Clear(); Assert.Equal(0, builder.Count); } [Fact] public void KeyComparer() { var builder = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("B", "1").ToBuilder(); Assert.Same(Comparer<string>.Default, builder.KeyComparer); Assert.True(builder.ContainsKey("a")); Assert.False(builder.ContainsKey("A")); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); Assert.Equal(2, builder.Count); Assert.True(builder.ContainsKey("a")); Assert.True(builder.ContainsKey("A")); Assert.True(builder.ContainsKey("b")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.True(set.ContainsKey("a")); Assert.True(set.ContainsKey("A")); Assert.True(set.ContainsKey("b")); } [Fact] public void KeyComparerCollisions() { // First check where collisions have matching values. var builder = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "1").ToBuilder(); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Equal(1, builder.Count); Assert.True(builder.ContainsKey("a")); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); Assert.Equal(1, set.Count); Assert.True(set.ContainsKey("a")); // Now check where collisions have conflicting values. builder = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("A", "2").Add("b", "3").ToBuilder(); AssertExtensions.Throws<ArgumentException>(null, () => builder.KeyComparer = StringComparer.OrdinalIgnoreCase); // Force all values to be considered equal. builder.ValueComparer = EverythingEqual<string>.Default; Assert.Same(EverythingEqual<string>.Default, builder.ValueComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; // should not throw because values will be seen as equal. Assert.Equal(2, builder.Count); Assert.True(builder.ContainsKey("a")); Assert.True(builder.ContainsKey("b")); } [Fact] public void KeyComparerEmptyCollection() { var builder = ImmutableSortedDictionary.Create<string, string>() .Add("a", "1").Add("B", "1").ToBuilder(); Assert.Same(Comparer<string>.Default, builder.KeyComparer); builder.KeyComparer = StringComparer.OrdinalIgnoreCase; Assert.Same(StringComparer.OrdinalIgnoreCase, builder.KeyComparer); var set = builder.ToImmutable(); Assert.Same(StringComparer.OrdinalIgnoreCase, set.KeyComparer); } [Fact] public void GetValueOrDefaultOfConcreteType() { var empty = ImmutableSortedDictionary.Create<string, int>().ToBuilder(); var populated = ImmutableSortedDictionary.Create<string, int>().Add("a", 5).ToBuilder(); Assert.Equal(0, empty.GetValueOrDefault("a")); Assert.Equal(1, empty.GetValueOrDefault("a", 1)); Assert.Equal(5, populated.GetValueOrDefault("a")); Assert.Equal(5, populated.GetValueOrDefault("a", 1)); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableSortedDictionary.CreateBuilder<string, int>()); ImmutableSortedDictionary<int, string>.Builder builder = ImmutableSortedDictionary.CreateBuilder<int, string>(); builder.Add(1, "One"); builder.Add(2, "Two"); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); KeyValuePair<int, string>[] items = itemProperty.GetValue(info.Instance) as KeyValuePair<int, string>[]; Assert.Equal(builder, items); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(ImmutableSortedDictionary.CreateBuilder<int, string>()); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); } protected override IImmutableDictionary<TKey, TValue> GetEmptyImmutableDictionary<TKey, TValue>() { return ImmutableSortedDictionary.Create<TKey, TValue>(); } protected override IImmutableDictionary<string, TValue> Empty<TValue>(StringComparer comparer) { return ImmutableSortedDictionary.Create<string, TValue>(comparer); } protected override bool TryGetKeyHelper<TKey, TValue>(IDictionary<TKey, TValue> dictionary, TKey equalKey, out TKey actualKey) { return ((ImmutableSortedDictionary<TKey, TValue>.Builder)dictionary).TryGetKey(equalKey, out actualKey); } protected override IDictionary<TKey, TValue> GetBuilder<TKey, TValue>(IImmutableDictionary<TKey, TValue> basis) { return ((ImmutableSortedDictionary<TKey, TValue>)(basis ?? GetEmptyImmutableDictionary<TKey, TValue>())).ToBuilder(); } } }
//------------------------------------------------------------------------------ // <copyright file="SiteMapNode.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /* * SiteMapNode class definition * * Copyright (c) 2002 Microsoft Corporation */ namespace System.Web { using System; using System.Configuration.Provider; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Resources; using System.Security.Permissions; using System.Web.Configuration; using System.Web.Compilation; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Util; /// <devdoc> /// <para></para> /// </devdoc> public class SiteMapNode : ICloneable, IHierarchyData, INavigateUIData { private static readonly string _siteMapNodeType = typeof(SiteMapNode).Name; private SiteMapProvider _provider; private bool _readonly; private bool _parentNodeSet; private bool _childNodesSet; private VirtualPath _virtualPath; private string _title; private string _description; private string _url; private string _key; private string _resourceKey; private IList _roles; private NameValueCollection _attributes; private NameValueCollection _resourceKeys; private SiteMapNode _parentNode; private SiteMapNodeCollection _childNodes; public SiteMapNode(SiteMapProvider provider, string key) : this(provider, key, null, null, null, null, null, null, null) { } public SiteMapNode(SiteMapProvider provider, string key, string url) : this(provider, key, url, null, null, null, null, null, null) { } public SiteMapNode(SiteMapProvider provider, string key, string url, string title) : this(provider, key, url, title, null, null, null, null, null) { } public SiteMapNode(SiteMapProvider provider, string key, string url, string title, string description) : this(provider, key, url, title, description, null, null, null, null) { } public SiteMapNode(SiteMapProvider provider, string key, string url, string title, string description, IList roles, NameValueCollection attributes, NameValueCollection explicitResourceKeys, string implicitResourceKey) { _provider = provider; _title = title; _description = description; _roles = roles; _attributes = attributes; _key = key; _resourceKeys = explicitResourceKeys; _resourceKey = implicitResourceKey; if (url != null) { _url = url.Trim(); } _virtualPath = CreateVirtualPathFromUrl(_url); if (_key == null) { throw new ArgumentNullException("key"); } if (_provider == null) { throw new ArgumentNullException("provider"); } } protected NameValueCollection Attributes { get { return _attributes; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "Attributes")); } _attributes = value; } } // Access custom attributes. public virtual string this[string key] { get { string text = null; if (_attributes != null) { text = _attributes[key]; } if (_provider.EnableLocalization) { // Try the implicit resource first string localizedText = GetImplicitResourceString(key); if (localizedText != null) { return localizedText; } // If not found, try the explicit resource. localizedText = GetExplicitResourceString(key, text, true); if (localizedText != null) { return localizedText; } } return text; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "Item")); } if (_attributes == null) { _attributes = new NameValueCollection(); } _attributes[key] = value; } } public virtual SiteMapNodeCollection ChildNodes { get { if (_childNodesSet) return _childNodes; return _provider.GetChildNodes(this); } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "ChildNodes")); } _childNodes = value; _childNodesSet = true; } } [ Localizable(true) ] public virtual string Description { get { if (_provider.EnableLocalization) { string localizedText = GetImplicitResourceString("description"); if (localizedText != null) { return localizedText; } localizedText = GetExplicitResourceString("description", _description, true); if (localizedText != null) { return localizedText; } } return _description == null? String.Empty : _description; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "Description")); } _description = value; } } public string Key { get { return _key; } } public virtual bool HasChildNodes { get { IList children = ChildNodes; return children != null && children.Count > 0; } } public virtual SiteMapNode NextSibling { get { IList siblings = SiblingNodes; if (siblings == null) { return null; } int index = siblings.IndexOf(this); if (index >= 0 && index < siblings.Count - 1) { return (SiteMapNode)siblings[index + 1]; } return null; } } // Get parent node. If not found in current provider, search recursively in parent providers. public virtual SiteMapNode ParentNode { get { if (_parentNodeSet) return _parentNode; return _provider.GetParentNode(this); } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "ParentNode")); } _parentNode = value; _parentNodeSet = true; } } public virtual SiteMapNode PreviousSibling { get { IList siblings = SiblingNodes; if (siblings == null) { return null; } int index = siblings.IndexOf(this); if (index > 0 && index <= siblings.Count - 1) { return (SiteMapNode)siblings[index - 1]; } return null; } } public SiteMapProvider Provider { get { return _provider; } } public bool ReadOnly { get { return _readonly; } set { _readonly = value; } } public String ResourceKey { get { return _resourceKey; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "ResourceKey")); } _resourceKey = value; } } public IList Roles { get { return _roles; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "Roles")); } _roles = value; } } public virtual SiteMapNode RootNode { get { SiteMapNode root = _provider.RootProvider.RootNode; if (root == null) { String name = ((ProviderBase)_provider.RootProvider).Name; throw new InvalidOperationException(SR.GetString(SR.SiteMapProvider_Invalid_RootNode, name)); } return root; } } private SiteMapNodeCollection SiblingNodes { get { SiteMapNode parent = ParentNode; return parent == null? null : parent.ChildNodes; } } [ Localizable(true) ] public virtual string Title { get { if (_provider.EnableLocalization) { string localizedText = GetImplicitResourceString("title"); if (localizedText != null) { return localizedText; } localizedText = GetExplicitResourceString("title", _title, true); if (localizedText != null) { return localizedText; } } return _title == null? String.Empty : _title; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "Title")); } _title = value; } } public virtual string Url { get { return _url == null? String.Empty : _url; } set { if (_readonly) { throw new InvalidOperationException(SR.GetString(SR.SiteMapNode_readonly, "Url")); } if (value != null) { _url = value.Trim(); } _virtualPath = CreateVirtualPathFromUrl(_url); } } internal VirtualPath VirtualPath { get { return _virtualPath; } } private VirtualPath CreateVirtualPathFromUrl(string url) { if (String.IsNullOrEmpty(url)) { return null; } if (!UrlPath.IsValidVirtualPathWithoutProtocol(url)) { return null; } if (UrlPath.IsAbsolutePhysicalPath(url)) { return null; } // Do not generate the virtualPath class at designtime. if (HttpRuntime.AppDomainAppVirtualPath == null) { return null; } if (UrlPath.IsRelativeUrl(url) && !UrlPath.IsAppRelativePath(url)) { url = UrlPath.Combine(HttpRuntime.AppDomainAppVirtualPathString, url); } // Remove the query string from url so the path can be validated by Authorization module. int queryStringIndex = url.IndexOf('?'); if (queryStringIndex != -1) { url = url.Substring(0, queryStringIndex); } return VirtualPath.Create(url, VirtualPathOptions.AllowAbsolutePath | VirtualPathOptions.AllowAppRelativePath); } public virtual SiteMapNode Clone() { ArrayList newRoles = null; NameValueCollection newAttributes = null; NameValueCollection newResourceKeys = null; if (_roles != null) { newRoles = new ArrayList(_roles); } if (_attributes != null) { newAttributes = new NameValueCollection(_attributes); } if (_resourceKeys != null) { newResourceKeys = new NameValueCollection(_resourceKeys); } SiteMapNode newNode = new SiteMapNode(_provider, Key, Url, Title, Description, newRoles, newAttributes, newResourceKeys, _resourceKey); return newNode; } public virtual SiteMapNode Clone(bool cloneParentNodes) { SiteMapNode current = Clone(); if (cloneParentNodes) { SiteMapNode node = current; SiteMapNode parent = ParentNode; while (parent != null) { SiteMapNode cloneParent = parent.Clone(); node.ParentNode = cloneParent; cloneParent.ChildNodes = new SiteMapNodeCollection(node); parent = parent.ParentNode; node = cloneParent; } } return current; } public override bool Equals(object obj) { SiteMapNode node = obj as SiteMapNode; return node != null && (_key == node.Key) && (String.Equals(_url, node._url, StringComparison.OrdinalIgnoreCase)); } public SiteMapNodeCollection GetAllNodes() { SiteMapNodeCollection collection = new SiteMapNodeCollection(); GetAllNodesRecursive(collection); return SiteMapNodeCollection.ReadOnly(collection); } private void GetAllNodesRecursive(SiteMapNodeCollection collection) { SiteMapNodeCollection childNodes = this.ChildNodes; if (childNodes != null && childNodes.Count > 0) { collection.AddRange(childNodes); foreach(SiteMapNode node in childNodes) node.GetAllNodesRecursive(collection); } } public SiteMapDataSourceView GetDataSourceView(SiteMapDataSource owner, string viewName) { return new SiteMapDataSourceView(owner, viewName, this); } public SiteMapHierarchicalDataSourceView GetHierarchicalDataSourceView() { return new SiteMapHierarchicalDataSourceView(this); } // Helpe method to retrieve localized string based on attribute name protected string GetExplicitResourceString(string attributeName, string defaultValue, bool throwIfNotFound) { if (attributeName == null) { throw new ArgumentNullException("attributeName"); } string text = null; if (_resourceKeys != null) { string[] keys = _resourceKeys.GetValues(attributeName); if (keys != null && keys.Length > 1) { try { text = ResourceExpressionBuilder.GetGlobalResourceObject(keys[0], keys[1]) as string; } catch (MissingManifestResourceException) { if (defaultValue != null) { return defaultValue; } } if (text == null && throwIfNotFound) { // throw if default value is not specified. throw new InvalidOperationException( SR.GetString(SR.Res_not_found_with_class_and_key, keys[0], keys[1])); ; } } } return text; } // Only use the key to get the hashcode since url can be changed and makes the objects mutable. public override int GetHashCode() { return _key.GetHashCode(); } // Helper method to retrieve localized string based on attribute name protected string GetImplicitResourceString(string attributeName) { if (attributeName == null) { throw new ArgumentNullException("attributeName"); } string text = null; if (!String.IsNullOrEmpty(_resourceKey)) { try { text = ResourceExpressionBuilder.GetGlobalResourceObject(Provider.ResourceKey, ResourceKey + "." + attributeName) as String; } catch { } } return text; } public virtual bool IsAccessibleToUser(HttpContext context) { return _provider.IsAccessibleToUser(context, this); } public virtual bool IsDescendantOf(SiteMapNode node) { SiteMapNode parent = ParentNode; while (parent != null) { if (parent.Equals(node)) { return true; } parent = parent.ParentNode; } return false; } public override string ToString() { return Title; } #region ICloneable implementation /// <internalonly/> object ICloneable.Clone() { return Clone(); } #endregion #region IHierarchyData implementation /// <internalonly/> bool IHierarchyData.HasChildren { get { return HasChildNodes; } } /// <internalonly/> object IHierarchyData.Item { get { return this; } } /// <internalonly/> string IHierarchyData.Path { get { return Key; } } /// <internalonly/> string IHierarchyData.Type { get { return _siteMapNodeType; } } /// <internalonly/> IHierarchicalEnumerable IHierarchyData.GetChildren() { return ChildNodes; } /// <internalonly/> IHierarchyData IHierarchyData.GetParent() { SiteMapNode parentNode = ParentNode; if (parentNode == null) return null; return parentNode; } #endregion #region INavigateUIData implementations string INavigateUIData.Description { get { return Description; } } /// <internalonly/> string INavigateUIData.Name { get { return Title; } } /// <internalonly/> string INavigateUIData.NavigateUrl { get { return Url; } } /// <internalonly/> string INavigateUIData.Value { get { return Title; } } #endregion } }
// // Mono.System.Xml.Schema.XmlSchemaSimpleContentExtension.cs // // Author: // Dwivedi, Ajay kumar Adwiv@Yahoo.com // Atsushi Enomoto ginga@kit.hi-ho.ne.jp // // // 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 Mono.System.Xml; using Mono.System.Xml.Serialization; namespace Mono.System.Xml.Schema { /// <summary> /// Summary description for XmlSchemaSimpleContentExtension. /// </summary> public class XmlSchemaSimpleContentExtension : XmlSchemaContent { private XmlSchemaAnyAttribute any; private XmlSchemaObjectCollection attributes; private XmlQualifiedName baseTypeName; const string xmlname = "extension"; public XmlSchemaSimpleContentExtension() { baseTypeName = XmlQualifiedName.Empty; attributes = new XmlSchemaObjectCollection(); } [Mono.System.Xml.Serialization.XmlAttribute("base")] public XmlQualifiedName BaseTypeName { get{ return baseTypeName; } set{ baseTypeName = value; } } [XmlElement("attribute",typeof(XmlSchemaAttribute))] [XmlElement("attributeGroup",typeof(XmlSchemaAttributeGroupRef))] public XmlSchemaObjectCollection Attributes { get{ return attributes; } } [XmlElement("anyAttribute")] public XmlSchemaAnyAttribute AnyAttribute { get{ return any; } set{ any = value; } } // internal properties internal override bool IsExtension { get { return true; } } internal override void SetParent (XmlSchemaObject parent) { base.SetParent (parent); if (AnyAttribute != null) AnyAttribute.SetParent (this); foreach (XmlSchemaObject obj in Attributes) obj.SetParent (this); } ///<remarks> /// 1. Base must be present and a QName ///</remarks> internal override int Compile(ValidationEventHandler h, XmlSchema schema) { // If this is already compiled this time, simply skip. if (CompilationId == schema.CompilationId) return 0; if (this.isRedefinedComponent) { if (Annotation != null) Annotation.isRedefinedComponent = true; if (AnyAttribute != null) AnyAttribute.isRedefinedComponent = true; foreach (XmlSchemaObject obj in Attributes) obj.isRedefinedComponent = true; } if(BaseTypeName == null || BaseTypeName.IsEmpty) { error(h, "base must be present, as a QName"); } else if(!XmlSchemaUtil.CheckQName(BaseTypeName)) error(h,"BaseTypeName must be a QName"); if(this.AnyAttribute != null) { errorCount += AnyAttribute.Compile(h,schema); } foreach(XmlSchemaObject obj in Attributes) { if(obj is XmlSchemaAttribute) { XmlSchemaAttribute attr = (XmlSchemaAttribute) obj; errorCount += attr.Compile(h,schema); } else if(obj is XmlSchemaAttributeGroupRef) { XmlSchemaAttributeGroupRef atgrp = (XmlSchemaAttributeGroupRef) obj; errorCount += atgrp.Compile(h,schema); } else error(h,obj.GetType() +" is not valid in this place::SimpleConentExtension"); } XmlSchemaUtil.CompileID(Id,this,schema.IDCollection,h); this.CompilationId = schema.CompilationId; return errorCount; } internal override XmlQualifiedName GetBaseTypeName () { return baseTypeName; } internal override XmlSchemaParticle GetParticle () { return null; } internal override int Validate(ValidationEventHandler h, XmlSchema schema) { if (IsValidated (schema.ValidationId)) return errorCount; XmlSchemaType st = schema.FindSchemaType (baseTypeName); if (st != null) { XmlSchemaComplexType ct = st as XmlSchemaComplexType; if (ct != null && ct.ContentModel is XmlSchemaComplexContent) error (h, "Specified type is complex type which contains complex content."); st.Validate (h, schema); actualBaseSchemaType = st; } else if (baseTypeName == XmlSchemaComplexType.AnyTypeName) { actualBaseSchemaType = XmlSchemaComplexType.AnyType; } else if (XmlSchemaUtil.IsBuiltInDatatypeName (baseTypeName)) { actualBaseSchemaType = XmlSchemaDatatype.FromName (baseTypeName); if (actualBaseSchemaType == null) error (h, "Invalid schema datatype name is specified."); } // otherwise, it might be missing sub components. else if (!schema.IsNamespaceAbsent (baseTypeName.Namespace)) error (h, "Referenced base schema type " + baseTypeName + " was not found in the corresponding schema."); ValidationId = schema.ValidationId; return errorCount; } //<extension //base = QName //id = ID //{any attributes with non-schema namespace . . .}> //Content: (annotation?, ((attribute | attributeGroup)*, anyAttribute?)) //</extension> internal static XmlSchemaSimpleContentExtension Read(XmlSchemaReader reader, ValidationEventHandler h) { XmlSchemaSimpleContentExtension extension = new XmlSchemaSimpleContentExtension(); reader.MoveToElement(); if(reader.NamespaceURI != XmlSchema.Namespace || reader.LocalName != xmlname) { error(h,"Should not happen :1: XmlSchemaAttributeGroup.Read, name="+reader.Name,null); reader.Skip(); return null; } extension.LineNumber = reader.LineNumber; extension.LinePosition = reader.LinePosition; extension.SourceUri = reader.BaseURI; while(reader.MoveToNextAttribute()) { if(reader.Name == "base") { Exception innerex; extension.baseTypeName= XmlSchemaUtil.ReadQNameAttribute(reader,out innerex); if(innerex != null) error(h, reader.Value + " is not a valid value for base attribute",innerex); } else if(reader.Name == "id") { extension.Id = reader.Value; } else if((reader.NamespaceURI == "" && reader.Name != "xmlns") || reader.NamespaceURI == XmlSchema.Namespace) { error(h,reader.Name + " is not a valid attribute for extension in this context",null); } else { XmlSchemaUtil.ReadUnhandledAttribute(reader,extension); } } reader.MoveToElement(); if(reader.IsEmptyElement) return extension; //Content: 1.annotation?, 2.(attribute | attributeGroup)*, 3.anyAttribute? int level = 1; while(reader.ReadNextElement()) { if(reader.NodeType == XmlNodeType.EndElement) { if(reader.LocalName != xmlname) error(h,"Should not happen :2: XmlSchemaSimpleContentExtension.Read, name="+reader.Name,null); break; } if(level <= 1 && reader.LocalName == "annotation") { level = 2; //Only one annotation XmlSchemaAnnotation annotation = XmlSchemaAnnotation.Read(reader,h); if(annotation != null) extension.Annotation = annotation; continue; } if(level <= 2) { if(reader.LocalName == "attribute") { level = 2; XmlSchemaAttribute attr = XmlSchemaAttribute.Read(reader,h); if(attr != null) extension.Attributes.Add(attr); continue; } if(reader.LocalName == "attributeGroup") { level = 2; XmlSchemaAttributeGroupRef attr = XmlSchemaAttributeGroupRef.Read(reader,h); if(attr != null) extension.attributes.Add(attr); continue; } } if(level <= 3 && reader.LocalName == "anyAttribute") { level = 4; XmlSchemaAnyAttribute anyattr = XmlSchemaAnyAttribute.Read(reader,h); if(anyattr != null) extension.AnyAttribute = anyattr; continue; } reader.RaiseInvalidElementError(); } return extension; } } }
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreVideo; using MonoTouch.AVFoundation; using MonoTouch.GLKit; using MonoTouch.CoreFoundation; using MonoTouch.CoreMedia; using MonoTouch.OpenGLES; using OpenTK.Graphics.ES20; using System.Threading.Tasks; using System.Diagnostics; using System.IO; namespace RosyWriter { public partial class RosyWriterViewController : UIViewController { #region Properties #endregion #region Private Members RosyWriterVideoProcessor videoProcessor; RosyWriterPreviewWindow oglView; UILabel frameRateLabel; UILabel dimensionsLabel; UILabel typeLabel; NSTimer timer; bool shouldShowStats; int backgroundRecordingID; #endregion public RosyWriterViewController () : base ("RosyWriterViewControlleriPhone", null) { } public void UpdateLabels () { if (shouldShowStats) { var frameRateString = string.Format ("{0} FPS", videoProcessor.VideoFrameRate.ToString ("F")); frameRateLabel.Text = frameRateString; frameRateLabel.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); var dimensionString = string.Format ("{0} x {0}", videoProcessor.VideoDimensions.Width, videoProcessor.VideoDimensions.Height); dimensionsLabel.Text = dimensionString; dimensionsLabel.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); var type = videoProcessor.VideoType; var typeString = Enum.GetName (typeof(CMVideoCodecType), type); typeLabel.Text = typeString; typeLabel.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); } else { frameRateLabel.Text = string.Empty; frameRateLabel.BackgroundColor = UIColor.Clear; dimensionsLabel.Text = string.Empty; dimensionsLabel.BackgroundColor = UIColor.Clear; typeLabel.Text = string.Empty; typeLabel.BackgroundColor = UIColor.Clear; } } public UILabel LabelWithText (string text, float yPosition) { float labelWidth = 200.0F; float labelHeight = 40.0F; float xPosition = viewPreview.Bounds.Size.Width - labelWidth - 10; RectangleF labelFrame = new RectangleF (xPosition, yPosition, labelWidth, labelHeight); UILabel label = new UILabel (labelFrame); label.Font = UIFont.SystemFontOfSize (36F); label.LineBreakMode = UILineBreakMode.WordWrap; label.TextAlignment = UITextAlignment.Right; label.TextColor = UIColor.White; label.BackgroundColor = UIColor.FromRGBA (0, 0, 0, .25F); label.Layer.CornerRadius = 4F; label.Text = text; return label; } public void DeviceOrientationDidChange (NSNotification notification) { var orientation = UIDevice.CurrentDevice.Orientation; // Don't update the reference orientation when the device orientation is face up/down or unknown. if (UIDeviceOrientation.Portrait == orientation || (UIDeviceOrientation.LandscapeLeft == orientation || UIDeviceOrientation.LandscapeRight == orientation)) videoProcessor.ReferenceOrientation = orientationFromDeviceOrientation (orientation); } private AVCaptureVideoOrientation orientationFromDeviceOrientation (UIDeviceOrientation orientation) { AVCaptureVideoOrientation retOrientation; switch (orientation) { case UIDeviceOrientation.PortraitUpsideDown: retOrientation = AVCaptureVideoOrientation.PortraitUpsideDown; break; case UIDeviceOrientation.Portrait: retOrientation = AVCaptureVideoOrientation.Portrait; break; case UIDeviceOrientation.LandscapeLeft: retOrientation = AVCaptureVideoOrientation.LandscapeLeft; break; case UIDeviceOrientation.LandscapeRight: retOrientation = AVCaptureVideoOrientation.LandscapeRight; break; default: retOrientation = (AVCaptureVideoOrientation)0; break; } return retOrientation; } public void Cleanup () { frameRateLabel.Dispose (); dimensionsLabel.Dispose (); typeLabel.Dispose (); var notificationCenter = NSNotificationCenter.DefaultCenter; notificationCenter.RemoveObserver (this, UIDevice.OrientationDidChangeNotification, UIApplication.SharedApplication); UIDevice.CurrentDevice.EndGeneratingDeviceOrientationNotifications (); notificationCenter.RemoveObserver (this, UIApplication.DidBecomeActiveNotification, UIApplication.SharedApplication); // Stop and tear down the capture session videoProcessor.StopAndTearDownCaptureSession (); videoProcessor.Dispose (); } #region Event Handler public void On_PixelBufferReadyForDisplay (object sender, CVImageBuffer imageBuffer) { // Don't make OpenGLES calls while in the backgroud. if (UIApplication.SharedApplication.ApplicationState != UIApplicationState.Background) oglView.DisplayPixelBuffer(imageBuffer); } public void On_ToggleRecording (object sender, EventArgs e) { // UIBarButtonItem btn = (UIBarButtonItem)sender; // Wait for the recording to start/stop before re-enabling the record button. InvokeOnMainThread (() => { btnRecord.Enabled = false; }); if (videoProcessor.IsRecording) { // The recordingWill/DidStop delegate methods will fire asynchronously in the response to this call. videoProcessor.StopRecording (); } else { videoProcessor.StartRecording (); } } public void On_ApplicationDidBecomeActive (NSNotification notification) { // For performance reasons, we manually pause/resume the session when saving a recoding. // If we try to resume the session in the background it will fail. Resume the session here as well to ensure we will succeed. videoProcessor.ResumeCaptureSession (); } #region Video Processer Event handlers public void On_RecordingWillStart (object sender) { InvokeOnMainThread (() => { btnRecord.Enabled = false; btnRecord.Title = "Stop"; // Disable the idle timer while we are recording UIApplication.SharedApplication.IdleTimerDisabled = true; // Make sure we have time to finish saving the movie if the app is backgrounded during recording if (UIDevice.CurrentDevice.IsMultitaskingSupported) backgroundRecordingID = UIApplication.SharedApplication.BeginBackgroundTask (() => {}); }); } public void On_RecordingDidStart (object sender) { InvokeOnMainThread (() => { btnRecord.Enabled = true; }); } public void On_RecordingWillStop (object sender) { InvokeOnMainThread (() => { // Disable until saving to the camera roll is complete btnRecord.Title = "Record"; btnRecord.Enabled = false; // Pause the capture session so the saving will be as fast as possible. // We resme the session in recordingDidStop videoProcessor.PauseCaptureSession (); }); } public void On_RecordingDidStop (object sender) { InvokeOnMainThread (() => { btnRecord.Enabled = true; UIApplication.SharedApplication.IdleTimerDisabled = false; videoProcessor.ResumeCaptureSession (); if (UIDevice.CurrentDevice.IsMultitaskingSupported) { UIApplication.SharedApplication.EndBackgroundTask (backgroundRecordingID); backgroundRecordingID = 0; } }); } #endregion #endregion #region UIViewController Methods public override void DidRotate (UIInterfaceOrientation fromInterfaceOrientation) { if (fromInterfaceOrientation == UIInterfaceOrientation.Portrait || fromInterfaceOrientation == UIInterfaceOrientation.LandscapeLeft || fromInterfaceOrientation == UIInterfaceOrientation.LandscapeRight) { } } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } public override void ViewDidLoad () { base.ViewDidLoad (); // Initialize the class responsible for managing AV capture session and asset writer videoProcessor = new RosyWriterVideoProcessor (); // Keep track of changes to the device orientation so we can update the video processor var notificationCenter = NSNotificationCenter.DefaultCenter; notificationCenter.AddObserver(UIApplication.DidChangeStatusBarOrientationNotification, DeviceOrientationDidChange); UIDevice.CurrentDevice.BeginGeneratingDeviceOrientationNotifications (); // Setup and start the capture session videoProcessor.SetupAndStartCaptureSession (); Console.WriteLine("Finished Setting up AV"); notificationCenter.AddObserver (UIApplication.DidBecomeActiveNotification, On_ApplicationDidBecomeActive); oglView = new RosyWriterPreviewWindow(RectangleF.Empty); // Our interface is always in portrait oglView.Transform = videoProcessor.TransformFromCurrentVideoOrientationToOrientation(AVCaptureVideoOrientation.Portrait); RectangleF bounds = viewPreview.ConvertRectToView(viewPreview.Bounds, oglView); oglView.Bounds = bounds; oglView.Center = new PointF(viewPreview.Bounds.Size.Width / 2.0F, viewPreview.Bounds.Size.Height / 2.0F); viewPreview.AddSubview(oglView); Console.WriteLine("Added OGL View"); // Set up labels shouldShowStats = true; frameRateLabel = LabelWithText (string.Empty, 10.0F); viewPreview.AddSubview (frameRateLabel); dimensionsLabel = LabelWithText (string.Empty, 54.0F); viewPreview.AddSubview (dimensionsLabel); typeLabel = LabelWithText (string.Empty, 90F); viewPreview.Add (typeLabel); // btnRecord Event Handler btnRecord.Clicked += On_ToggleRecording; // Video Processor Event Handlers videoProcessor.RecordingDidStart += On_RecordingDidStart; videoProcessor.RecordingDidStop += On_RecordingDidStop; videoProcessor.RecordingWillStart += On_RecordingWillStart; videoProcessor.RecordingWillStop += On_RecordingWillStop; videoProcessor.PixelBufferReadyForDisplay += On_PixelBufferReadyForDisplay; Console.WriteLine("Finished OnDidLoad"); } public override void ViewDidUnload () { base.ViewDidUnload (); // Clear any references to subviews of the main view in order to // allow the Garbage Collector to collect them sooner. // // e.g. myOutlet.Dispose (); myOutlet = null; Cleanup (); ReleaseDesignerOutlets (); } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); timer = NSTimer.CreateRepeatingScheduledTimer (.25, UpdateLabels); } public override void ViewDidDisappear (bool animated) { base.ViewDidDisappear (animated); timer.Invalidate (); timer.Dispose (); } public override bool ShouldAutorotateToInterfaceOrientation (UIInterfaceOrientation toInterfaceOrientation) { // Return true for supported orientations return (toInterfaceOrientation != UIInterfaceOrientation.PortraitUpsideDown); } #endregion } }
#region Copyright & License // // Copyright 2001-2005 The Apache Software Foundation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using log4net.Core; namespace log4net.Util { /// <summary> /// A fixed size rolling buffer of logging events. /// </summary> /// <remarks> /// <para> /// An array backed fixed size leaky bucket. /// </para> /// </remarks> /// <author>Nicko Cadell</author> /// <author>Gert Driesen</author> public class CyclicBuffer { #region Public Instance Constructors /// <summary> /// Constructor /// </summary> /// <param name="maxSize">The maximum number of logging events in the buffer.</param> /// <remarks> /// <para> /// Initializes a new instance of the <see cref="CyclicBuffer" /> class with /// the specified maximum number of buffered logging events. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="maxSize"/> argument is not a positive integer.</exception> public CyclicBuffer(int maxSize) { if (maxSize < 1) { throw SystemInfo.CreateArgumentOutOfRangeException("maxSize", (object)maxSize, "Parameter: maxSize, Value: [" + maxSize + "] out of range. Non zero positive integer required"); } m_maxSize = maxSize; m_events = new LoggingEvent[maxSize]; m_first = 0; m_last = 0; m_numElems = 0; } #endregion Public Instance Constructors #region Public Instance Methods /// <summary> /// Appends a <paramref name="loggingEvent"/> to the buffer. /// </summary> /// <param name="loggingEvent">The event to append to the buffer.</param> /// <returns>The event discarded from the buffer, if the buffer is full, otherwise <c>null</c>.</returns> /// <remarks> /// <para> /// Append an event to the buffer. If the buffer still contains free space then /// <c>null</c> is returned. If the buffer is full then an event will be dropped /// to make space for the new event, the event dropped is returned. /// </para> /// </remarks> public LoggingEvent Append(LoggingEvent loggingEvent) { if (loggingEvent == null) { throw new ArgumentNullException("loggingEvent"); } lock(this) { // save the discarded event LoggingEvent discardedLoggingEvent = m_events[m_last]; // overwrite the last event position m_events[m_last] = loggingEvent; if (++m_last == m_maxSize) { m_last = 0; } if (m_numElems < m_maxSize) { m_numElems++; } else if (++m_first == m_maxSize) { m_first = 0; } if (m_numElems < m_maxSize) { // Space remaining return null; } else { // Buffer is full and discarding an event return discardedLoggingEvent; } } } /// <summary> /// Get and remove the oldest event in the buffer. /// </summary> /// <returns>The oldest logging event in the buffer</returns> /// <remarks> /// <para> /// Gets the oldest (first) logging event in the buffer and removes it /// from the buffer. /// </para> /// </remarks> public LoggingEvent PopOldest() { lock(this) { LoggingEvent ret = null; if (m_numElems > 0) { m_numElems--; ret = m_events[m_first]; m_events[m_first] = null; if (++m_first == m_maxSize) { m_first = 0; } } return ret; } } /// <summary> /// Pops all the logging events from the buffer into an array. /// </summary> /// <returns>An array of all the logging events in the buffer.</returns> /// <remarks> /// <para> /// Get all the events in the buffer and clear the buffer. /// </para> /// </remarks> public LoggingEvent[] PopAll() { lock(this) { LoggingEvent[] ret = new LoggingEvent[m_numElems]; if (m_numElems > 0) { if (m_first < m_last) { Array.Copy(m_events, m_first, ret, 0, m_numElems); } else { Array.Copy(m_events, m_first, ret, 0, m_maxSize - m_first); Array.Copy(m_events, 0, ret, m_maxSize - m_first, m_last); } } Clear(); return ret; } } /// <summary> /// Clear the buffer /// </summary> /// <remarks> /// <para> /// Clear the buffer of all events. The events in the buffer are lost. /// </para> /// </remarks> public void Clear() { lock(this) { // Set all the elements to null Array.Clear(m_events, 0, m_events.Length); m_first = 0; m_last = 0; m_numElems = 0; } } #if RESIZABLE_CYCLIC_BUFFER /// <summary> /// Resizes the cyclic buffer to <paramref name="newSize"/>. /// </summary> /// <param name="newSize">The new size of the buffer.</param> /// <remarks> /// <para> /// Resize the cyclic buffer. Events in the buffer are copied into /// the newly sized buffer. If the buffer is shrunk and there are /// more events currently in the buffer than the new size of the /// buffer then the newest events will be dropped from the buffer. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">The <paramref name="newSize"/> argument is not a positive integer.</exception> public void Resize(int newSize) { lock(this) { if (newSize < 0) { throw log4net.Util.SystemInfo.CreateArgumentOutOfRangeException("newSize", (object)newSize, "Parameter: newSize, Value: [" + newSize + "] out of range. Non zero positive integer required"); } if (newSize == m_numElems) { return; // nothing to do } LoggingEvent[] temp = new LoggingEvent[newSize]; int loopLen = (newSize < m_numElems) ? newSize : m_numElems; for(int i = 0; i < loopLen; i++) { temp[i] = m_events[m_first]; m_events[m_first] = null; if (++m_first == m_numElems) { m_first = 0; } } m_events = temp; m_first = 0; m_numElems = loopLen; m_maxSize = newSize; if (loopLen == newSize) { m_last = 0; } else { m_last = loopLen; } } } #endif #endregion Public Instance Methods #region Public Instance Properties /// <summary> /// Gets the <paramref name="i"/>th oldest event currently in the buffer. /// </summary> /// <value>The <paramref name="i"/>th oldest event currently in the buffer.</value> /// <remarks> /// <para> /// If <paramref name="i"/> is outside the range 0 to the number of events /// currently in the buffer, then <c>null</c> is returned. /// </para> /// </remarks> public LoggingEvent this[int i] { get { lock(this) { if (i < 0 || i >= m_numElems) { return null; } return m_events[(m_first + i) % m_maxSize]; } } } /// <summary> /// Gets the maximum size of the buffer. /// </summary> /// <value>The maximum size of the buffer.</value> /// <remarks> /// <para> /// Gets the maximum size of the buffer /// </para> /// </remarks> public int MaxSize { get { lock(this) { return m_maxSize; } } #if RESIZABLE_CYCLIC_BUFFER set { /// Setting the MaxSize will cause the buffer to resize. Resize(value); } #endif } /// <summary> /// Gets the number of logging events in the buffer. /// </summary> /// <value>The number of logging events in the buffer.</value> /// <remarks> /// <para> /// This number is guaranteed to be in the range 0 to <see cref="MaxSize"/> /// (inclusive). /// </para> /// </remarks> public int Length { get { lock(this) { return m_numElems; } } } #endregion Public Instance Properties #region Private Instance Fields private LoggingEvent[] m_events; private int m_first; private int m_last; private int m_numElems; private int m_maxSize; #endregion Private Instance Fields } }
// // Import.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2011 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using Mono.Cecil.Metadata; using Mono.Collections.Generic; using SR = System.Reflection; namespace Mono.Cecil { enum ImportGenericKind { Definition, Open, } struct ImportGenericContext { Collection<IGenericParameterProvider> stack; public bool IsEmpty { get { return stack == null; } } public ImportGenericContext (IGenericParameterProvider provider) { stack = null; Push (provider); } public void Push (IGenericParameterProvider provider) { if (stack == null) stack = new Collection<IGenericParameterProvider> (1) { provider }; else stack.Add (provider); } public void Pop () { stack.RemoveAt (stack.Count - 1); } public TypeReference MethodParameter (string method, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = stack [i] as MethodReference; if (candidate == null) continue; if (method != candidate.Name) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } public TypeReference TypeParameter (string type, int position) { for (int i = stack.Count - 1; i >= 0; i--) { var candidate = GenericTypeFor (stack [i]); if (candidate.FullName != type) continue; return candidate.GenericParameters [position]; } throw new InvalidOperationException (); } static TypeReference GenericTypeFor (IGenericParameterProvider context) { var type = context as TypeReference; if (type != null) return type.GetElementType (); var method = context as MethodReference; if (method != null) return method.DeclaringType.GetElementType (); throw new InvalidOperationException (); } } class MetadataImporter { readonly ModuleDefinition module; public MetadataImporter (ModuleDefinition module) { this.module = module; } public IScopeResolver ScopeResolver { get; set; } #if !CF static readonly Dictionary<Type, ElementType> type_etype_mapping = new Dictionary<Type, ElementType> (18) { { typeof (void), ElementType.Void }, { typeof (bool), ElementType.Boolean }, { typeof (char), ElementType.Char }, { typeof (sbyte), ElementType.I1 }, { typeof (byte), ElementType.U1 }, { typeof (short), ElementType.I2 }, { typeof (ushort), ElementType.U2 }, { typeof (int), ElementType.I4 }, { typeof (uint), ElementType.U4 }, { typeof (long), ElementType.I8 }, { typeof (ulong), ElementType.U8 }, { typeof (float), ElementType.R4 }, { typeof (double), ElementType.R8 }, { typeof (string), ElementType.String }, { typeof (TypedReference), ElementType.TypedByRef }, { typeof (IntPtr), ElementType.I }, { typeof (UIntPtr), ElementType.U }, { typeof (object), ElementType.Object }, }; public TypeReference ImportType (Type type, ImportGenericContext context) { return ImportType (type, context, ImportGenericKind.Open); } public TypeReference ImportType (Type type, ImportGenericContext context, ImportGenericKind import_kind) { if (IsTypeSpecification (type) || ImportOpenGenericType (type, import_kind)) return ImportTypeSpecification (type, context); var reference = new TypeReference ( string.Empty, type.Name, module, ImportScope (type.Assembly), type.IsValueType); reference.etype = ImportElementType (type); if (IsNestedType (type)) reference.DeclaringType = ImportType (type.DeclaringType, context, import_kind); else reference.Namespace = type.Namespace ?? string.Empty; if (type.IsGenericType) ImportGenericParameters (reference, type.GetGenericArguments ()); return reference; } static bool ImportOpenGenericType (Type type, ImportGenericKind import_kind) { return type.IsGenericType && type.IsGenericTypeDefinition && import_kind == ImportGenericKind.Open; } static bool ImportOpenGenericMethod (SR.MethodBase method, ImportGenericKind import_kind) { return method.IsGenericMethod && method.IsGenericMethodDefinition && import_kind == ImportGenericKind.Open; } static bool IsNestedType (Type type) { #if !SILVERLIGHT return type.IsNested; #else return type.DeclaringType != null; #endif } TypeReference ImportTypeSpecification (Type type, ImportGenericContext context) { if (type.IsByRef) return new ByReferenceType (ImportType (type.GetElementType (), context)); if (type.IsPointer) return new PointerType (ImportType (type.GetElementType (), context)); if (type.IsArray) return new ArrayType (ImportType (type.GetElementType (), context), type.GetArrayRank ()); if (type.IsGenericType) return ImportGenericInstance (type, context); if (type.IsGenericParameter) return ImportGenericParameter (type, context); throw new NotSupportedException (type.FullName); } static TypeReference ImportGenericParameter (Type type, ImportGenericContext context) { if (context.IsEmpty) throw new InvalidOperationException (); if (type.DeclaringMethod != null) return context.MethodParameter (type.DeclaringMethod.Name, type.GenericParameterPosition); if (type.DeclaringType != null) return context.TypeParameter (NormalizedFullName (type.DeclaringType), type.GenericParameterPosition); throw new InvalidOperationException(); } private static string NormalizedFullName (Type type) { if (IsNestedType (type)) return NormalizedFullName (type.DeclaringType) + "/" + type.Name; return type.FullName; } TypeReference ImportGenericInstance (Type type, ImportGenericContext context) { var element_type = ImportType (type.GetGenericTypeDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceType (element_type); var arguments = type.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_type); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool IsTypeSpecification (Type type) { return type.HasElementType || IsGenericInstance (type) || type.IsGenericParameter; } static bool IsGenericInstance (Type type) { return type.IsGenericType && !type.IsGenericTypeDefinition; } static ElementType ImportElementType (Type type) { ElementType etype; if (!type_etype_mapping.TryGetValue (type, out etype)) return ElementType.None; return etype; } IMetadataScope ImportScope (SR.Assembly assembly) { #if !SILVERLIGHT var name = assembly.GetName (); AssemblyNameReference reference; if (TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { Culture = name.CultureInfo.Name, PublicKeyToken = name.GetPublicKeyToken (), HashAlgorithm = (AssemblyHashAlgorithm) name.HashAlgorithm, }; return ResolveScope(reference); #else var name = AssemblyNameReference.Parse (assembly.FullName); if (TryGetAssemblyNameReference (name, out scope)) return scope; module.AssemblyReferences.Add (name); return name; #endif } private IMetadataScope ResolveScope(AssemblyNameReference scope) { if (ScopeResolver == null) { module.AssemblyReferences.Add(scope); return scope; } IMetadataScope resolvedScope = ScopeResolver.Resolve(module, scope); if (resolvedScope == scope) { module.AssemblyReferences.Add(scope); return scope; } else if (resolvedScope == module || module.Assembly.Name == scope) { return module; } else { return ImportScope(resolvedScope); } } #if !SILVERLIGHT bool TryGetAssemblyNameReference (SR.AssemblyName name, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } #endif public FieldReference ImportField (SR.FieldInfo field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); if (IsGenericInstance (field.DeclaringType)) field = ResolveFieldDefinition (field); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } static SR.FieldInfo ResolveFieldDefinition (SR.FieldInfo field) { #if !SILVERLIGHT return field.Module.ResolveField (field.MetadataToken); #else return field.DeclaringType.GetGenericTypeDefinition ().GetField (field.Name, SR.BindingFlags.Public | SR.BindingFlags.NonPublic | (field.IsStatic ? SR.BindingFlags.Static : SR.BindingFlags.Instance)); #endif } public MethodReference ImportMethod (SR.MethodBase method, ImportGenericContext context, ImportGenericKind import_kind) { if (IsMethodSpecification (method) || ImportOpenGenericMethod (method, import_kind)) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); if (IsGenericInstance (method.DeclaringType)) method = method.Module.ResolveMethod (method.MetadataToken); var reference = new MethodReference { Name = method.Name, HasThis = HasCallingConvention (method, SR.CallingConventions.HasThis), ExplicitThis = HasCallingConvention (method, SR.CallingConventions.ExplicitThis), DeclaringType = ImportType (method.DeclaringType, context, ImportGenericKind.Definition), }; if (HasCallingConvention (method, SR.CallingConventions.VarArgs)) reference.CallingConvention &= MethodCallingConvention.VarArg; if (method.IsGenericMethod) ImportGenericParameters (reference, method.GetGenericArguments ()); context.Push (reference); try { var method_info = method as SR.MethodInfo; reference.ReturnType = method_info != null ? ImportType (method_info.ReturnType, context) : ImportType (typeof (void), default (ImportGenericContext)); var parameters = method.GetParameters (); var reference_parameters = reference.Parameters; for (int i = 0; i < parameters.Length; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); reference.DeclaringType = declaring_type; return reference; } finally { context.Pop (); } } static void ImportGenericParameters (IGenericParameterProvider provider, Type [] arguments) { var provider_parameters = provider.GenericParameters; for (int i = 0; i < arguments.Length; i++) provider_parameters.Add (new GenericParameter (arguments [i].Name, provider)); } static bool IsMethodSpecification (SR.MethodBase method) { return method.IsGenericMethod && !method.IsGenericMethodDefinition; } MethodReference ImportMethodSpecification (SR.MethodBase method, ImportGenericContext context) { var method_info = method as SR.MethodInfo; if (method_info == null) throw new InvalidOperationException (); var element_method = ImportMethod (method_info.GetGenericMethodDefinition (), context, ImportGenericKind.Definition); var instance = new GenericInstanceMethod (element_method); var arguments = method.GetGenericArguments (); var instance_arguments = instance.GenericArguments; context.Push (element_method); try { for (int i = 0; i < arguments.Length; i++) instance_arguments.Add (ImportType (arguments [i], context)); return instance; } finally { context.Pop (); } } static bool HasCallingConvention (SR.MethodBase method, SR.CallingConventions conventions) { return (method.CallingConvention & conventions) != 0; } #endif public TypeReference ImportType (TypeReference type, ImportGenericContext context) { if (type.IsTypeSpecification ()) return ImportTypeSpecification (type, context); var reference = new TypeReference ( type.Namespace, type.Name, module, ImportScope (type.Scope), type.IsValueType); MetadataSystem.TryProcessPrimitiveTypeReference (reference); if (type.IsNested) reference.DeclaringType = ImportType (type.DeclaringType, context); if (type.HasGenericParameters) ImportGenericParameters (reference, type); return reference; } IMetadataScope ImportScope (IMetadataScope scope) { if (scope == null || scope == module || module.Assembly.Name == scope) { return module; } switch (scope.MetadataScopeType) { case MetadataScopeType.AssemblyNameReference: return ImportAssemblyName ((AssemblyNameReference) scope); case MetadataScopeType.ModuleDefinition: return ImportAssemblyName (((ModuleDefinition) scope).Assembly.Name); case MetadataScopeType.ModuleReference: throw new NotImplementedException (); } throw new NotSupportedException (); } AssemblyNameReference ImportAssemblyName (AssemblyNameReference name) { AssemblyNameReference reference; if (TryGetAssemblyNameReference (name, out reference)) return reference; reference = new AssemblyNameReference (name.Name, name.Version) { Culture = name.Culture, HashAlgorithm = name.HashAlgorithm, }; var pk_token = !name.PublicKeyToken.IsNullOrEmpty () ? new byte [name.PublicKeyToken.Length] : Empty<byte>.Array; if (pk_token.Length > 0) Buffer.BlockCopy (name.PublicKeyToken, 0, pk_token, 0, pk_token.Length); reference.PublicKeyToken = pk_token; module.AssemblyReferences.Add (reference); return reference; } bool TryGetAssemblyNameReference (AssemblyNameReference name_reference, out AssemblyNameReference assembly_reference) { var references = module.AssemblyReferences; for (int i = 0; i < references.Count; i++) { var reference = references [i]; if (name_reference.FullName != reference.FullName) // TODO compare field by field continue; assembly_reference = reference; return true; } assembly_reference = null; return false; } static void ImportGenericParameters (IGenericParameterProvider imported, IGenericParameterProvider original) { var parameters = original.GenericParameters; var imported_parameters = imported.GenericParameters; for (int i = 0; i < parameters.Count; i++) imported_parameters.Add (new GenericParameter (parameters [i].Name, imported)); } TypeReference ImportTypeSpecification (TypeReference type, ImportGenericContext context) { switch (type.etype) { case ElementType.SzArray: var vector = (ArrayType) type; return new ArrayType (ImportType (vector.ElementType, context)); case ElementType.Ptr: var pointer = (PointerType) type; return new PointerType (ImportType (pointer.ElementType, context)); case ElementType.ByRef: var byref = (ByReferenceType) type; return new ByReferenceType (ImportType (byref.ElementType, context)); case ElementType.Pinned: var pinned = (PinnedType) type; return new PinnedType (ImportType (pinned.ElementType, context)); case ElementType.Sentinel: var sentinel = (SentinelType) type; return new SentinelType (ImportType (sentinel.ElementType, context)); case ElementType.CModOpt: var modopt = (OptionalModifierType) type; return new OptionalModifierType ( ImportType (modopt.ModifierType, context), ImportType (modopt.ElementType, context)); case ElementType.CModReqD: var modreq = (RequiredModifierType) type; return new RequiredModifierType ( ImportType (modreq.ModifierType, context), ImportType (modreq.ElementType, context)); case ElementType.Array: var array = (ArrayType) type; var imported_array = new ArrayType (ImportType (array.ElementType, context)); if (array.IsVector) return imported_array; var dimensions = array.Dimensions; var imported_dimensions = imported_array.Dimensions; imported_dimensions.Clear (); for (int i = 0; i < dimensions.Count; i++) { var dimension = dimensions [i]; imported_dimensions.Add (new ArrayDimension (dimension.LowerBound, dimension.UpperBound)); } return imported_array; case ElementType.GenericInst: var instance = (GenericInstanceType) type; var element_type = ImportType (instance.ElementType, context); var imported_instance = new GenericInstanceType (element_type); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; case ElementType.Var: var var_parameter = (GenericParameter) type; return context.TypeParameter (type.DeclaringType.FullName, var_parameter.Position); case ElementType.MVar: var mvar_parameter = (GenericParameter) type; return context.MethodParameter (mvar_parameter.DeclaringMethod.Name, mvar_parameter.Position); } throw new NotSupportedException (type.etype.ToString ()); } public FieldReference ImportField (FieldReference field, ImportGenericContext context) { var declaring_type = ImportType (field.DeclaringType, context); context.Push (declaring_type); try { return new FieldReference { Name = field.Name, DeclaringType = declaring_type, FieldType = ImportType (field.FieldType, context), }; } finally { context.Pop (); } } public MethodReference ImportMethod (MethodReference method, ImportGenericContext context) { if (method.IsGenericInstance) return ImportMethodSpecification (method, context); var declaring_type = ImportType (method.DeclaringType, context); var reference = new MethodReference { Name = method.Name, HasThis = method.HasThis, ExplicitThis = method.ExplicitThis, DeclaringType = declaring_type, CallingConvention = method.CallingConvention, }; if (method.HasGenericParameters) ImportGenericParameters (reference, method); context.Push (reference); try { reference.ReturnType = ImportType (method.ReturnType, context); if (!method.HasParameters) return reference; var reference_parameters = reference.Parameters; var parameters = method.Parameters; for (int i = 0; i < parameters.Count; i++) reference_parameters.Add ( new ParameterDefinition (ImportType (parameters [i].ParameterType, context))); return reference; } finally { context.Pop(); } } MethodSpecification ImportMethodSpecification (MethodReference method, ImportGenericContext context) { if (!method.IsGenericInstance) throw new NotSupportedException (); var instance = (GenericInstanceMethod) method; var element_method = ImportMethod (instance.ElementMethod, context); var imported_instance = new GenericInstanceMethod (element_method); var arguments = instance.GenericArguments; var imported_arguments = imported_instance.GenericArguments; for (int i = 0; i < arguments.Count; i++) imported_arguments.Add (ImportType (arguments [i], context)); return imported_instance; } } }
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.Owin.Infrastructure; using Microsoft.Owin.Logging; using Microsoft.Owin.Security.Infrastructure; namespace Microsoft.Owin.Security.Cookies { internal class CookieAuthenticationHandler : AuthenticationHandler<CookieAuthenticationOptions> { private const string HeaderNameCacheControl = "Cache-Control"; private const string HeaderNamePragma = "Pragma"; private const string HeaderNameExpires = "Expires"; private const string HeaderValueNoCache = "no-cache"; private const string HeaderValueMinusOne = "-1"; private const string SessionIdClaim = "Microsoft.Owin.Security.Cookies-SessionId"; private readonly ILogger _logger; private bool _shouldRenew; private DateTimeOffset _renewIssuedUtc; private DateTimeOffset _renewExpiresUtc; private string _sessionKey; public CookieAuthenticationHandler(ILogger logger) { if (logger == null) { throw new ArgumentNullException("logger"); } _logger = logger; } protected override async Task<AuthenticationTicket> AuthenticateCoreAsync() { AuthenticationTicket ticket = null; try { string cookie = Options.CookieManager.GetRequestCookie(Context, Options.CookieName); if (string.IsNullOrWhiteSpace(cookie)) { return null; } ticket = Options.TicketDataFormat.Unprotect(cookie); if (ticket == null) { _logger.WriteWarning(@"Unprotect ticket failed"); return null; } if (Options.SessionStore != null) { Claim claim = ticket.Identity.Claims.FirstOrDefault(c => c.Type.Equals(SessionIdClaim)); if (claim == null) { _logger.WriteWarning(@"SessoinId missing"); return null; } _sessionKey = claim.Value; ticket = await Options.SessionStore.RetrieveAsync(_sessionKey); if (ticket == null) { _logger.WriteWarning(@"Identity missing in session store"); return null; } } DateTimeOffset currentUtc = Options.SystemClock.UtcNow; DateTimeOffset? issuedUtc = ticket.Properties.IssuedUtc; DateTimeOffset? expiresUtc = ticket.Properties.ExpiresUtc; if (expiresUtc != null && expiresUtc.Value < currentUtc) { if (Options.SessionStore != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } return null; } bool? allowRefresh = ticket.Properties.AllowRefresh; if (issuedUtc != null && expiresUtc != null && Options.SlidingExpiration && (!allowRefresh.HasValue || allowRefresh.Value)) { TimeSpan timeElapsed = currentUtc.Subtract(issuedUtc.Value); TimeSpan timeRemaining = expiresUtc.Value.Subtract(currentUtc); if (timeRemaining < timeElapsed) { _shouldRenew = true; _renewIssuedUtc = currentUtc; TimeSpan timeSpan = expiresUtc.Value.Subtract(issuedUtc.Value); _renewExpiresUtc = currentUtc.Add(timeSpan); } } var context = new CookieValidateIdentityContext(Context, ticket, Options); await Options.Provider.ValidateIdentity(context); return new AuthenticationTicket(context.Identity, context.Properties); } catch (Exception exception) { CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options, CookieExceptionContext.ExceptionLocation.AuthenticateAsync, exception, ticket); Options.Provider.Exception(exceptionContext); if (exceptionContext.Rethrow) { throw; } return exceptionContext.Ticket; } } protected override async Task ApplyResponseGrantAsync() { AuthenticationResponseGrant signin = Helper.LookupSignIn(Options.AuthenticationType); bool shouldSignin = signin != null; AuthenticationResponseRevoke signout = Helper.LookupSignOut(Options.AuthenticationType, Options.AuthenticationMode); bool shouldSignout = signout != null; if (!(shouldSignin || shouldSignout || _shouldRenew)) { return; } AuthenticationTicket model = await AuthenticateAsync(); try { var cookieOptions = new CookieOptions { Domain = Options.CookieDomain, HttpOnly = Options.CookieHttpOnly, Path = Options.CookiePath ?? "/", }; if (Options.CookieSecure == CookieSecureOption.SameAsRequest) { cookieOptions.Secure = Request.IsSecure; } else { cookieOptions.Secure = Options.CookieSecure == CookieSecureOption.Always; } if (shouldSignin) { var signInContext = new CookieResponseSignInContext( Context, Options, Options.AuthenticationType, signin.Identity, signin.Properties, cookieOptions); DateTimeOffset issuedUtc; if (signInContext.Properties.IssuedUtc.HasValue) { issuedUtc = signInContext.Properties.IssuedUtc.Value; } else { issuedUtc = Options.SystemClock.UtcNow; signInContext.Properties.IssuedUtc = issuedUtc; } if (!signInContext.Properties.ExpiresUtc.HasValue) { signInContext.Properties.ExpiresUtc = issuedUtc.Add(Options.ExpireTimeSpan); } Options.Provider.ResponseSignIn(signInContext); if (signInContext.Properties.IsPersistent) { DateTimeOffset expiresUtc = signInContext.Properties.ExpiresUtc ?? issuedUtc.Add(Options.ExpireTimeSpan); signInContext.CookieOptions.Expires = expiresUtc.ToUniversalTime().DateTime; } model = new AuthenticationTicket(signInContext.Identity, signInContext.Properties); if (Options.SessionStore != null) { if (_sessionKey != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } _sessionKey = await Options.SessionStore.StoreAsync(model); ClaimsIdentity identity = new ClaimsIdentity( new[] { new Claim(SessionIdClaim, _sessionKey) }, Options.AuthenticationType); model = new AuthenticationTicket(identity, null); } string cookieValue = Options.TicketDataFormat.Protect(model); Options.CookieManager.AppendResponseCookie( Context, Options.CookieName, cookieValue, signInContext.CookieOptions); var signedInContext = new CookieResponseSignedInContext( Context, Options, Options.AuthenticationType, signInContext.Identity, signInContext.Properties); Options.Provider.ResponseSignedIn(signedInContext); } else if (shouldSignout) { if (Options.SessionStore != null && _sessionKey != null) { await Options.SessionStore.RemoveAsync(_sessionKey); } var context = new CookieResponseSignOutContext( Context, Options, cookieOptions); Options.Provider.ResponseSignOut(context); Options.CookieManager.DeleteCookie( Context, Options.CookieName, context.CookieOptions); } else if (_shouldRenew) { model.Properties.IssuedUtc = _renewIssuedUtc; model.Properties.ExpiresUtc = _renewExpiresUtc; if (Options.SessionStore != null && _sessionKey != null) { await Options.SessionStore.RenewAsync(_sessionKey, model); ClaimsIdentity identity = new ClaimsIdentity( new[] { new Claim(SessionIdClaim, _sessionKey) }, Options.AuthenticationType); model = new AuthenticationTicket(identity, null); } string cookieValue = Options.TicketDataFormat.Protect(model); if (model.Properties.IsPersistent) { cookieOptions.Expires = _renewExpiresUtc.ToUniversalTime().DateTime; } Options.CookieManager.AppendResponseCookie( Context, Options.CookieName, cookieValue, cookieOptions); } Response.Headers.Set( HeaderNameCacheControl, HeaderValueNoCache); Response.Headers.Set( HeaderNamePragma, HeaderValueNoCache); Response.Headers.Set( HeaderNameExpires, HeaderValueMinusOne); bool shouldLoginRedirect = shouldSignin && Options.LoginPath.HasValue && Request.Path == Options.LoginPath; bool shouldLogoutRedirect = shouldSignout && Options.LogoutPath.HasValue && Request.Path == Options.LogoutPath; if ((shouldLoginRedirect || shouldLogoutRedirect) && Response.StatusCode == 200) { IReadableStringCollection query = Request.Query; string redirectUri = query.Get(Options.ReturnUrlParameter); if (!string.IsNullOrWhiteSpace(redirectUri) && IsHostRelative(redirectUri)) { var redirectContext = new CookieApplyRedirectContext(Context, Options, redirectUri); Options.Provider.ApplyRedirect(redirectContext); } } } catch (Exception exception) { CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options, CookieExceptionContext.ExceptionLocation.ApplyResponseGrant, exception, model); Options.Provider.Exception(exceptionContext); if (exceptionContext.Rethrow) { throw; } } } private static bool IsHostRelative(string path) { if (string.IsNullOrEmpty(path)) { return false; } if (path.Length == 1) { return path[0] == '/'; } return path[0] == '/' && path[1] != '/' && path[1] != '\\'; } protected override Task ApplyResponseChallengeAsync() { if (Response.StatusCode != 401 || !Options.LoginPath.HasValue) { return Task.FromResult(0); } AuthenticationResponseChallenge challenge = Helper.LookupChallenge(Options.AuthenticationType, Options.AuthenticationMode); try { if (challenge != null) { string loginUri = challenge.Properties.RedirectUri; if (string.IsNullOrWhiteSpace(loginUri)) { string currentUri = Request.PathBase + Request.Path + Request.QueryString; loginUri = Request.Scheme + Uri.SchemeDelimiter + Request.Host + Request.PathBase + Options.LoginPath + new QueryString(Options.ReturnUrlParameter, currentUri); } var redirectContext = new CookieApplyRedirectContext(Context, Options, loginUri); Options.Provider.ApplyRedirect(redirectContext); } } catch (Exception exception) { CookieExceptionContext exceptionContext = new CookieExceptionContext(Context, Options, CookieExceptionContext.ExceptionLocation.ApplyResponseChallenge, exception, ticket: null); Options.Provider.Exception(exceptionContext); if (exceptionContext.Rethrow) { throw; } } return Task.FromResult<object>(null); } } }
/* * Velcro Physics: * Copyright (c) 2017 Ian Qvist * * Original source Box2D: * Copyright (c) 2006-2011 Erin Catto http://www.box2d.org * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using Microsoft.Xna.Framework; using QEngine.Physics.Dynamics.Solver; using QEngine.Physics.Shared; using QEngine.Physics.Utilities; namespace QEngine.Physics.Dynamics.Joints { // Point-to-point constraint // C = p2 - p1 // Cdot = v2 - v1 // = v2 + cross(w2, r2) - v1 - cross(w1, r1) // J = [-I -r1_skew I r2_skew ] // Identity used: // w k % (rx i + ry j) = w * (-ry i + rx j) // Angle constraint // C = angle2 - angle1 - referenceAngle // Cdot = w2 - w1 // J = [0 0 -1 0 0 1] // K = invI1 + invI2 /// <summary> /// A weld joint essentially glues two bodies together. A weld joint may /// distort somewhat because the island constraint solver is approximate. /// The joint is soft constraint based, which means the two bodies will move /// relative to each other, when a force is applied. To combine two bodies /// in a rigid fashion, combine the fixtures to a single body instead. /// </summary> public class WeldJoint : Joint { private float _bias; private float _gamma; // Solver shared private Vector3 _impulse; // Solver temp private int _indexA; private int _indexB; private float _invIA; private float _invIB; private float _invMassA; private float _invMassB; private Vector2 _localCenterA; private Vector2 _localCenterB; private Mat33 _mass; private Vector2 _rA; private Vector2 _rB; internal WeldJoint() { JointType = JointType.Weld; } /// <summary> /// You need to specify an anchor point where they are attached. /// The position of the anchor point is important for computing the reaction torque. /// </summary> /// <param name="bodyA">The first body</param> /// <param name="bodyB">The second body</param> /// <param name="anchorA">The first body anchor.</param> /// <param name="anchorB">The second body anchor.</param> /// <param name="useWorldCoordinates">Set to true if you are using world coordinates as anchors.</param> public WeldJoint(Body bodyA, Body bodyB, Vector2 anchorA, Vector2 anchorB, bool useWorldCoordinates = false) : base(bodyA, bodyB) { JointType = JointType.Weld; if (useWorldCoordinates) { LocalAnchorA = bodyA.GetLocalPoint(anchorA); LocalAnchorB = bodyB.GetLocalPoint(anchorB); } else { LocalAnchorA = anchorA; LocalAnchorB = anchorB; } ReferenceAngle = BodyB.Rotation - BodyA.Rotation; } /// <summary> /// The local anchor point on BodyA /// </summary> public Vector2 LocalAnchorA { get; set; } /// <summary> /// The local anchor point on BodyB /// </summary> public Vector2 LocalAnchorB { get; set; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } set { LocalAnchorA = BodyA.GetLocalPoint(value); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { LocalAnchorB = BodyB.GetLocalPoint(value); } } /// <summary> /// The bodyB angle minus bodyA angle in the reference state (radians). /// </summary> public float ReferenceAngle { get; set; } /// <summary> /// The frequency of the joint. A higher frequency means a stiffer joint, but /// a too high value can cause the joint to oscillate. /// Default is 0, which means the joint does no spring calculations. /// </summary> public float FrequencyHz { get; set; } /// <summary> /// The damping on the joint. The damping is only used when /// the joint has a frequency (> 0). A higher value means more damping. /// </summary> public float DampingRatio { get; set; } public override Vector2 GetReactionForce(float invDt) { return invDt * new Vector2(_impulse.X, _impulse.Y); } public override float GetReactionTorque(float invDt) { return invDt * _impulse.Z; } internal override void InitVelocityConstraints(ref SolverData data) { _indexA = BodyA.IslandIndex; _indexB = BodyB.IslandIndex; _localCenterA = BodyA._sweep.LocalCenter; _localCenterB = BodyB._sweep.LocalCenter; _invMassA = BodyA._invMass; _invMassB = BodyB._invMass; _invIA = BodyA._invI; _invIB = BodyB._invI; float aA = data.Positions[_indexA].A; Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; float aB = data.Positions[_indexB].A; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; Rot qA = new Rot(aA), qB = new Rot(aB); _rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); _rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); // J = [-I -r1_skew I r2_skew] // [ 0 -1 0 1] // r_skew = [-ry; rx] // Matlab // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Mat33 K = new Mat33(); K.ex.X = mA + mB + _rA.Y * _rA.Y * iA + _rB.Y * _rB.Y * iB; K.ey.X = -_rA.Y * _rA.X * iA - _rB.Y * _rB.X * iB; K.ez.X = -_rA.Y * iA - _rB.Y * iB; K.ex.Y = K.ey.X; K.ey.Y = mA + mB + _rA.X * _rA.X * iA + _rB.X * _rB.X * iB; K.ez.Y = _rA.X * iA + _rB.X * iB; K.ex.Z = K.ez.X; K.ey.Z = K.ez.Y; K.ez.Z = iA + iB; if (FrequencyHz > 0.0f) { K.GetInverse22(ref _mass); float invM = iA + iB; float m = invM > 0.0f ? 1.0f / invM : 0.0f; float C = aB - aA - ReferenceAngle; // Frequency float omega = 2.0f * Settings.Pi * FrequencyHz; // Damping coefficient float d = 2.0f * m * DampingRatio * omega; // Spring stiffness float k = m * omega * omega; // magic formulas float h = data.Step.dt; _gamma = h * (d + h * k); _gamma = _gamma != 0.0f ? 1.0f / _gamma : 0.0f; _bias = C * h * k * _gamma; invM += _gamma; _mass.ez.Z = invM != 0.0f ? 1.0f / invM : 0.0f; } else if (K.ez.Z == 0.0f) { K.GetInverse22(ref _mass); _gamma = 0.0f; _bias = 0.0f; } else { K.GetSymInverse33(ref _mass); _gamma = 0.0f; _bias = 0.0f; } if (Settings.EnableWarmstarting) { // Scale impulses to support a variable time step. _impulse *= data.Step.dtRatio; Vector2 P = new Vector2(_impulse.X, _impulse.Y); vA -= mA * P; wA -= iA * (MathUtils.Cross(_rA, P) + _impulse.Z); vB += mB * P; wB += iB * (MathUtils.Cross(_rB, P) + _impulse.Z); } else { _impulse = Vector3.Zero; } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override void SolveVelocityConstraints(ref SolverData data) { Vector2 vA = data.Velocities[_indexA].V; float wA = data.Velocities[_indexA].W; Vector2 vB = data.Velocities[_indexB].V; float wB = data.Velocities[_indexB].W; float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; if (FrequencyHz > 0.0f) { float Cdot2 = wB - wA; float impulse2 = -_mass.ez.Z * (Cdot2 + _bias + _gamma * _impulse.Z); _impulse.Z += impulse2; wA -= iA * impulse2; wB += iB * impulse2; Vector2 Cdot1 = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA); Vector2 impulse1 = -MathUtils.Mul22(_mass, Cdot1); _impulse.X += impulse1.X; _impulse.Y += impulse1.Y; Vector2 P = impulse1; vA -= mA * P; wA -= iA * MathUtils.Cross(_rA, P); vB += mB * P; wB += iB * MathUtils.Cross(_rB, P); } else { Vector2 Cdot1 = vB + MathUtils.Cross(wB, _rB) - vA - MathUtils.Cross(wA, _rA); float Cdot2 = wB - wA; Vector3 Cdot = new Vector3(Cdot1.X, Cdot1.Y, Cdot2); Vector3 impulse = -MathUtils.Mul(_mass, Cdot); _impulse += impulse; Vector2 P = new Vector2(impulse.X, impulse.Y); vA -= mA * P; wA -= iA * (MathUtils.Cross(_rA, P) + impulse.Z); vB += mB * P; wB += iB * (MathUtils.Cross(_rB, P) + impulse.Z); } data.Velocities[_indexA].V = vA; data.Velocities[_indexA].W = wA; data.Velocities[_indexB].V = vB; data.Velocities[_indexB].W = wB; } internal override bool SolvePositionConstraints(ref SolverData data) { Vector2 cA = data.Positions[_indexA].C; float aA = data.Positions[_indexA].A; Vector2 cB = data.Positions[_indexB].C; float aB = data.Positions[_indexB].A; Rot qA = new Rot(aA), qB = new Rot(aB); float mA = _invMassA, mB = _invMassB; float iA = _invIA, iB = _invIB; Vector2 rA = MathUtils.Mul(qA, LocalAnchorA - _localCenterA); Vector2 rB = MathUtils.Mul(qB, LocalAnchorB - _localCenterB); float positionError, angularError; Mat33 K = new Mat33(); K.ex.X = mA + mB + rA.Y * rA.Y * iA + rB.Y * rB.Y * iB; K.ey.X = -rA.Y * rA.X * iA - rB.Y * rB.X * iB; K.ez.X = -rA.Y * iA - rB.Y * iB; K.ex.Y = K.ey.X; K.ey.Y = mA + mB + rA.X * rA.X * iA + rB.X * rB.X * iB; K.ez.Y = rA.X * iA + rB.X * iB; K.ex.Z = K.ez.X; K.ey.Z = K.ez.Y; K.ez.Z = iA + iB; if (FrequencyHz > 0.0f) { Vector2 C1 = cB + rB - cA - rA; positionError = C1.Length(); angularError = 0.0f; Vector2 P = -K.Solve22(C1); cA -= mA * P; aA -= iA * MathUtils.Cross(rA, P); cB += mB * P; aB += iB * MathUtils.Cross(rB, P); } else { Vector2 C1 = cB + rB - cA - rA; float C2 = aB - aA - ReferenceAngle; positionError = C1.Length(); angularError = Math.Abs(C2); Vector3 C = new Vector3(C1.X, C1.Y, C2); Vector3 impulse; if (K.ez.Z > 0.0f) { impulse = -K.Solve33(C); } else { Vector2 impulse2 = -K.Solve22(C1); impulse = new Vector3(impulse2.X, impulse2.Y, 0.0f); } Vector2 P = new Vector2(impulse.X, impulse.Y); cA -= mA * P; aA -= iA * (MathUtils.Cross(rA, P) + impulse.Z); cB += mB * P; aB += iB * (MathUtils.Cross(rB, P) + impulse.Z); } data.Positions[_indexA].C = cA; data.Positions[_indexA].A = aA; data.Positions[_indexB].C = cB; data.Positions[_indexB].A = aB; return positionError <= Settings.LinearSlop && angularError <= Settings.AngularSlop; } } }
using System; using System.Collections.Generic; using System.Linq; using Orleans; using Orleans.Runtime; namespace OrleansManager { class Program { private static IManagementGrain systemManagement; static void Main(string[] args) { Console.WriteLine("Invoked OrleansManager.exe with arguments {0}", Utils.EnumerableToString(args)); var command = args.Length > 0 ? args[0].ToLowerInvariant() : ""; if (string.IsNullOrEmpty(command) || command.Equals("/?") || command.Equals("-?")) { PrintUsage(); Environment.Exit(-1); } try { RunCommand(command, args); Environment.Exit(0); } catch (Exception exc) { Console.WriteLine("Terminating due to exception:"); Console.WriteLine(exc.ToString()); } } private static void RunCommand(string command, string[] args) { GrainClient.Initialize(); systemManagement = GrainClient.GrainFactory.GetGrain<IManagementGrain>(0); Dictionary<string, string> options = args.Skip(1) .Where(s => s.StartsWith("-")) .Select(s => s.Substring(1).Split('=')) .ToDictionary(a => a[0].ToLowerInvariant(), a => a.Length > 1 ? a[1] : ""); var restWithoutOptions = args.Skip(1).Where(s => !s.StartsWith("-")).ToArray(); switch (command) { case "grainstats": PrintSimpleGrainStatistics(restWithoutOptions); break; case "fullgrainstats": PrintGrainStatistics(restWithoutOptions); break; case "collect": CollectActivations(options, restWithoutOptions); break; case "unregister": var unregisterArgs = args.Skip(1).ToArray(); UnregisterGrain(unregisterArgs); break; case "lookup": var lookupArgs = args.Skip(1).ToArray(); LookupGrain(lookupArgs); break; case "grainreport": var grainReportArgs = args.Skip(1).ToArray(); GrainReport(grainReportArgs); break; default: PrintUsage(); break; } } private static void PrintUsage() { Console.WriteLine(@"Usage: OrleansManager grainstats [silo1 silo2 ...] OrleansManager fullgrainstats [silo1 silo2 ...] OrleansManager collect [-memory=nnn] [-age=nnn] [silo1 silo2 ...] OrleansManager unregister <grain interface type code (int)|grain implementation class name (string)> <grain id long|grain id Guid> OrleansManager lookup <grain interface type code (int)|grain implementation class name (string)> <grain id long|grain id Guid> OrleansManager grainReport <grain interface type code (int)|grain implementation class name (string)> <grain id long|grain id Guid>"); } private static void CollectActivations(IReadOnlyDictionary<string, string> options, IEnumerable<string> args) { var silos = args.Select(ParseSilo).ToArray(); int ageLimitSeconds = 0; string s; if (options.TryGetValue("age", out s)) int.TryParse(s, out ageLimitSeconds); var ageLimit = TimeSpan.FromSeconds(ageLimitSeconds); if (ageLimit > TimeSpan.Zero) systemManagement.ForceActivationCollection(silos, ageLimit); else systemManagement.ForceGarbageCollection(silos); } private static void PrintSimpleGrainStatistics(IEnumerable<string> args) { var silos = args.Select(ParseSilo).ToArray(); var stats = systemManagement.GetSimpleGrainStatistics(silos).Result; Console.WriteLine("Silo Activations Type"); Console.WriteLine("--------------------- ----------- ------------"); foreach (var s in stats.OrderBy(s => s.SiloAddress + s.GrainType)) Console.WriteLine("{0} {1} {2}", s.SiloAddress.ToString().PadRight(21), Pad(s.ActivationCount, 11), s.GrainType); } private static void PrintGrainStatistics(IEnumerable<string> args) { var silos = args.Select(ParseSilo).ToArray(); var stats = systemManagement.GetSimpleGrainStatistics(silos).Result; Console.WriteLine("Act Type"); Console.WriteLine("-------- ----- ------ ------------"); foreach (var s in stats.OrderBy(s => Tuple.Create(s.GrainType, s.ActivationCount))) Console.WriteLine("{0} {1}", Pad(s.ActivationCount, 8), s.GrainType); } private static void GrainReport(string[] args) { var grainId = ConstructGrainId(args, "GrainReport"); var silos = GetSiloAddresses(); if (silos == null || silos.Count == 0) return; var reports = new List<DetailedGrainReport>(); foreach (var silo in silos) { WriteStatus(string.Format("**Calling GetDetailedGrainReport({0}, {1})", silo, grainId)); try { var siloControl = GrainClient.InternalGrainFactory.GetSystemTarget<ISiloControl>(Constants.SiloControlId, silo); DetailedGrainReport grainReport = siloControl.GetDetailedGrainReport(grainId).Result; reports.Add(grainReport); } catch (Exception exc) { WriteStatus(string.Format("**Failed to get grain report from silo {0}. Exc: {1}", silo, exc.ToString())); } } foreach (var grainReport in reports) WriteStatus(grainReport.ToString()); LookupGrain(args); } private static void UnregisterGrain(string[] args) { var grainId = ConstructGrainId(args, "unregister"); var silo = GetSiloAddress(); if (silo == null) return; var directory = GrainClient.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo); WriteStatus(string.Format("**Calling DeleteGrain({0}, {1})", silo, grainId)); directory.DeleteGrainAsync(grainId).Wait(); WriteStatus(string.Format("**DeleteGrain finished OK.")); } private static async void LookupGrain(string[] args) { var grainId = ConstructGrainId(args, "lookup"); var silo = GetSiloAddress(); if (silo == null) return; var directory = GrainClient.InternalGrainFactory.GetSystemTarget<IRemoteGrainDirectory>(Constants.DirectoryServiceId, silo); WriteStatus(string.Format("**Calling LookupGrain({0}, {1})", silo, grainId)); //Tuple<List<Tuple<SiloAddress, ActivationId>>, int> lookupResult = await directory.FullLookUp(grainId, true); var lookupResult = await directory.LookupAsync(grainId); WriteStatus(string.Format("**LookupGrain finished OK. Lookup result is:")); var list = lookupResult.Addresses; if (list == null) { WriteStatus(string.Format("**The returned activation list is null.")); return; } if (list.Count == 0) { WriteStatus(string.Format("**The returned activation list is empty.")); return; } Console.WriteLine("**There {0} {1} activations registered in the directory for this grain. The activations are:", (list.Count > 1) ? "are" : "is", list.Count); foreach (var tuple in list) { WriteStatus(string.Format("**Activation {0} on silo {1}", tuple.Activation, tuple.Silo)); } } private static GrainId ConstructGrainId(string[] args, string operation) { if (args == null || args.Length < 2) { PrintUsage(); return null; } string interfaceTypeCodeOrImplClassName = args[0]; int interfaceTypeCodeDataLong; long implementationTypeCode; var grainTypeResolver = RuntimeClient.Current.GrainTypeResolver; if (int.TryParse(interfaceTypeCodeOrImplClassName, out interfaceTypeCodeDataLong)) { // parsed it as int, so it is an interface type code. implementationTypeCode = GetImplementation(grainTypeResolver, interfaceTypeCodeDataLong).GrainTypeCode; } else { // interfaceTypeCodeOrImplClassName is the implementation class name implementationTypeCode = GetImplementation(grainTypeResolver, interfaceTypeCodeOrImplClassName).GrainTypeCode; } var grainIdStr = args[1]; GrainId grainId = null; long grainIdLong; Guid grainIdGuid; if (long.TryParse(grainIdStr, out grainIdLong)) grainId = GrainId.GetGrainId(implementationTypeCode, grainIdLong); else if (Guid.TryParse(grainIdStr, out grainIdGuid)) grainId = GrainId.GetGrainId(implementationTypeCode, grainIdGuid); WriteStatus(string.Format("**Full Grain Id to {0} is: GrainId = {1}", operation, grainId.ToFullString())); return grainId; } private static SiloAddress GetSiloAddress() { List<SiloAddress> silos = GetSiloAddresses(); if (silos == null || silos.Count==0) return null; return silos.FirstOrDefault(); } private static List<SiloAddress> GetSiloAddresses() { IList<Uri> gateways = GrainClient.Gateways; if (gateways.Count >= 1) return gateways.Select(Utils.ToSiloAddress).ToList(); WriteStatus(string.Format("**Retrieved only zero gateways from Client.Gateways")); return null; } private static string Pad(int value, int width) { return value.ToString("d").PadRight(width); } private static SiloAddress ParseSilo(string s) { return SiloAddress.FromParsableString(s); } public static void WriteStatus(string msg) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine(msg); Console.ResetColor(); } internal static GrainClassData GetImplementation(IGrainTypeResolver grainTypeResolver, int interfaceId, string grainClassNamePrefix = null) { GrainClassData implementation; if (grainTypeResolver.TryGetGrainClassData(interfaceId, out implementation, grainClassNamePrefix)) return implementation; var loadedAssemblies = grainTypeResolver.GetLoadedGrainAssemblies(); throw new ArgumentException( string.Format("Cannot find an implementation class for grain interface: {0}{2}. Make sure the grain assembly was correctly deployed and loaded in the silo.{1}", interfaceId, string.IsNullOrEmpty(loadedAssemblies) ? string.Empty : string.Format(" Loaded grain assemblies: {0}", loadedAssemblies), string.IsNullOrEmpty(grainClassNamePrefix) ? string.Empty : ", grainClassNamePrefix=" + grainClassNamePrefix)); } internal static GrainClassData GetImplementation(IGrainTypeResolver grainTypeResolver, string grainImplementationClassName) { GrainClassData implementation; if (!grainTypeResolver.TryGetGrainClassData(grainImplementationClassName, out implementation)) throw new ArgumentException(string.Format("Cannot find an implementation grain class: {0}. Make sure the grain assembly was correctly deployed and loaded in the silo.", grainImplementationClassName)); return implementation; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Globalization; using Xunit; public static class CharTests { [Fact] public static void TestCompareTo() { // Int32 Char.CompareTo(Char) char h = 'h'; Assert.True(h.CompareTo('h') == 0); Assert.True(h.CompareTo('a') > 0); Assert.True(h.CompareTo('z') < 0); } [Fact] public static void TestSystemIComparableCompareTo() { // Int32 Char.System.IComparable.CompareTo(Object) IComparable h = 'h'; Assert.True(h.CompareTo('h') == 0); Assert.True(h.CompareTo('a') > 0); Assert.True(h.CompareTo('z') < 0); Assert.True(h.CompareTo(null) > 0); Assert.Throws<ArgumentException>(() => h.CompareTo("H")); } private static void ValidateConvertFromUtf32(int i, string expected) { try { string s = char.ConvertFromUtf32(i); Assert.Equal(expected, s); } catch (ArgumentOutOfRangeException) { Assert.True(expected == null, "Expected an ArgumentOutOfRangeException"); } } [Fact] public static void TestConvertFromUtf32() { // String Char.ConvertFromUtf32(Int32) ValidateConvertFromUtf32(0x10000, "\uD800\uDC00"); ValidateConvertFromUtf32(0x103FF, "\uD800\uDFFF"); ValidateConvertFromUtf32(0xFFFFF, "\uDBBF\uDFFF"); ValidateConvertFromUtf32(0x10FC00, "\uDBFF\uDC00"); ValidateConvertFromUtf32(0x10FFFF, "\uDBFF\uDFFF"); ValidateConvertFromUtf32(0, "\0"); ValidateConvertFromUtf32(0x3FF, "\u03FF"); ValidateConvertFromUtf32(0xE000, "\uE000"); ValidateConvertFromUtf32(0xFFFF, "\uFFFF"); ValidateConvertFromUtf32(0xD800, null); ValidateConvertFromUtf32(0xDC00, null); ValidateConvertFromUtf32(0xDFFF, null); ValidateConvertFromUtf32(0x110000, null); ValidateConvertFromUtf32(-1, null); ValidateConvertFromUtf32(int.MaxValue, null); ValidateConvertFromUtf32(int.MinValue, null); } private static void ValidateconverToUtf32<T>(string s, int i, int expected) where T : Exception { try { int result = char.ConvertToUtf32(s, i); Assert.Equal(result, expected); } catch (T) { Assert.True(expected == int.MinValue, "Expected an exception to be thrown"); } } [Fact] public static void TestConvertToUtf32StrInt() { // Int32 Char.ConvertToUtf32(String, Int32) ValidateconverToUtf32<Exception>("\uD800\uDC00", 0, 0x10000); ValidateconverToUtf32<Exception>("\uD800\uD800\uDFFF", 1, 0x103FF); ValidateconverToUtf32<Exception>("\uDBBF\uDFFF", 0, 0xFFFFF); ValidateconverToUtf32<Exception>("\uDBFF\uDC00", 0, 0x10FC00); ValidateconverToUtf32<Exception>("\uDBFF\uDFFF", 0, 0x10FFFF); // Not surrogate pairs ValidateconverToUtf32<Exception>("\u0000\u0001", 0, 0); ValidateconverToUtf32<Exception>("\u0000\u0001", 1, 1); ValidateconverToUtf32<Exception>("\u0000", 0, 0); ValidateconverToUtf32<Exception>("\u0020\uD7FF", 0, 32); ValidateconverToUtf32<Exception>("\u0020\uD7FF", 1, 0xD7FF); ValidateconverToUtf32<Exception>("abcde", 4, (int)'e'); ValidateconverToUtf32<Exception>("\uD800\uD7FF", 1, 0xD7FF); // high, non-surrogate ValidateconverToUtf32<Exception>("\uD800\u0000", 1, 0); // high, non-surrogate ValidateconverToUtf32<Exception>("\uDF01\u0000", 1, 0); // low, non-surrogate // Invalid inputs ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 0, int.MinValue); // high, high ValidateconverToUtf32<ArgumentException>("\uD800\uD7FF", 0, int.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentException>("\uD800\u0000", 0, int.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 0, int.MinValue); // low, high ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 0, int.MinValue); // low, low ValidateconverToUtf32<ArgumentException>("\uDF01\u0000", 0, int.MinValue); // low, non-surrogate ValidateconverToUtf32<ArgumentException>("\uD800\uD800", 1, int.MinValue); // high, high ValidateconverToUtf32<ArgumentException>("\uDC01\uD940", 1, int.MinValue); // low, high ValidateconverToUtf32<ArgumentException>("\uDD00\uDE00", 1, int.MinValue); // low, low ValidateconverToUtf32<ArgumentNullException>(null, 0, int.MinValue); // null string ValidateconverToUtf32<ArgumentOutOfRangeException>("", 0, int.MinValue); // index out of range ValidateconverToUtf32<ArgumentOutOfRangeException>("", -1, int.MinValue); // index out of range ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", -1, int.MinValue); // index out of range ValidateconverToUtf32<ArgumentOutOfRangeException>("abcde", 5, int.MinValue); // index out of range } private static void ValidateconverToUtf32<T>(char c1, char c2, int expected) where T : Exception { try { int result = char.ConvertToUtf32(c1, c2); Assert.Equal(result, expected); } catch (T) { Assert.True(expected == int.MinValue, "Expected an exception to be thrown"); } } [Fact] public static void TestConvertToUtf32() { // Int32 Char.ConvertToUtf32(Char, Char) ValidateconverToUtf32<Exception>('\uD800', '\uDC00', 0x10000); ValidateconverToUtf32<Exception>('\uD800', '\uDFFF', 0x103FF); ValidateconverToUtf32<Exception>('\uDBBF', '\uDFFF', 0xFFFFF); ValidateconverToUtf32<Exception>('\uDBFF', '\uDC00', 0x10FC00); ValidateconverToUtf32<Exception>('\uDBFF', '\uDFFF', 0x10FFFF); ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD800', int.MinValue); // high, high ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\uD7FF', int.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\uD800', '\u0000', int.MinValue); // high, non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDC01', '\uD940', int.MinValue); // low, high ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDD00', '\uDE00', int.MinValue); // low, low ValidateconverToUtf32<ArgumentOutOfRangeException>('\uDF01', '\u0000', int.MinValue); // low, non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0032', '\uD7FF', int.MinValue); // both non-surrogate ValidateconverToUtf32<ArgumentOutOfRangeException>('\u0000', '\u0000', int.MinValue); // both non-surrogate } [Fact] public static void TestEquals() { // Boolean Char.Equals(Char) char a = 'a'; Assert.True(a.Equals('a')); Assert.False(a.Equals('b')); Assert.False(a.Equals('A')); } [Fact] public static void TestEqualsObj() { // Boolean Char.Equals(Object) char a = 'a'; Assert.True(a.Equals((object)'a')); Assert.False(a.Equals((object)'b')); Assert.False(a.Equals((object)'A')); Assert.False(a.Equals(null)); int i = (int)'a'; Assert.False(a.Equals(i)); Assert.False(a.Equals("a")); } [Fact] public static void TestGetHashCode() { // Int32 Char.GetHashCode() char a = 'a'; char b = 'b'; Assert.NotEqual(a.GetHashCode(), b.GetHashCode()); } [Fact] public static void TestGetNumericValueStrInt() { Assert.Equal(Char.GetNumericValue("\uD800\uDD07", 0), 1); Assert.Equal(Char.GetNumericValue("9", 0), 9); Assert.Equal(Char.GetNumericValue("Test 7", 5), 7); Assert.Equal(Char.GetNumericValue("T", 0), -1); } [Fact] public static void TestGetNumericValue() { Assert.Equal(Char.GetNumericValue('9'), 9); Assert.Equal(Char.GetNumericValue('z'), -1); } [Fact] public static void TestIsControl() { // Boolean Char.IsControl(Char) foreach (var c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c)); } [Fact] public static void TestIsControlStrInt() { // Boolean Char.IsControl(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.Control)) Assert.True(char.IsControl(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.Control)) Assert.False(char.IsControl(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsControl(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsControl("abc", 4)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsDigit() { // Boolean Char.IsDigit(Char) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsDigitStrInt() { // Boolean Char.IsDigit(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsDigit(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsDigit(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsDigit(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsDigit("abc", 4)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetter() { // Boolean Char.IsLetter(Char) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.True(char.IsLetter(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.False(char.IsLetter(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetterStrInt() { // Boolean Char.IsLetter(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.True(char.IsLetter(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter)) Assert.False(char.IsLetter(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLetter(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetter("abc", 4)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetterOrDigit() { // Boolean Char.IsLetterOrDigit(Char) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsLetterOrDigit(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsLetterOrDigit(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLetterOrDigitStrInt() { // Boolean Char.IsLetterOrDigit(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.True(char.IsLetterOrDigit(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.ModifierLetter, UnicodeCategory.OtherLetter, UnicodeCategory.DecimalDigitNumber)) Assert.False(char.IsLetterOrDigit(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLetterOrDigit(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLetterOrDigit("abc", 4)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLower() { // Boolean Char.IsLower(Char) foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsLowerStrInt() { // Boolean Char.IsLower(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.LowercaseLetter)) Assert.True(char.IsLower(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter)) Assert.False(char.IsLower(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLower(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLower("abc", 4)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsNumber() { // Boolean Char.IsNumber(Char) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.True(char.IsNumber(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.False(char.IsNumber(c)); } [ActiveIssue(5645, PlatformID.Windows)] [Fact] public static void TestIsNumberStrInt() { // Boolean Char.IsNumber(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.True(char.IsNumber(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.DecimalDigitNumber, UnicodeCategory.LetterNumber, UnicodeCategory.OtherNumber)) Assert.False(char.IsNumber(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsNumber(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsNumber("abc", 4)); } [Fact] public static void TestIsPunctuation() { // Boolean Char.IsPunctuation(Char) foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.True(char.IsPunctuation(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.False(char.IsPunctuation(c)); } [Fact] public static void TestIsPunctuationStrInt() { // Boolean Char.IsPunctuation(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.True(char.IsPunctuation(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.ConnectorPunctuation, UnicodeCategory.DashPunctuation, UnicodeCategory.OpenPunctuation, UnicodeCategory.ClosePunctuation, UnicodeCategory.InitialQuotePunctuation, UnicodeCategory.FinalQuotePunctuation, UnicodeCategory.OtherPunctuation)) Assert.False(char.IsPunctuation(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsPunctuation(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsPunctuation("abc", 4)); } [Fact] public static void TestIsSeparator() { // Boolean Char.IsSeparator(Char) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsSeparator(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.False(char.IsSeparator(c)); } [Fact] public static void TestIsSeparatorStrInt() { // Boolean Char.IsSeparator(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsSeparator(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.False(char.IsSeparator(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsSeparator(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSeparator("abc", 4)); } [Fact] public static void TestIsLowSurrogate() { // Boolean Char.IsLowSurrogate(Char) foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c)); } [Fact] public static void TestIsLowSurrogateStrInt() { // Boolean Char.IsLowSurrogate(String, Int32) foreach (char c in s_lowSurrogates) Assert.True(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_highSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsLowSurrogate(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsLowSurrogate(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsLowSurrogate("abc", 4)); } [Fact] public static void TestIsHighSurrogate() { // Boolean Char.IsHighSurrogate(Char) foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c)); } [Fact] public static void TestIsHighSurrogateStrInt() { // Boolean Char.IsHighSurrogate(String, Int32) foreach (char c in s_highSurrogates) Assert.True(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsHighSurrogate(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsHighSurrogate(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsHighSurrogate("abc", 4)); } [Fact] public static void TestIsSurrogate() { // Boolean Char.IsSurrogate(Char) foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c)); } [Fact] public static void TestIsSurrogateStrInt() { // Boolean Char.IsSurrogate(String, Int32) foreach (char c in s_highSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_lowSurrogates) Assert.True(char.IsSurrogate(c.ToString(), 0)); foreach (char c in s_nonSurrogates) Assert.False(char.IsSurrogate(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsSurrogate(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSurrogate("abc", 4)); } [Fact] public static void TestIsSurrogatePair() { // Boolean Char.IsSurrogatePair(Char, Char) foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(Char.IsSurrogatePair(hs, ls)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(Char.IsSurrogatePair(hs, ls)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(Char.IsSurrogatePair(hs, ls)); } [Fact] public static void TestIsSurrogatePairStrInt() { // Boolean Char.IsSurrogatePair(String, Int32) foreach (char hs in s_highSurrogates) foreach (char ls in s_lowSurrogates) Assert.True(Char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_nonSurrogates) foreach (char ls in s_lowSurrogates) Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0)); foreach (char hs in s_highSurrogates) foreach (char ls in s_nonSurrogates) Assert.False(Char.IsSurrogatePair(hs.ToString() + ls, 0)); } [Fact] public static void TestIsSymbol() { // Boolean Char.IsSymbol(Char) foreach (var c in GetTestChars(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.True(char.IsSymbol(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.False(char.IsSymbol(c)); } [Fact] public static void TestIsSymbolStrInt() { // Boolean Char.IsSymbol(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.True(char.IsSymbol(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.MathSymbol, UnicodeCategory.ModifierSymbol, UnicodeCategory.CurrencySymbol, UnicodeCategory.OtherSymbol)) Assert.False(char.IsSymbol(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsSymbol(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsSymbol("abc", 4)); } [Fact] public static void TestIsUpper() { // Boolean Char.IsUpper(Char) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c)); } [Fact] public static void TestIsUpperStrInt() { // Boolean Char.IsUpper(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.UppercaseLetter)) Assert.True(char.IsUpper(c.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter)) Assert.False(char.IsUpper(c.ToString(), 0)); Assert.Throws<ArgumentNullException>(() => char.IsUpper(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsUpper("abc", 4)); } [Fact] public static void TestIsWhiteSpace() { // Boolean Char.IsWhiteSpace(Char) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsWhiteSpace(c)); // Some control chars are also considered whitespace for legacy reasons. //if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace('\u000b')); Assert.True(char.IsWhiteSpace('\u0085')); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c)); } } [Fact] public static void TestIsWhiteSpaceStrInt() { // Boolean Char.IsWhiteSpace(String, Int32) foreach (var c in GetTestChars(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) Assert.True(char.IsWhiteSpace(c.ToString(), 0)); // Some control chars are also considered whitespace for legacy reasons. //if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') Assert.True(char.IsWhiteSpace('\u000b'.ToString(), 0)); Assert.True(char.IsWhiteSpace('\u0085'.ToString(), 0)); foreach (var c in GetTestCharsNotInCategory(UnicodeCategory.SpaceSeparator, UnicodeCategory.LineSeparator, UnicodeCategory.ParagraphSeparator)) { // Need to special case some control chars that are treated as whitespace if ((c >= '\x0009' && c <= '\x000d') || c == '\x0085') continue; Assert.False(char.IsWhiteSpace(c.ToString(), 0)); } Assert.Throws<ArgumentNullException>(() => char.IsWhiteSpace(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => char.IsWhiteSpace("abc", 4)); } [Fact] public static void TestMaxValue() { // Char Char.MaxValue Assert.Equal(0xffff, char.MaxValue); } [Fact] public static void TestMinValue() { // Char Char.MinValue Assert.Equal(0, char.MinValue); } [Fact] public static void TestToLower() { // Char Char.ToLower(Char) Assert.Equal('a', char.ToLower('A')); Assert.Equal('a', char.ToLower('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLower(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToLower(c); Assert.Equal(c, lc); } } [Fact] public static void TestToLowerInvariant() { // Char Char.ToLowerInvariant(Char) Assert.Equal('a', char.ToLowerInvariant('A')); Assert.Equal('a', char.ToLowerInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.UppercaseLetter)) { char lc = char.ToLowerInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsLower(lc)); } // TitlecaseLetter can have a lower case form (e.g. \u01C8 'Lj' letter which will be 'lj') // LetterNumber can have a lower case form (e.g. \u2162 'III' letter which will be 'iii') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.UppercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToLowerInvariant(c); Assert.Equal(c, lc); } } [Fact] public static void TestToString() { // String Char.ToString() Assert.Equal(new string('a', 1), 'a'.ToString()); Assert.Equal(new string('\uabcd', 1), '\uabcd'.ToString()); } [Fact] public static void TestToStringChar() { // String Char.ToString(Char) Assert.Equal(new string('a', 1), char.ToString('a')); Assert.Equal(new string('\uabcd', 1), char.ToString('\uabcd')); } [Fact] public static void TestToUpper() { // Char Char.ToUpper(Char) Assert.Equal('A', char.ToUpper('A')); Assert.Equal('A', char.ToUpper('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpper(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToUpper(c); Assert.Equal(c, lc); } } [Fact] public static void TestToUpperInvariant() { // Char Char.ToUpperInvariant(Char) Assert.Equal('A', char.ToUpperInvariant('A')); Assert.Equal('A', char.ToUpperInvariant('a')); foreach (char c in GetTestChars(UnicodeCategory.LowercaseLetter)) { char lc = char.ToUpperInvariant(c); Assert.NotEqual(c, lc); Assert.True(char.IsUpper(lc)); } // TitlecaseLetter can have a uppercase form (e.g. \u01C8 'Lj' letter which will be 'LJ') // LetterNumber can have a uppercase form (e.g. \u2172 'iii' letter which will be 'III') foreach (char c in GetTestCharsNotInCategory(UnicodeCategory.LowercaseLetter, UnicodeCategory.TitlecaseLetter, UnicodeCategory.LetterNumber)) { char lc = char.ToUpperInvariant(c); Assert.Equal(c, lc); } } private static void ValidateTryParse(string s, char expected, bool shouldSucceed) { char result; Assert.Equal(shouldSucceed, char.TryParse(s, out result)); if (shouldSucceed) Assert.Equal(expected, result); } [Fact] public static void TestTryParse() { // Boolean Char.TryParse(String, Char) ValidateTryParse("a", 'a', true); ValidateTryParse("4", '4', true); ValidateTryParse(" ", ' ', true); ValidateTryParse("\n", '\n', true); ValidateTryParse("\0", '\0', true); ValidateTryParse("\u0135", '\u0135', true); ValidateTryParse("\u05d9", '\u05d9', true); ValidateTryParse("\ud801", '\ud801', true); // high surrogate ValidateTryParse("\udc01", '\udc01', true); // low surrogate ValidateTryParse("\ue001", '\ue001', true); // private use codepoint // Fail cases ValidateTryParse(null, '\0', false); ValidateTryParse("", '\0', false); ValidateTryParse("\n\r", '\0', false); ValidateTryParse("kj", '\0', false); ValidateTryParse(" a", '\0', false); ValidateTryParse("a ", '\0', false); ValidateTryParse("\\u0135", '\0', false); ValidateTryParse("\u01356", '\0', false); ValidateTryParse("\ud801\udc01", '\0', false); // surrogate pair } private static IEnumerable<char> GetTestCharsNotInCategory(params UnicodeCategory[] categories) { Assert.Equal(s_latinTestSet.Length, s_unicodeTestSet.Length); for (int i = 0; i < s_latinTestSet.Length; i++) { if (Array.Exists(categories, uc => uc == (UnicodeCategory)i)) continue; char[] latinSet = s_latinTestSet[i]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[i]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static IEnumerable<char> GetTestChars(params UnicodeCategory[] categories) { for (int i = 0; i < categories.Length; i++) { char[] latinSet = s_latinTestSet[(int)categories[i]]; for (int j = 0; j < latinSet.Length; j++) yield return latinSet[j]; char[] unicodeSet = s_unicodeTestSet[(int)categories[i]]; for (int k = 0; k < unicodeSet.Length; k++) yield return unicodeSet[k]; } } private static char[][] s_latinTestSet = new char[][] { new char[] {'\u0047','\u004c','\u0051','\u0056','\u00c0','\u00c5','\u00ca','\u00cf','\u00d4','\u00da'}, // UnicodeCategory.UppercaseLetter new char[] {'\u0062','\u0068','\u006e','\u0074','\u007a','\u00e1','\u00e7','\u00ed','\u00f3','\u00fa'}, // UnicodeCategory.LowercaseLetter new char[] {}, // UnicodeCategory.TitlecaseLetter new char[] {}, // UnicodeCategory.ModifierLetter new char[] {}, // UnicodeCategory.OtherLetter new char[] {}, // UnicodeCategory.NonSpacingMark new char[] {}, // UnicodeCategory.SpacingCombiningMark new char[] {}, // UnicodeCategory.EnclosingMark new char[] {'\u0030','\u0031','\u0032','\u0033','\u0034','\u0035','\u0036','\u0037','\u0038','\u0039'}, // UnicodeCategory.DecimalDigitNumber new char[] {}, // UnicodeCategory.LetterNumber new char[] {'\u00b2','\u00b3','\u00b9','\u00bc','\u00bd','\u00be'}, // UnicodeCategory.OtherNumber new char[] {'\u0020','\u00a0'}, // UnicodeCategory.SpaceSeparator new char[] {}, // UnicodeCategory.LineSeparator new char[] {}, // UnicodeCategory.ParagraphSeparator new char[] {'\u0005','\u000b','\u0011','\u0017','\u001d','\u0082','\u0085','\u008e','\u0094','\u009a'}, // UnicodeCategory.Control new char[] {}, // UnicodeCategory.Format new char[] {}, // UnicodeCategory.Surrogate new char[] {}, // UnicodeCategory.PrivateUse new char[] {'\u005f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u002d','\u00ad'}, // UnicodeCategory.DashPunctuation new char[] {'\u0028','\u005b','\u007b'}, // UnicodeCategory.OpenPunctuation new char[] {'\u0029','\u005d','\u007d'}, // UnicodeCategory.ClosePunctuation new char[] {'\u00ab'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u00bb'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u002e','\u002f','\u003a','\u003b','\u003f','\u0040','\u005c','\u00a1','\u00b7','\u00bf'}, // UnicodeCategory.OtherPunctuation new char[] {'\u002b','\u003c','\u003d','\u003e','\u007c','\u007e','\u00ac','\u00b1','\u00d7','\u00f7'}, // UnicodeCategory.MathSymbol new char[] {'\u0024','\u00a2','\u00a3','\u00a4','\u00a5'}, // UnicodeCategory.CurrencySymbol new char[] {'\u005e','\u0060','\u00a8','\u00af','\u00b4','\u00b8'}, // UnicodeCategory.ModifierSymbol new char[] {'\u00a6','\u00a7','\u00a9','\u00ae','\u00b0','\u00b6'}, // UnicodeCategory.OtherSymbol new char[] {}, // UnicodeCategory.OtherNotAssigned }; private static char[][] s_unicodeTestSet = new char[][] { new char[] {'\u0102','\u01ac','\u0392','\u0428','\u0508','\u10c4','\u1eb4','\u1fba','\u2c28','\ua668'}, // UnicodeCategory.UppercaseLetter new char[] { '\u0107', '\u012D', '\u0140', '\u0151', '\u013A', '\u01A1', '\u01F9', '\u022D', '\u1E09','\uFF45' }, // UnicodeCategory.LowercaseLetter new char[] {'\u01c8','\u1f88','\u1f8b','\u1f8e','\u1f99','\u1f9c','\u1f9f','\u1faa','\u1fad','\u1fbc'}, // UnicodeCategory.TitlecaseLetter new char[] {'\u02b7','\u02cd','\u07f4','\u1d2f','\u1d41','\u1d53','\u1d9d','\u1daf','\u2091','\u30fe'}, // UnicodeCategory.ModifierLetter new char[] {'\u01c0','\u37be','\u4970','\u5b6c','\u6d1e','\u7ed0','\u9082','\ua271','\ub985','\ucb37'}, // UnicodeCategory.OtherLetter new char[] {'\u0303','\u034e','\u05b5','\u0738','\u0a4d','\u0e49','\u0fad','\u180b','\u1dd5','\u2dfd'}, // UnicodeCategory.NonSpacingMark new char[] {'\u0982','\u0b03','\u0c41','\u0d40','\u0df3','\u1083','\u1925','\u19b9','\u1b44','\ua8b5'}, // UnicodeCategory.SpacingCombiningMark new char[] {'\u20dd','\u20de','\u20df','\u20e0','\u20e2','\u20e3','\u20e4','\ua670','\ua671','\ua672'}, // UnicodeCategory.EnclosingMark new char[] {'\u0660','\u0966','\u0ae6','\u0c66','\u0e50','\u1040','\u1810','\u1b50','\u1c50','\ua900'}, // UnicodeCategory.DecimalDigitNumber new char[] {'\u2162','\u2167','\u216c','\u2171','\u2176','\u217b','\u2180','\u2187','\u3023','\u3028'}, // UnicodeCategory.LetterNumber new char[] {'\u0c78','\u136b','\u17f7','\u2158','\u2471','\u248a','\u24f1','\u2780','\u3220','\u3280'}, // UnicodeCategory.OtherNumber new char[] {'\u2004','\u2005','\u2006','\u2007','\u2008','\u2009','\u200a','\u202f','\u205f','\u3000'}, // UnicodeCategory.SpaceSeparator new char[] {'\u2028'}, // UnicodeCategory.LineSeparator new char[] {'\u2029'}, // UnicodeCategory.ParagraphSeparator new char[] {}, // UnicodeCategory.Control new char[] {'\u0603','\u17b4','\u200c','\u200f','\u202c','\u2060','\u2063','\u206b','\u206e','\ufff9'}, // UnicodeCategory.Format new char[] {'\ud808','\ud8d4','\ud9a0','\uda6c','\udb38','\udc04','\udcd0','\udd9c','\ude68','\udf34'}, // UnicodeCategory.Surrogate new char[] {'\ue000','\ue280','\ue500','\ue780','\uea00','\uec80','\uef00','\uf180','\uf400','\uf680'}, // UnicodeCategory.PrivateUse new char[] {'\u203f','\u2040','\u2054','\ufe33','\ufe34','\ufe4d','\ufe4e','\ufe4f','\uff3f'}, // UnicodeCategory.ConnectorPunctuation new char[] {'\u2e17','\u2e1a','\u301c','\u3030','\u30a0','\ufe31','\ufe32','\ufe58','\ufe63','\uff0d'}, // UnicodeCategory.DashPunctuation new char[] {'\u2768','\u2774','\u27ee','\u298d','\u29d8','\u2e28','\u3014','\ufe17','\ufe3f','\ufe5d'}, // UnicodeCategory.OpenPunctuation new char[] {'\u276b','\u27c6','\u2984','\u2990','\u29db','\u3009','\u3017','\ufe18','\ufe40','\ufe5e'}, // UnicodeCategory.ClosePunctuation new char[] {'\u201b','\u201c','\u201f','\u2039','\u2e02','\u2e04','\u2e09','\u2e0c','\u2e1c','\u2e20'}, // UnicodeCategory.InitialQuotePunctuation new char[] {'\u2019','\u201d','\u203a','\u2e03','\u2e05','\u2e0a','\u2e0d','\u2e1d','\u2e21'}, // UnicodeCategory.FinalQuotePunctuation new char[] {'\u0589','\u0709','\u0f10','\u16ec','\u1b5b','\u2034','\u2058','\u2e16','\ua8cf','\ufe55'}, // UnicodeCategory.OtherPunctuation new char[] {'\u2052','\u2234','\u2290','\u22ec','\u27dd','\u2943','\u29b5','\u2a17','\u2a73','\u2acf'}, // UnicodeCategory.MathSymbol new char[] {'\u17db','\u20a2','\u20a5','\u20a8','\u20ab','\u20ae','\u20b1','\u20b4','\ufe69','\uffe1'}, // UnicodeCategory.CurrencySymbol new char[] {'\u02c5','\u02da','\u02e8','\u02f3','\u02fc','\u1fc0','\u1fee','\ua703','\ua70c','\ua715'}, // UnicodeCategory.ModifierSymbol new char[] {'\u0bf3','\u2316','\u24ac','\u25b2','\u26af','\u285c','\u2e8f','\u2f8c','\u3292','\u3392'}, // UnicodeCategory.OtherSymbol new char[] {'\u09c6','\u0dfa','\u2e5c','\ua9f9','\uabbd'}, // UnicodeCategory.OtherNotAssigned }; private static char[] s_highSurrogates = new char[] { '\ud800', '\udaaa', '\udbff' }; // range from '\ud800' to '\udbff' private static char[] s_lowSurrogates = new char[] { '\udc00', '\udeee', '\udfff' }; // range from '\udc00' to '\udfff' private static char[] s_nonSurrogates = new char[] { '\u0000', '\ud7ff', '\ue000', '\uffff' }; }
/*++ Copyright (c) Microsoft Corporation Module Name: FtpRequestCacheValidator.cs Abstract: The class implements FTP Caching validators Author: Alexei Vopilov 3-Aug-2004 Revision History: --*/ namespace System.Net.Cache { using System; using System.Net; using System.IO; using System.Collections; using System.Text; using System.Collections.Specialized; using System.Globalization; using System.Threading; // The class represents an adavanced way for an application to control caching protocol internal class FtpRequestCacheValidator: HttpRequestCacheValidator { DateTime m_LastModified; bool m_HttpProxyMode; private bool HttpProxyMode {get{return m_HttpProxyMode;}} internal new RequestCachePolicy Policy {get {return ((RequestCacheValidator)this).Policy;}} // private void ZeroPrivateVars() { m_LastModified = DateTime.MinValue; m_HttpProxyMode = false; } //public internal override RequestCacheValidator CreateValidator() { return new FtpRequestCacheValidator(StrictCacheErrors, UnspecifiedMaxAge); } //public internal FtpRequestCacheValidator(bool strictCacheErrors, TimeSpan unspecifiedMaxAge): base(strictCacheErrors, unspecifiedMaxAge) { } // // This validation method is called first and before any Cache access is done. // Given the request instance the code has to decide whether the request is ever suitable for caching. // // Returns: // Continue = Proceed to the next protocol stage. // DoNotTakeFromCache = Don't used caches value for this request // DoNotUseCache = Cache is not used for this request and response is not cached. protected internal override CacheValidationStatus ValidateRequest() { // cleanup context after previous request ZeroPrivateVars(); if (Request is HttpWebRequest) { m_HttpProxyMode = true; if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_ftp_proxy_doesnt_support_partial)); return base.ValidateRequest(); } if (Policy.Level == RequestCacheLevel.BypassCache) return CacheValidationStatus.DoNotUseCache; string method = Request.Method.ToUpper(CultureInfo.InvariantCulture); if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_ftp_method, method)); switch (method) { case WebRequestMethods.Ftp.DownloadFile: RequestMethod = HttpMethod.Get; break; case WebRequestMethods.Ftp.UploadFile: RequestMethod = HttpMethod.Put;break; case WebRequestMethods.Ftp.AppendFile: RequestMethod = HttpMethod.Put;break; case WebRequestMethods.Ftp.Rename: RequestMethod = HttpMethod.Put;break; case WebRequestMethods.Ftp.DeleteFile: RequestMethod = HttpMethod.Delete;break; default: RequestMethod = HttpMethod.Other; break; } if ((RequestMethod != HttpMethod.Get || !((FtpWebRequest)Request).UseBinary) && Policy.Level == RequestCacheLevel.CacheOnly) { // Throw because the request must hit the wire and it's cache-only policy FailRequest(WebExceptionStatus.RequestProhibitedByCachePolicy); } if (method != WebRequestMethods.Ftp.DownloadFile) return CacheValidationStatus.DoNotTakeFromCache; if (!((FtpWebRequest)Request).UseBinary) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_ftp_supports_bin_only)); return CacheValidationStatus.DoNotUseCache; } if (Policy.Level >= RequestCacheLevel.Reload) return CacheValidationStatus.DoNotTakeFromCache; return CacheValidationStatus.Continue; } // // This validation method is called after caching protocol has retrieved the metadata of a cached entry. // Given the cached entry context, the request instance and the effective caching policy, // the handler has to decide whether a cached item can be considered as fresh. protected internal override CacheFreshnessStatus ValidateFreshness() { if (HttpProxyMode) { if (CacheStream != Stream.Null) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_replacing_entry_with_HTTP_200)); // HTTP validator cannot parse FTP status code and other metadata if (CacheEntry.EntryMetadata == null) CacheEntry.EntryMetadata = new StringCollection(); CacheEntry.EntryMetadata.Clear(); CacheEntry.EntryMetadata.Add("HTTP/1.1 200 OK"); } return base.ValidateFreshness(); } DateTime nowDate = DateTime.UtcNow; if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_now_time, nowDate.ToString("r", CultureInfo.InvariantCulture))); // If absolute Expires can be recovered if (CacheEntry.ExpiresUtc != DateTime.MinValue) { //Take absolute Expires value if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_max_age_absolute, CacheEntry.ExpiresUtc.ToString("r", CultureInfo.InvariantCulture))); if (CacheEntry.ExpiresUtc < nowDate) { return CacheFreshnessStatus.Stale; } return CacheFreshnessStatus.Fresh; } TimeSpan age = TimeSpan.MaxValue; if(CacheEntry.LastSynchronizedUtc != DateTime.MinValue) { age = nowDate - CacheEntry.LastSynchronizedUtc; if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_age1, ((int)age.TotalSeconds).ToString(NumberFormatInfo.InvariantInfo), CacheEntry.LastSynchronizedUtc.ToString("r", CultureInfo.InvariantCulture))); } // // Heruistic expiration // if (CacheEntry.LastModifiedUtc != DateTime.MinValue) { TimeSpan span = (nowDate - CacheEntry.LastModifiedUtc); int maxAgeSeconds = (int)(span.TotalSeconds/10); if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_no_max_age_use_10_percent, maxAgeSeconds.ToString(NumberFormatInfo.InvariantInfo), CacheEntry.LastModifiedUtc.ToString("r", CultureInfo.InvariantCulture))); if (age.TotalSeconds < maxAgeSeconds) { return CacheFreshnessStatus.Fresh; } return CacheFreshnessStatus.Stale; } // Else we can only rely on UnspecifiedMaxAge hint if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_no_max_age_use_default, ((int)(UnspecifiedMaxAge.TotalSeconds)).ToString(NumberFormatInfo.InvariantInfo))); if (UnspecifiedMaxAge >= age) { return CacheFreshnessStatus.Fresh; } return CacheFreshnessStatus.Stale; //return OnValidateFreshness(this); } // This method may add headers under the "Warning" header name protected internal override CacheValidationStatus ValidateCache() { if (HttpProxyMode) return base.ValidateCache(); if (Policy.Level >= RequestCacheLevel.Reload) { // For those policies cache is never returned GlobalLog.Assert("OnValidateCache()", "This validator should not be called for policy = " + Policy.ToString()); if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_validator_invalid_for_policy, Policy.ToString())); return CacheValidationStatus.DoNotTakeFromCache; } // First check is do we have a cached entry at all? if (CacheStream == Stream.Null || CacheEntry.IsPartialEntry) { if (Policy.Level == RequestCacheLevel.CacheOnly) { // Throw because entry was not found and it's cache-only policy FailRequest(WebExceptionStatus.CacheEntryNotFound); } if (CacheStream == Stream.Null) { return CacheValidationStatus.DoNotTakeFromCache; } // Otherwise it's a partial entry and we can go on the wire } CacheStreamOffset = 0L; CacheStreamLength = CacheEntry.StreamSize; // // Before request submission validation // if (Policy.Level == RequestCacheLevel.Revalidate || CacheEntry.IsPartialEntry) { return TryConditionalRequest(); } long contentOffset = Request is FtpWebRequest ? ((FtpWebRequest)Request).ContentOffset: 0L; if (CacheFreshnessStatus == CacheFreshnessStatus.Fresh || Policy.Level == RequestCacheLevel.CacheOnly || Policy.Level == RequestCacheLevel.CacheIfAvailable) { if (contentOffset != 0) { if (contentOffset >= CacheStreamLength) { if (Policy.Level == RequestCacheLevel.CacheOnly) { // Throw because request is outside of cached size and it's cache-only policy FailRequest(WebExceptionStatus.CacheEntryNotFound); } return CacheValidationStatus.DoNotTakeFromCache; } CacheStreamOffset = contentOffset; } return CacheValidationStatus.ReturnCachedResponse; } return CacheValidationStatus.DoNotTakeFromCache; } // // This is (optionally) called after receiveing a live response // protected internal override CacheValidationStatus RevalidateCache() { if (HttpProxyMode) return base.RevalidateCache(); if (Policy.Level >= RequestCacheLevel.Reload) { // For those policies cache is never returned GlobalLog.Assert("RevalidateCache()", "This validator should not be called for policy = " + Policy.ToString()); if(Logging.On)Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_validator_invalid_for_policy, Policy.ToString())); return CacheValidationStatus.DoNotTakeFromCache; } // First check is do we still hold on a cached entry? if (CacheStream == Stream.Null) { return CacheValidationStatus.DoNotTakeFromCache; } // // This is a second+ time validation after receiving at least one response // CacheValidationStatus result = CacheValidationStatus.DoNotTakeFromCache; FtpWebResponse resp = Response as FtpWebResponse; if (resp == null) { // This will result to an application error return CacheValidationStatus.DoNotTakeFromCache; } if (resp.StatusCode == FtpStatusCode.FileStatus) { if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_response_last_modified, resp.LastModified.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture), resp.ContentLength)); if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_cache_last_modified, CacheEntry.LastModifiedUtc.ToString("r", CultureInfo.InvariantCulture), CacheEntry.StreamSize)); if (CacheStreamOffset != 0L && CacheEntry.IsPartialEntry) { //should never happen if(Logging.On) Logging.PrintError(Logging.RequestCache, SR.GetString(SR.net_log_cache_partial_and_non_zero_content_offset, CacheStreamOffset.ToString(CultureInfo.InvariantCulture))); result = CacheValidationStatus.DoNotTakeFromCache; } if (resp.LastModified.ToUniversalTime() == CacheEntry.LastModifiedUtc) { if (CacheEntry.IsPartialEntry) { // A caller will need to use Validator.CacheEntry.StreamSize to figure out what the restart point is if (resp.ContentLength > 0) this.CacheStreamLength = resp.ContentLength; else this.CacheStreamLength = -1; result = CacheValidationStatus.CombineCachedAndServerResponse; } else if (resp.ContentLength == CacheEntry.StreamSize) { result = CacheValidationStatus.ReturnCachedResponse; } else result = CacheValidationStatus.DoNotTakeFromCache; } else result = CacheValidationStatus.DoNotTakeFromCache; } else { result = CacheValidationStatus.DoNotTakeFromCache; } return result; } // // This validation method is responsible to answer whether the live response is sufficient to make // the final decision for caching protocol. // This is useful in case of possible failure or inconsistent results received from // the remote cache. // /// Invalid response from this method means the request was internally modified and should be retried </remarks> protected internal override CacheValidationStatus ValidateResponse() { if (HttpProxyMode) return base.ValidateResponse(); if (Policy.Level != RequestCacheLevel.Default && Policy.Level != RequestCacheLevel.Revalidate) { // Those policy levels do not modify requests if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_response_valid_based_on_policy, Policy.ToString())); return CacheValidationStatus.Continue; } FtpWebResponse resp = Response as FtpWebResponse; if (resp == null) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_null_response_failure)); return CacheValidationStatus.Continue; } if(Logging.On) Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_ftp_response_status, ((int)resp.StatusCode).ToString(CultureInfo.InvariantCulture), resp.StatusCode.ToString())); // If there was a retry already, it should go with cache disabled so by default we won't retry it again if (ResponseCount > 1) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_resp_valid_based_on_retry, ResponseCount)); return CacheValidationStatus.Continue; } if (resp.StatusCode != FtpStatusCode.OpeningData && resp.StatusCode != FtpStatusCode.FileStatus) { return CacheValidationStatus.RetryResponseFromServer; } return CacheValidationStatus.Continue; } ///This action handler is responsible for making final decision on whether // a received response can be cached. // Invalid result from this method means the response must not be cached protected internal override CacheValidationStatus UpdateCache() { if (HttpProxyMode) return base.UpdateCache(); // An combined cace+wire response is not supported if user has specified a restart offset. CacheStreamOffset = 0L; if (RequestMethod == HttpMethod.Other) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_not_updated_based_on_policy, Request.Method)); return CacheValidationStatus.DoNotUpdateCache; } if (ValidationStatus == CacheValidationStatus.RemoveFromCache) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_removed_existing_invalid_entry)); return CacheValidationStatus.RemoveFromCache; } if (Policy.Level == RequestCacheLevel.CacheOnly) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_not_updated_based_on_policy, Policy.ToString())); return CacheValidationStatus.DoNotUpdateCache; } FtpWebResponse resp = Response as FtpWebResponse; if (resp == null) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_not_updated_because_no_response)); return CacheValidationStatus.DoNotUpdateCache; } // // Check on cache removal based on the request method // if (RequestMethod == HttpMethod.Delete || RequestMethod == HttpMethod.Put) { if (RequestMethod == HttpMethod.Delete || resp.StatusCode == FtpStatusCode.OpeningData || resp.StatusCode == FtpStatusCode.DataAlreadyOpen || resp.StatusCode == FtpStatusCode.FileActionOK || resp.StatusCode == FtpStatusCode.ClosingData) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_removed_existing_based_on_method, Request.Method)); return CacheValidationStatus.RemoveFromCache; } if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_existing_not_removed_because_unexpected_response_status, (int)resp.StatusCode, resp.StatusCode.ToString())); return CacheValidationStatus.DoNotUpdateCache; } if (Policy.Level == RequestCacheLevel.NoCacheNoStore) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_removed_existing_based_on_policy, Policy.ToString())); return CacheValidationStatus.RemoveFromCache; } if (ValidationStatus == CacheValidationStatus.ReturnCachedResponse) { // have a response still returning from cache means just revalidated the entry. return UpdateCacheEntryOnRevalidate(); } if (resp.StatusCode != FtpStatusCode.OpeningData && resp.StatusCode != FtpStatusCode.DataAlreadyOpen && resp.StatusCode != FtpStatusCode.ClosingData) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_not_updated_based_on_ftp_response_status, FtpStatusCode.OpeningData.ToString() + "|" + FtpStatusCode.DataAlreadyOpen.ToString() + "|" + FtpStatusCode.ClosingData.ToString(), resp.StatusCode.ToString())); return CacheValidationStatus.DoNotUpdateCache; } // Check on no-update or cache removal if restart action has invalidated existing cache entry if (((FtpWebRequest)Request).ContentOffset != 0L) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_update_not_supported_for_ftp_restart, ((FtpWebRequest)Request).ContentOffset.ToString(CultureInfo.InvariantCulture))); if (CacheEntry.LastModifiedUtc != DateTime.MinValue && resp.LastModified.ToUniversalTime() != CacheEntry.LastModifiedUtc) { if(Logging.On)Logging.PrintWarning(Logging.RequestCache, SR.GetString(SR.net_log_cache_removed_entry_because_ftp_restart_response_changed, CacheEntry.LastModifiedUtc.ToString("r", CultureInfo.InvariantCulture), resp.LastModified.ToUniversalTime().ToString("r", CultureInfo.InvariantCulture))); return CacheValidationStatus.RemoveFromCache; } return CacheValidationStatus.DoNotUpdateCache; } return UpdateCacheEntryOnStore(); } // // // private CacheValidationStatus UpdateCacheEntryOnStore() { CacheEntry.EntryMetadata = null; CacheEntry.SystemMetadata = null; FtpWebResponse resp = Response as FtpWebResponse; if (resp.LastModified != DateTime.MinValue) { CacheEntry.LastModifiedUtc = resp.LastModified.ToUniversalTime(); } ResponseEntityLength = Response.ContentLength; CacheEntry.StreamSize = ResponseEntityLength; //This is passed down to cache on what size to expect CacheEntry.LastSynchronizedUtc = DateTime.UtcNow; return CacheValidationStatus.CacheResponse; } // // private CacheValidationStatus UpdateCacheEntryOnRevalidate() { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_last_synchronized, CacheEntry.LastSynchronizedUtc.ToString("r", CultureInfo.InvariantCulture))); DateTime nowUtc = DateTime.UtcNow; if (CacheEntry.LastSynchronizedUtc + TimeSpan.FromMinutes(1) >= nowUtc) { if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_suppress_update_because_synched_last_minute)); return CacheValidationStatus.DoNotUpdateCache; } CacheEntry.EntryMetadata = null; CacheEntry.SystemMetadata = null; CacheEntry.LastSynchronizedUtc = nowUtc; if(Logging.On)Logging.PrintInfo(Logging.RequestCache, SR.GetString(SR.net_log_cache_updating_last_synchronized, CacheEntry.LastSynchronizedUtc.ToString("r", CultureInfo.InvariantCulture))); return CacheValidationStatus.UpdateResponseInformation; } // private CacheValidationStatus TryConditionalRequest() { FtpWebRequest request = Request as FtpWebRequest; if (request == null || !request.UseBinary) return CacheValidationStatus.DoNotTakeFromCache; if (request.ContentOffset != 0L) { if (CacheEntry.IsPartialEntry || request.ContentOffset >= CacheStreamLength) return CacheValidationStatus.DoNotTakeFromCache; CacheStreamOffset = request.ContentOffset; } return CacheValidationStatus.Continue; } } }
// *********************************************************************** // Copyright (c) 2010 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.Threading; using NUnit.Framework.Interfaces; using NUnit.Framework.Internal; namespace NUnit.Framework.Attributes { [TestFixture] public class ApplyToTestTests { Test test; [SetUp] public void SetUp() { test = new TestDummy(); test.RunState = RunState.Runnable; } #region CategoryAttribute [TestCase('!')] [TestCase('+')] [TestCase(',')] [TestCase('-')] public void CategoryAttributePassesOnSpecialCharacters(char specialCharacter) { var categoryName = new string(specialCharacter, 5); new CategoryAttribute(categoryName).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo(categoryName)); } [Test] public void CategoryAttributeSetsCategory() { new CategoryAttribute("database").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); } [Test] public void CategoryAttributeSetsCategoryOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new CategoryAttribute("database").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Category), Is.EqualTo("database")); } [Test] public void CategoryAttributeSetsMultipleCategories() { new CategoryAttribute("group1").ApplyToTest(test); new CategoryAttribute("group2").ApplyToTest(test); Assert.That(test.Properties[PropertyNames.Category], Is.EquivalentTo( new string[] { "group1", "group2" } )); } #endregion #region DescriptionAttribute [Test] public void DescriptionAttributeSetsDescription() { new DescriptionAttribute("Cool test!").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); } [Test] public void DescriptionAttributeSetsDescriptionOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new DescriptionAttribute("Cool test!").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.Description), Is.EqualTo("Cool test!")); } #endregion #region IgnoreAttribute [Test] public void IgnoreAttributeIgnoresTest() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeSetsIgnoreReason() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); } [Test] public void IgnoreAttributeDoesNotAffectNonRunnableTest() { test.MakeInvalid("UNCHANGED"); new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED")); } [Test] public void IgnoreAttributeIgnoresTestUntilDateSpecified() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeIgnoresTestUntilDateTimeSpecified() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01 12:00:00Z"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } [Test] public void IgnoreAttributeMarksTestAsRunnableAfterUntilDatePasses() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "1492-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [TestCase("4242-01-01")] [TestCase("4242-01-01 00:00:00Z")] [TestCase("4242-01-01 00:00:00")] public void IgnoreAttributeUntilSetsTheReason(string date) { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = date; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Ignoring until 4242-01-01 00:00:00Z. BECAUSE")); } [Test] public void IgnoreAttributeWithInvalidDateThrowsException() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); Assert.Throws<FormatException>(() => ignoreAttribute.Until = "Thursday the twenty fifth of December"); } [Test] public void IgnoreAttributeWithUntilAddsIgnoreUntilDateProperty() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "4242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("4242-01-01 00:00:00Z")); } [Test] public void IgnoreAttributeWithUntilAddsIgnoreUntilDatePropertyPastUntilDate() { var ignoreAttribute = new IgnoreAttribute("BECAUSE"); ignoreAttribute.Until = "1242-01-01"; ignoreAttribute.ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.IgnoreUntilDate), Is.EqualTo("1242-01-01 00:00:00Z")); } [Test] public void IgnoreAttributeWithExplicitIgnoresTest() { new IgnoreAttribute("BECAUSE").ApplyToTest(test); new ExplicitAttribute().ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } #endregion #region ExplicitAttribute [Test] public void ExplicitAttributeMakesTestExplicit() { new ExplicitAttribute().ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); } [Test] public void ExplicitAttributeSetsIgnoreReason() { new ExplicitAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Explicit)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("BECAUSE")); } [Test] public void ExplicitAttributeDoesNotAffectNonRunnableTest() { test.MakeInvalid("UNCHANGED"); new ExplicitAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("UNCHANGED")); } [Test] public void ExplicitAttributeWithIgnoreIgnoresTest() { new ExplicitAttribute().ApplyToTest(test); new IgnoreAttribute("BECAUSE").ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Ignored)); } #endregion #region CombinatorialAttribute [Test] public void CombinatorialAttributeSetsJoinType() { new CombinatorialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); } [Test] public void CombinatorialAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new CombinatorialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Combinatorial")); } #endregion #region CultureAttribute [Test] public void CultureAttributeIncludingCurrentCultureRunsTest() { string name = System.Globalization.CultureInfo.CurrentCulture.Name; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void CultureAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; string name = System.Globalization.CultureInfo.CurrentCulture.Name; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void CultureAttributeExcludingCurrentCultureSkipsTest() { string name = System.Globalization.CultureInfo.CurrentCulture.Name; CultureAttribute attr = new CultureAttribute(name); attr.Exclude = name; attr.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Not supported under culture " + name)); } [Test] public void CultureAttributeIncludingOtherCultureSkipsTest() { string name = "fr-FR"; if (System.Globalization.CultureInfo.CurrentCulture.Name == name) name = "en-US"; new CultureAttribute(name).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Is.EqualTo("Only supported under culture " + name)); } [Test] public void CultureAttributeExcludingOtherCultureRunsTest() { string other = "fr-FR"; if (System.Globalization.CultureInfo.CurrentCulture.Name == other) other = "en-US"; CultureAttribute attr = new CultureAttribute(); attr.Exclude = other; attr.ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void CultureAttributeWithMultipleCulturesIncluded() { string current = System.Globalization.CultureInfo.CurrentCulture.Name; string other = current == "fr-FR" ? "en-US" : "fr-FR"; string cultures = current + "," + other; new CultureAttribute(cultures).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } #endregion #region MaxTimeAttribute [Test] public void MaxTimeAttributeSetsMaxTime() { new MaxTimeAttribute(2000).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); } [Test] public void MaxTimeAttributeSetsMaxTimeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new MaxTimeAttribute(2000).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.MaxTime), Is.EqualTo(2000)); } #endregion #region PairwiseAttribute [Test] public void PairwiseAttributeSetsJoinType() { new PairwiseAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); } [Test] public void PairwiseAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new PairwiseAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Pairwise")); } #endregion #region PlatformAttribute #if PLATFORM_DETECTION [Test] public void PlatformAttributeRunsTest() { string myPlatform = GetMyPlatform(); new PlatformAttribute(myPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Runnable)); } [Test] public void PlatformAttributeSkipsTest() { string notMyPlatform = System.IO.Path.DirectorySeparatorChar == '/' ? "Win" : "Linux"; new PlatformAttribute(notMyPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.Skipped)); } [Test] public void PlatformAttributeDoesNotAffectNonRunnableTest() { test.RunState = RunState.NotRunnable; string myPlatform = GetMyPlatform(); new PlatformAttribute(myPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); } [Test] public void InvalidPlatformAttributeIsNotRunnable() { var invalidPlatform = "FakePlatform"; new PlatformAttribute(invalidPlatform).ApplyToTest(test); Assert.That(test.RunState, Is.EqualTo(RunState.NotRunnable)); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Does.StartWith("Invalid platform name")); Assert.That(test.Properties.Get(PropertyNames.SkipReason), Does.Contain(invalidPlatform)); } string GetMyPlatform() { if (System.IO.Path.DirectorySeparatorChar == '/') { return OSPlatform.CurrentPlatform.IsMacOSX ? "MacOSX" : "Linux"; } return "Win"; } #endif #endregion #region RepeatAttribute [Test] public void RepeatAttributeSetsRepeatCount() { new RepeatAttribute(5).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); } [Test] public void RepeatAttributeSetsRepeatCountOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new RepeatAttribute(5).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RepeatCount), Is.EqualTo(5)); } #endregion #if PARALLEL #if APARTMENT_STATE #region RequiresMTAAttribute [Test] public void RequiresMTAAttributeSetsApartmentState() { new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.MTA)); } [Test] public void RequiresMTAAttributeSetsApartmentStateOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new ApartmentAttribute(ApartmentState.MTA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.MTA)); } #endregion #region RequiresSTAAttribute [Test] public void RequiresSTAAttributeSetsApartmentState() { new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } [Test] public void RequiresSTAAttributeSetsApartmentStateOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new ApartmentAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } #endregion #endif #region RequiresThreadAttribute [Test] public void RequiresThreadAttributeSetsRequiresThread() { new RequiresThreadAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); } [Test] public void RequiresThreadAttributeSetsRequiresThreadOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new RequiresThreadAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); } #if APARTMENT_STATE [Test] public void RequiresThreadAttributeMaySetApartmentState() { new RequiresThreadAttribute(ApartmentState.STA).ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.RequiresThread), Is.EqualTo(true)); Assert.That(test.Properties.Get(PropertyNames.ApartmentState), Is.EqualTo(ApartmentState.STA)); } #endif #endregion #endif #region SequentialAttribute [Test] public void SequentialAttributeSetsJoinType() { new SequentialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); } [Test] public void SequentialAttributeSetsJoinTypeOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SequentialAttribute().ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.JoinType), Is.EqualTo("Sequential")); } #endregion #if PARALLEL #region SetCultureAttribute public void SetCultureAttributeSetsSetCultureProperty() { new SetCultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); } public void SetCultureAttributeSetsSetCulturePropertyOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SetCultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetCulture), Is.EqualTo("fr-FR")); } #endregion #region SetUICultureAttribute public void SetUICultureAttributeSetsSetUICultureProperty() { new SetUICultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); } public void SetUICultureAttributeSetsSetUICulturePropertyOnNonRunnableTest() { test.RunState = RunState.NotRunnable; new SetUICultureAttribute("fr-FR").ApplyToTest(test); Assert.That(test.Properties.Get(PropertyNames.SetUICulture), Is.EqualTo("fr-FR")); } #endregion #endif } }
namespace Gdn.Migrations { using System; using System.Collections.Generic; using System.Data.Entity.Infrastructure.Annotations; using System.Data.Entity.Migrations; public partial class AbpZero_Initial : DbMigration { public override void Up() { CreateTable( "dbo.AbpAuditLogs", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), ServiceName = c.String(maxLength: 256), MethodName = c.String(maxLength: 256), Parameters = c.String(maxLength: 1024), ExecutionTime = c.DateTime(nullable: false), ExecutionDuration = c.Int(nullable: false), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Exception = c.String(maxLength: 2000), ImpersonatorUserId = c.Long(), ImpersonatorTenantId = c.Int(), CustomData = c.String(maxLength: 2000), }, annotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpBackgroundJobs", c => new { Id = c.Long(nullable: false, identity: true), JobType = c.String(nullable: false, maxLength: 512), JobArgs = c.String(nullable: false), TryCount = c.Short(nullable: false), NextTryTime = c.DateTime(nullable: false), LastTryTime = c.DateTime(), IsAbandoned = c.Boolean(nullable: false), Priority = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id) .Index(t => new { t.IsAbandoned, t.NextTryTime }); CreateTable( "dbo.AbpFeatures", c => new { Id = c.Long(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 128), Value = c.String(nullable: false, maxLength: 2000), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), EditionId = c.Int(), TenantId = c.Int(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpEditions", t => t.EditionId, cascadeDelete: true) .Index(t => t.EditionId); CreateTable( "dbo.AbpEditions", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(nullable: false, maxLength: 32), DisplayName = c.String(nullable: false, maxLength: 64), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguages", c => new { Id = c.Int(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 10), DisplayName = c.String(nullable: false, maxLength: 64), Icon = c.String(maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpLanguageTexts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), LanguageName = c.String(nullable: false, maxLength: 10), Source = c.String(nullable: false, maxLength: 128), Key = c.String(nullable: false, maxLength: 256), Value = c.String(nullable: false), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotifications", c => new { Id = c.Guid(nullable: false), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), UserIds = c.String(), ExcludedUserIds = c.String(), TenantIds = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpNotificationSubscriptions", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), NotificationName = c.String(maxLength: 96), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.NotificationName, t.EntityTypeName, t.EntityId, t.UserId }); CreateTable( "dbo.AbpOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), ParentId = c.Long(), Code = c.String(nullable: false, maxLength: 95), DisplayName = c.String(nullable: false, maxLength: 128), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpOrganizationUnits", t => t.ParentId) .Index(t => t.ParentId); CreateTable( "dbo.AbpPermissions", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsGranted = c.Boolean(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), RoleId = c.Int(), UserId = c.Long(), Discriminator = c.String(nullable: false, maxLength: 128), }, annotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .ForeignKey("dbo.AbpRoles", t => t.RoleId, cascadeDelete: true) .Index(t => t.RoleId) .Index(t => t.UserId); CreateTable( "dbo.AbpRoles", c => new { Id = c.Int(nullable: false, identity: true), DisplayName = c.String(nullable: false, maxLength: 64), IsStatic = c.Boolean(nullable: false), IsDefault = c.Boolean(nullable: false), TenantId = c.Int(), Name = c.String(nullable: false, maxLength: 32), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUsers", c => new { Id = c.Long(nullable: false, identity: true), AuthenticationSource = c.String(maxLength: 64), Name = c.String(nullable: false, maxLength: 32), Surname = c.String(nullable: false, maxLength: 32), Password = c.String(nullable: false, maxLength: 128), IsEmailConfirmed = c.Boolean(nullable: false), EmailConfirmationCode = c.String(maxLength: 328), PasswordResetCode = c.String(maxLength: 328), LockoutEndDateUtc = c.DateTime(), AccessFailedCount = c.Int(nullable: false), IsLockoutEnabled = c.Boolean(nullable: false), PhoneNumber = c.String(), IsPhoneNumberConfirmed = c.Boolean(nullable: false), SecurityStamp = c.String(), IsTwoFactorEnabled = c.Boolean(nullable: false), IsActive = c.Boolean(nullable: false), UserName = c.String(nullable: false, maxLength: 32), TenantId = c.Int(), EmailAddress = c.String(nullable: false, maxLength: 256), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserClaims", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), ClaimType = c.String(), ClaimValue = c.String(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserLogins", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), LoginProvider = c.String(nullable: false, maxLength: 128), ProviderKey = c.String(nullable: false, maxLength: 256), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpUserRoles", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), RoleId = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId, cascadeDelete: true) .Index(t => t.UserId); CreateTable( "dbo.AbpSettings", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(), Name = c.String(nullable: false, maxLength: 256), Value = c.String(maxLength: 2000), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.UserId) .Index(t => t.UserId); CreateTable( "dbo.AbpTenantNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), NotificationName = c.String(nullable: false, maxLength: 96), Data = c.String(), DataTypeName = c.String(maxLength: 512), EntityTypeName = c.String(maxLength: 250), EntityTypeAssemblyQualifiedName = c.String(maxLength: 512), EntityId = c.String(maxLength: 96), Severity = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpTenants", c => new { Id = c.Int(nullable: false, identity: true), EditionId = c.Int(), Name = c.String(nullable: false, maxLength: 128), IsActive = c.Boolean(nullable: false), TenancyName = c.String(nullable: false, maxLength: 64), ConnectionString = c.String(maxLength: 1024), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AbpUsers", t => t.CreatorUserId) .ForeignKey("dbo.AbpUsers", t => t.DeleterUserId) .ForeignKey("dbo.AbpEditions", t => t.EditionId) .ForeignKey("dbo.AbpUsers", t => t.LastModifierUserId) .Index(t => t.EditionId) .Index(t => t.DeleterUserId) .Index(t => t.LastModifierUserId) .Index(t => t.CreatorUserId); CreateTable( "dbo.AbpUserAccounts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), UserLinkId = c.Long(), UserName = c.String(), EmailAddress = c.String(), LastLoginTime = c.DateTime(), IsDeleted = c.Boolean(nullable: false), DeleterUserId = c.Long(), DeletionTime = c.DateTime(), LastModificationTime = c.DateTime(), LastModifierUserId = c.Long(), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateTable( "dbo.AbpUserLoginAttempts", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), TenancyName = c.String(maxLength: 64), UserId = c.Long(), UserNameOrEmailAddress = c.String(maxLength: 255), ClientIpAddress = c.String(maxLength: 64), ClientName = c.String(maxLength: 128), BrowserInfo = c.String(maxLength: 256), Result = c.Byte(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.TenantId }) .Index(t => new { t.TenancyName, t.UserNameOrEmailAddress, t.Result }); CreateTable( "dbo.AbpUserNotifications", c => new { Id = c.Guid(nullable: false), TenantId = c.Int(), UserId = c.Long(nullable: false), TenantNotificationId = c.Guid(nullable: false), State = c.Int(nullable: false), CreationTime = c.DateTime(nullable: false), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id) .Index(t => new { t.UserId, t.State, t.CreationTime }); CreateTable( "dbo.AbpUserOrganizationUnits", c => new { Id = c.Long(nullable: false, identity: true), TenantId = c.Int(), UserId = c.Long(nullable: false), OrganizationUnitId = c.Long(nullable: false), CreationTime = c.DateTime(nullable: false), CreatorUserId = c.Long(), }, annotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }) .PrimaryKey(t => t.Id); CreateIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" }); CreateIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" }); CreateIndex("AbpEditions", new[] { "Name" }); CreateIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" }); CreateIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" }); CreateIndex("AbpFeatures", new[] { "TenantId", "Name" }); CreateIndex("AbpLanguages", new[] { "TenantId", "Name" }); CreateIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" }); CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" }); CreateIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" }); DropIndex("AbpPermissions", new[] { "UserId" }); DropIndex("AbpPermissions", new[] { "RoleId" }); CreateIndex("AbpPermissions", new[] { "UserId", "Name" }); CreateIndex("AbpPermissions", new[] { "RoleId", "Name" }); CreateIndex("AbpRoles", new[] { "TenantId", "Name" }); CreateIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" }); DropIndex("AbpSettings", new[] { "UserId" }); CreateIndex("AbpSettings", new[] { "TenantId", "Name" }); CreateIndex("AbpSettings", new[] { "UserId", "Name" }); CreateIndex("AbpTenants", new[] { "TenancyName" }); CreateIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" }); DropIndex("AbpUserLogins", new[] { "UserId" }); CreateIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" }); CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" }); CreateIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" }); CreateIndex("AbpUserOrganizationUnits", new[] { "UserId" }); CreateIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" }); DropIndex("AbpUserRoles", new[] { "UserId" }); CreateIndex("AbpUserRoles", new[] { "UserId", "RoleId" }); CreateIndex("AbpUserRoles", new[] { "RoleId" }); CreateIndex("AbpUsers", new[] { "TenantId", "UserName" }); CreateIndex("AbpUsers", new[] { "TenantId", "EmailAddress" }); CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" }); CreateIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" }); } public override void Down() { DropIndex("AbpAuditLogs", new[] { "TenantId", "ExecutionTime" }); DropIndex("AbpAuditLogs", new[] { "UserId", "ExecutionTime" }); DropIndex("AbpEditions", new[] { "Name" }); DropIndex("AbpFeatures", new[] { "Discriminator", "TenantId", "Name" }); DropIndex("AbpFeatures", new[] { "Discriminator", "EditionId", "Name" }); DropIndex("AbpFeatures", new[] { "TenantId", "Name" }); DropIndex("AbpLanguages", new[] { "TenantId", "Name" }); DropIndex("AbpLanguageTexts", new[] { "TenantId", "LanguageName", "Source", "Key" }); DropIndex("AbpOrganizationUnits", new[] { "TenantId", "ParentId" }); DropIndex("AbpOrganizationUnits", new[] { "TenantId", "Code" }); CreateIndex("AbpPermissions", new[] { "UserId" }); CreateIndex("AbpPermissions", new[] { "RoleId" }); DropIndex("AbpPermissions", new[] { "UserId", "Name" }); DropIndex("AbpPermissions", new[] { "RoleId", "Name" }); DropIndex("AbpRoles", new[] { "TenantId", "Name" }); DropIndex("AbpRoles", new[] { "IsDeleted", "TenantId", "Name" }); CreateIndex("AbpSettings", new[] { "UserId" }); DropIndex("AbpSettings", new[] { "TenantId", "Name" }); DropIndex("AbpSettings", new[] { "UserId", "Name" }); DropIndex("AbpTenants", new[] { "TenancyName" }); DropIndex("AbpTenants", new[] { "IsDeleted", "TenancyName" }); CreateIndex("AbpUserLogins", new[] { "UserId" }); DropIndex("AbpUserLogins", new[] { "UserId", "LoginProvider" }); DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "UserId" }); DropIndex("AbpUserOrganizationUnits", new[] { "TenantId", "OrganizationUnitId" }); DropIndex("AbpUserOrganizationUnits", new[] { "UserId" }); DropIndex("AbpUserOrganizationUnits", new[] { "OrganizationUnitId" }); CreateIndex("AbpUserRoles", new[] { "UserId" }); DropIndex("AbpUserRoles", new[] { "UserId", "RoleId" }); DropIndex("AbpUserRoles", new[] { "RoleId" }); DropIndex("AbpUsers", new[] { "TenantId", "UserName" }); DropIndex("AbpUsers", new[] { "TenantId", "EmailAddress" }); DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "UserName" }); DropIndex("AbpUsers", new[] { "IsDeleted", "TenantId", "EmailAddress" }); DropForeignKey("dbo.AbpTenants", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "EditionId", "dbo.AbpEditions"); DropForeignKey("dbo.AbpTenants", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpTenants", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "RoleId", "dbo.AbpRoles"); DropForeignKey("dbo.AbpRoles", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpRoles", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpSettings", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserRoles", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpPermissions", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserLogins", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "LastModifierUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "DeleterUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUsers", "CreatorUserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpUserClaims", "UserId", "dbo.AbpUsers"); DropForeignKey("dbo.AbpOrganizationUnits", "ParentId", "dbo.AbpOrganizationUnits"); DropForeignKey("dbo.AbpFeatures", "EditionId", "dbo.AbpEditions"); DropIndex("dbo.AbpUserNotifications", new[] { "UserId", "State", "CreationTime" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "TenancyName", "UserNameOrEmailAddress", "Result" }); DropIndex("dbo.AbpUserLoginAttempts", new[] { "UserId", "TenantId" }); DropIndex("dbo.AbpTenants", new[] { "CreatorUserId" }); DropIndex("dbo.AbpTenants", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpTenants", new[] { "DeleterUserId" }); DropIndex("dbo.AbpTenants", new[] { "EditionId" }); DropIndex("dbo.AbpSettings", new[] { "UserId" }); DropIndex("dbo.AbpUserRoles", new[] { "UserId" }); DropIndex("dbo.AbpUserLogins", new[] { "UserId" }); DropIndex("dbo.AbpUserClaims", new[] { "UserId" }); DropIndex("dbo.AbpUsers", new[] { "CreatorUserId" }); DropIndex("dbo.AbpUsers", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpUsers", new[] { "DeleterUserId" }); DropIndex("dbo.AbpRoles", new[] { "CreatorUserId" }); DropIndex("dbo.AbpRoles", new[] { "LastModifierUserId" }); DropIndex("dbo.AbpRoles", new[] { "DeleterUserId" }); DropIndex("dbo.AbpPermissions", new[] { "UserId" }); DropIndex("dbo.AbpPermissions", new[] { "RoleId" }); DropIndex("dbo.AbpOrganizationUnits", new[] { "ParentId" }); DropIndex("dbo.AbpNotificationSubscriptions", new[] { "NotificationName", "EntityTypeName", "EntityId", "UserId" }); DropIndex("dbo.AbpFeatures", new[] { "EditionId" }); DropIndex("dbo.AbpBackgroundJobs", new[] { "IsAbandoned", "NextTryTime" }); DropTable("dbo.AbpUserOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserOrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLoginAttempts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLoginAttempt_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserAccounts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserAccount_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenants", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Tenant_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpTenantNotifications", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantNotificationInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpSettings", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Setting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserRole_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserLogins", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserLogin_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUserClaims", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_UserClaim_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpUsers", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_User_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_User_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpRoles", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Role_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_Role_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpPermissions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_PermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_RolePermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_UserPermissionSetting_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpOrganizationUnits", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_OrganizationUnit_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_OrganizationUnit_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotificationSubscriptions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_NotificationSubscriptionInfo_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpNotifications"); DropTable("dbo.AbpLanguageTexts", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguageText_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpLanguages", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_ApplicationLanguage_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, { "DynamicFilter_ApplicationLanguage_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpEditions", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_Edition_SoftDelete", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpFeatures", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_TenantFeatureSetting_MustHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); DropTable("dbo.AbpBackgroundJobs"); DropTable("dbo.AbpAuditLogs", removedAnnotations: new Dictionary<string, object> { { "DynamicFilter_AuditLog_MayHaveTenant", "EntityFramework.DynamicFilters.DynamicFilterDefinition" }, }); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Shared.TestHooks; using Microsoft.CodeAnalysis.SolutionCrawler; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Composition; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using Microsoft.CodeAnalysis.Editor.UnitTests.Utilities; namespace Microsoft.CodeAnalysis.Editor.UnitTests.SolutionCrawler { public class WorkCoordinatorTests { private const string SolutionCrawler = nameof(SolutionCrawler); [Fact] public async Task RegisterService() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var registrationService = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), AggregateAsynchronousOperationListener.EmptyListeners); // register and unregister workspace to the service registrationService.Register(workspace); registrationService.Unregister(workspace); // make sure we wait for all waiter. the test wrongly assumed there won't be // any pending async event which is implementation detail when creating workspace // and changing options. await WaitWaiterAsync(workspace.ExportProvider); } } [Fact] public async Task DynamicallyAddAnalyzer() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { // create solution and wait for it to settle var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); // create solution crawler and add new analyzer provider dynamically var service = new SolutionCrawlerRegistrationService( SpecializedCollections.EmptyEnumerable<Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>>(), GetListeners(workspace.ExportProvider)); service.Register(workspace); var provider = new AnalyzerProvider(new Analyzer()); service.AddAnalyzerProvider(provider, Metadata.Crawler); // wait for everything to settle await WaitAsync(service, workspace); service.Unregister(workspace); // check whether everything ran as expected Assert.Equal(10, provider.Analyzer.SyntaxDocumentIds.Count); Assert.Equal(10, provider.Analyzer.DocumentIds.Count); } } [Fact, WorkItem(747226, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/747226")] public async Task SolutionAdded_Simple() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionId = SolutionId.CreateNewId(); var projectId = ProjectId.CreateNewId(); var solutionInfo = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1") }) }); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solutionInfo)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task SolutionAdded_Complex() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); var worker = await ExecuteOperation(workspace, w => w.OnSolutionAdded(solution)); Assert.Equal(10, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Solution_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.OnSolutionRemoved()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Solution_Clear() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.ClearSolution()); Assert.Equal(10, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Solution_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.OnSolutionReloaded(solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Solution_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var solution = workspace.CurrentSolution; var documentId = solution.Projects.First().DocumentIds[0]; solution = solution.RemoveDocument(documentId); var changedSolution = solution.AddProject("P3", "P3", LanguageNames.CSharp).AddDocument("D1", "").Project.Solution; var worker = await ExecuteOperation(workspace, w => w.ChangeSolution(changedSolution)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Project_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectId = ProjectId.CreateNewId(); var projectInfo = ProjectInfo.Create( projectId, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new List<DocumentInfo> { DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId), "D2") }); var worker = await ExecuteOperation(workspace, w => w.OnProjectAdded(projectInfo)); Assert.Equal(2, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Project_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var projectid = workspace.CurrentSolution.ProjectIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectRemoved(projectid)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Project_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(); var documentId = project.DocumentIds[0]; var solution = workspace.CurrentSolution.RemoveDocument(documentId); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, solution)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Project_AssemblyName_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").WithAssemblyName("newName"); var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public async Task Project_AnalyzerOptions_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var project = workspace.CurrentSolution.Projects.First(p => p.Name == "P1").AddAdditionalDocument("a1", SourceText.From("")).Project; var worker = await ExecuteOperation(workspace, w => w.ChangeProject(project.Id, project.Solution)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [Fact] public async Task Test_NeedsReanalysisOnOptionChanged() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solutionInfo = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solutionInfo); await WaitWaiterAsync(workspace.ExportProvider); var worker = await ExecuteOperation(workspace, w => w.Options = w.Options.WithChangedOption(Analyzer.TestOption, false)); Assert.Equal(10, worker.SyntaxDocumentIds.Count); Assert.Equal(10, worker.DocumentIds.Count); Assert.Equal(2, worker.ProjectIds.Count); } } [Fact] public async Task Project_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var worker = await ExecuteOperation(workspace, w => w.OnProjectReloaded(project)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_Add() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var info = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(6, worker.DocumentIds.Count); } } [Fact] public async Task Document_Remove() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentRemoved(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); Assert.Equal(1, worker.InvalidateDocumentIds.Count); } } [Fact] public async Task Document_Reload() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Documents[0]; var worker = await ExecuteOperation(workspace, w => w.OnDocumentReloaded(id)); Assert.Equal(0, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_Reanalyze() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var info = solution.Projects[0].Documents[0]; var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. await TouchEverything(workspace.CurrentSolution); service.Reanalyze(workspace, worker, projectIds: null, documentIds: SpecializedCollections.SingletonEnumerable<DocumentId>(info.Id), highPriority: false); await TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(1, worker.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Change() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var worker = await ExecuteOperation(workspace, w => w.ChangeDocument(id, SourceText.From("//"))); Assert.Equal(1, worker.SyntaxDocumentIds.Count); } } [Fact] public async Task Document_AdditionalFileChange() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var project = solution.Projects[0]; var ncfile = DocumentInfo.Create(DocumentId.CreateNewId(project.Id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentAdded(ncfile)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.ChangeAdditionalDocument(ncfile.Id, SourceText.From("//"))); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); worker = await ExecuteOperation(workspace, w => w.OnAdditionalDocumentRemoved(ncfile.Id)); Assert.Equal(5, worker.SyntaxDocumentIds.Count); Assert.Equal(5, worker.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Cancellation() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_Cancellation_MultipleTimes() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(waitForCancellation: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); analyzer.RunningEvent.Reset(); workspace.ChangeDocument(id, SourceText.From("// ")); analyzer.RunningEvent.Wait(); workspace.ChangeDocument(id, SourceText.From("// ")); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [WorkItem(670335, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/670335")] public async Task Document_InvocationReasons() { using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { var solution = GetInitialSolutionInfo_2Projects_10Documents(workspace); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = workspace.CurrentSolution.Projects.First().DocumentIds[0]; var analyzer = new Analyzer(blockedRun: true); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // first invocation will block worker workspace.ChangeDocument(id, SourceText.From("//")); analyzer.RunningEvent.Wait(); var openReady = new ManualResetEventSlim(initialState: false); var closeReady = new ManualResetEventSlim(initialState: false); workspace.DocumentOpened += (o, e) => openReady.Set(); workspace.DocumentClosed += (o, e) => closeReady.Set(); // cause several different request to queue up workspace.ChangeDocument(id, SourceText.From("// ")); workspace.OpenDocument(id); workspace.CloseDocument(id); openReady.Set(); closeReady.Set(); analyzer.BlockEvent.Set(); await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(5, analyzer.DocumentIds.Count); } } [Fact] public async Task Document_TopLevelType_Whitespace() { var code = @"class C { $$ }"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_Character() { var code = @"class C { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_NewLine() { var code = @"class C { $$ }"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelType_NewLine2() { var code = @"class C { $$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_EmptyFile() { var code = @"$$"; var textToInsert = "class"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel1() { var code = @"class C { public void Test($$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel2() { var code = @"class C { public void Test(int $$"; var textToInsert = " "; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevel3() { var code = @"class C { public void Test(int i,$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_InteriorNode1() { var code = @"class C { public void Test() {$$"; var textToInsert = "\r\n"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode2() { var code = @"class C { public void Test() { $$ }"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Field() { var code = @"class C { int i = $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Field1() { var code = @"class C { int i = 1 + $$ }"; var textToInsert = "1"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_InteriorNode_Accessor() { var code = @"class C { public int A { get { $$ } } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: false); } [Fact] public async Task Document_TopLevelWhitespace() { var code = @"class C { /// $$ public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_TopLevelWhitespace2() { var code = @"/// $$ class C { public int A() { } }"; var textToInsert = "return"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public async Task Document_InteriorNode_Malformed() { var code = @"class C { public void Test() { $$"; var textToInsert = "int"; await InsertText(code, textToInsert, expectDocumentAnalysis: true); } [Fact] public void VBPropertyTest() { var markup = @"Class C Default Public Property G(x As Integer) As Integer Get $$ End Get Set(value As Integer) End Set End Property End Class"; MarkupTestFile.GetPosition(markup, out var code, out int position); var root = Microsoft.CodeAnalysis.VisualBasic.SyntaxFactory.ParseCompilationUnit(code); var property = root.FindToken(position).Parent.FirstAncestorOrSelf<Microsoft.CodeAnalysis.VisualBasic.Syntax.PropertyBlockSyntax>(); var memberId = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxFactsService.Instance.GetMethodLevelMemberId(root, property); Assert.Equal(0, memberId); } [Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")] public async Task SemanticChange_Propagation_Transitive() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, false); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(4, worker.DocumentIds.Count); } } [Fact, WorkItem(739943, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/739943")] public async Task SemanticChange_Propagation_Direct() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.DirectDependencyPropagationOnly, true); workspace.OnSolutionAdded(solution); await WaitWaiterAsync(workspace.ExportProvider); var id = solution.Projects[0].Id; var info = DocumentInfo.Create(DocumentId.CreateNewId(id), "D6"); var worker = await ExecuteOperation(workspace, w => w.OnDocumentAdded(info)); Assert.Equal(1, worker.SyntaxDocumentIds.Count); Assert.Equal(3, worker.DocumentIds.Count); } } [Fact] public async Task ProgressReporterTest() { var solution = GetInitialSolutionInfoWithP2P(); using (var workspace = new WorkCoordinatorWorkspace(SolutionCrawler)) { await WaitWaiterAsync(workspace.ExportProvider); var service = workspace.Services.GetService<ISolutionCrawlerService>(); var reporter = service.GetProgressReporter(workspace); Assert.False(reporter.InProgress); // set up events bool started = false; reporter.Started += (o, a) => { started = true; }; bool stopped = false; reporter.Stopped += (o, a) => { stopped = true; }; var registrationService = workspace.Services.GetService<ISolutionCrawlerRegistrationService>(); registrationService.Register(workspace); // first mutation workspace.OnSolutionAdded(solution); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); // reset started = false; stopped = false; // second mutation workspace.OnDocumentAdded(DocumentInfo.Create(DocumentId.CreateNewId(solution.Projects[0].Id), "D6")); await WaitAsync((SolutionCrawlerRegistrationService)registrationService, workspace); Assert.True(started); Assert.True(stopped); registrationService.Unregister(workspace); } } private async Task InsertText(string code, string text, bool expectDocumentAnalysis, string language = LanguageNames.CSharp) { using (var workspace = await TestWorkspace.CreateAsync( SolutionCrawler, language, compilationOptions: null, parseOptions: null, content: code, exportProvider: EditorServicesUtil.ExportProvider)) { SetOptions(workspace); var analyzer = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(analyzer), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); var testDocument = workspace.Documents.First(); var insertPosition = testDocument.CursorPosition; var textBuffer = testDocument.GetTextBuffer(); using (var edit = textBuffer.CreateEdit()) { edit.Insert(insertPosition.Value, text); edit.Apply(); } await WaitAsync(service, workspace); service.Unregister(workspace); Assert.Equal(1, analyzer.SyntaxDocumentIds.Count); Assert.Equal(expectDocumentAnalysis ? 1 : 0, analyzer.DocumentIds.Count); } } private async Task<Analyzer> ExecuteOperation(TestWorkspace workspace, Action<TestWorkspace> operation) { var worker = new Analyzer(); var lazyWorker = new Lazy<IIncrementalAnalyzerProvider, IncrementalAnalyzerProviderMetadata>(() => new AnalyzerProvider(worker), Metadata.Crawler); var service = new SolutionCrawlerRegistrationService(new[] { lazyWorker }, GetListeners(workspace.ExportProvider)); service.Register(workspace); // don't rely on background parser to have tree. explicitly do it here. await TouchEverything(workspace.CurrentSolution); operation(workspace); await TouchEverything(workspace.CurrentSolution); await WaitAsync(service, workspace); service.Unregister(workspace); return worker; } private async Task TouchEverything(Solution solution) { foreach (var project in solution.Projects) { foreach (var document in project.Documents) { await document.GetTextAsync(); await document.GetSyntaxRootAsync(); await document.GetSemanticModelAsync(); } } } private async Task WaitAsync(SolutionCrawlerRegistrationService service, TestWorkspace workspace) { await WaitWaiterAsync(workspace.ExportProvider); service.WaitUntilCompletion_ForTestingPurposesOnly(workspace); } private async Task WaitWaiterAsync(ExportProvider provider) { var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; await workspaceWaiter.CreateWaitTask(); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; await solutionCrawlerWaiter.CreateWaitTask(); } private static SolutionInfo GetInitialSolutionInfoWithP2P() { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); var projectId3 = ProjectId.CreateNewId(); var projectId4 = ProjectId.CreateNewId(); var projectId5 = ProjectId.CreateNewId(); var solution = SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2") }, projectReferences: new[] { new ProjectReference(projectId1) }), ProjectInfo.Create(projectId3, VersionStamp.Create(), "P3", "P3", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId3), "D3") }, projectReferences: new[] { new ProjectReference(projectId2) }), ProjectInfo.Create(projectId4, VersionStamp.Create(), "P4", "P4", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId4), "D4") }), ProjectInfo.Create(projectId5, VersionStamp.Create(), "P5", "P5", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId5), "D5") }, projectReferences: new[] { new ProjectReference(projectId4) }), }); return solution; } private static SolutionInfo GetInitialSolutionInfo_2Projects_10Documents(TestWorkspace workspace) { var projectId1 = ProjectId.CreateNewId(); var projectId2 = ProjectId.CreateNewId(); return SolutionInfo.Create(SolutionId.CreateNewId(), VersionStamp.Create(), projects: new[] { ProjectInfo.Create(projectId1, VersionStamp.Create(), "P1", "P1", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId1), "D5") }), ProjectInfo.Create(projectId2, VersionStamp.Create(), "P2", "P2", LanguageNames.CSharp, documents: new[] { DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D1"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D2"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D3"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D4"), DocumentInfo.Create(DocumentId.CreateNewId(projectId2), "D5") }) }); } private static IEnumerable<Lazy<IAsynchronousOperationListener, FeatureMetadata>> GetListeners(ExportProvider provider) { return provider.GetExports<IAsynchronousOperationListener, FeatureMetadata>(); } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.SolutionCrawler)] private class SolutionCrawlerWaiter : AsynchronousOperationListener { internal SolutionCrawlerWaiter() { } } [Shared] [Export(typeof(IAsynchronousOperationListener))] [Export(typeof(IAsynchronousOperationWaiter))] [Feature(FeatureAttribute.Workspace)] private class WorkspaceWaiter : AsynchronousOperationListener { internal WorkspaceWaiter() { } } private static void SetOptions(Workspace workspace) { // override default timespan to make test run faster workspace.Options = workspace.Options.WithChangedOption(InternalSolutionCrawlerOptions.ActiveFileWorkerBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.AllFilesWorkerBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.PreviewBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.ProjectPropagationBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.SemanticChangeBackOffTimeSpanInMS, 0) .WithChangedOption(InternalSolutionCrawlerOptions.EntireProjectWorkerBackOffTimeSpanInMS, 100); } private class WorkCoordinatorWorkspace : TestWorkspace { private readonly IAsynchronousOperationWaiter _workspaceWaiter; private readonly IAsynchronousOperationWaiter _solutionCrawlerWaiter; public WorkCoordinatorWorkspace(string workspaceKind = null, bool disablePartialSolutions = true) : base(EditorServicesUtil.CreateExportProvider(), workspaceKind, disablePartialSolutions) { _workspaceWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as IAsynchronousOperationWaiter; _solutionCrawlerWaiter = GetListeners(ExportProvider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as IAsynchronousOperationWaiter; Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); SetOptions(this); } protected override void Dispose(bool finalize) { base.Dispose(finalize); Assert.False(_workspaceWaiter.HasPendingWork); Assert.False(_solutionCrawlerWaiter.HasPendingWork); } } private class AnalyzerProvider : IIncrementalAnalyzerProvider { public readonly Analyzer Analyzer; public AnalyzerProvider(Analyzer analyzer) { Analyzer = analyzer; } public IIncrementalAnalyzer CreateIncrementalAnalyzer(Workspace workspace) { return Analyzer; } } internal class Metadata : IncrementalAnalyzerProviderMetadata { public Metadata(params string[] workspaceKinds) : base(new Dictionary<string, object> { { "WorkspaceKinds", workspaceKinds }, { "HighPriorityForActiveFile", false }, { "Name", "TestAnalyzer" } }) { } public static readonly Metadata Crawler = new Metadata(SolutionCrawler); } private class Analyzer : IIncrementalAnalyzer { public static readonly Option<bool> TestOption = new Option<bool>("TestOptions", "TestOption", defaultValue: true); private readonly bool _waitForCancellation; private readonly bool _blockedRun; public readonly ManualResetEventSlim BlockEvent; public readonly ManualResetEventSlim RunningEvent; public readonly HashSet<DocumentId> SyntaxDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<DocumentId> DocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> ProjectIds = new HashSet<ProjectId>(); public readonly HashSet<DocumentId> InvalidateDocumentIds = new HashSet<DocumentId>(); public readonly HashSet<ProjectId> InvalidateProjectIds = new HashSet<ProjectId>(); public Analyzer(bool waitForCancellation = false, bool blockedRun = false) { _waitForCancellation = waitForCancellation; _blockedRun = blockedRun; this.BlockEvent = new ManualResetEventSlim(initialState: false); this.RunningEvent = new ManualResetEventSlim(initialState: false); } public Task AnalyzeProjectAsync(Project project, bool semanticsChanged, InvocationReasons reasons, CancellationToken cancellationToken) { this.ProjectIds.Add(project.Id); return SpecializedTasks.EmptyTask; } public Task AnalyzeDocumentAsync(Document document, SyntaxNode bodyOpt, InvocationReasons reasons, CancellationToken cancellationToken) { if (bodyOpt == null) { this.DocumentIds.Add(document.Id); } return SpecializedTasks.EmptyTask; } public Task AnalyzeSyntaxAsync(Document document, InvocationReasons reasons, CancellationToken cancellationToken) { this.SyntaxDocumentIds.Add(document.Id); Process(document.Id, cancellationToken); return SpecializedTasks.EmptyTask; } public void RemoveDocument(DocumentId documentId) { InvalidateDocumentIds.Add(documentId); } public void RemoveProject(ProjectId projectId) { InvalidateProjectIds.Add(projectId); } private void Process(DocumentId documentId, CancellationToken cancellationToken) { if (_blockedRun && !RunningEvent.IsSet) { this.RunningEvent.Set(); // Wait until unblocked this.BlockEvent.Wait(); } if (_waitForCancellation && !RunningEvent.IsSet) { this.RunningEvent.Set(); cancellationToken.WaitHandle.WaitOne(); cancellationToken.ThrowIfCancellationRequested(); } } public bool NeedsReanalysisOnOptionChanged(object sender, OptionChangedEventArgs e) { return e.Option == TestOption; } #region unused public Task NewSolutionSnapshotAsync(Solution solution, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentOpenAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentCloseAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } public Task DocumentResetAsync(Document document, CancellationToken cancellationToken) { return SpecializedTasks.EmptyTask; } #endregion } #if false private string GetListenerTrace(ExportProvider provider) { var sb = new StringBuilder(); var workspaceWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.Workspace).Value as TestAsynchronousOperationListener; sb.AppendLine("workspace"); sb.AppendLine(workspaceWaiter.Trace()); var solutionCrawlerWaiter = GetListeners(provider).First(l => l.Metadata.FeatureName == FeatureAttribute.SolutionCrawler).Value as TestAsynchronousOperationListener; sb.AppendLine("solutionCrawler"); sb.AppendLine(solutionCrawlerWaiter.Trace()); return sb.ToString(); } internal abstract partial class TestAsynchronousOperationListener : IAsynchronousOperationListener, IAsynchronousOperationWaiter { private readonly object gate = new object(); private readonly HashSet<TaskCompletionSource<bool>> pendingTasks = new HashSet<TaskCompletionSource<bool>>(); private readonly StringBuilder sb = new StringBuilder(); private int counter; public TestAsynchronousOperationListener() { } public IAsyncToken BeginAsyncOperation(string name, object tag = null) { lock (gate) { return new AsyncToken(this, name); } } private void Increment(string name) { lock (gate) { sb.AppendLine("i -> " + name + ":" + counter++); } } private void Decrement(string name) { lock (gate) { counter--; if (counter == 0) { foreach (var task in pendingTasks) { task.SetResult(true); } pendingTasks.Clear(); } sb.AppendLine("d -> " + name + ":" + counter); } } public virtual Task CreateWaitTask() { lock (gate) { var source = new TaskCompletionSource<bool>(); if (counter == 0) { // There is nothing to wait for, so we are immediately done source.SetResult(true); } else { pendingTasks.Add(source); } return source.Task; } } public bool TrackActiveTokens { get; set; } public bool HasPendingWork { get { return counter != 0; } } private class AsyncToken : IAsyncToken { private readonly TestAsynchronousOperationListener listener; private readonly string name; private bool disposed; public AsyncToken(TestAsynchronousOperationListener listener, string name) { this.listener = listener; this.name = name; listener.Increment(name); } public void Dispose() { lock (listener.gate) { if (disposed) { throw new InvalidOperationException("Double disposing of an async token"); } disposed = true; listener.Decrement(this.name); } } } public string Trace() { return sb.ToString(); } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO; using System.Threading; namespace System.Net.Security { // // This is a wrapping stream that does data encryption/decryption based on a successfully authenticated SSPI context. // internal class SslStreamInternal { private static readonly AsyncCallback s_writeCallback = new AsyncCallback(WriteCallback); private static readonly AsyncProtocolCallback s_resumeAsyncWriteCallback = new AsyncProtocolCallback(ResumeAsyncWriteCallback); private static readonly AsyncProtocolCallback s_resumeAsyncReadCallback = new AsyncProtocolCallback(ResumeAsyncReadCallback); private static readonly AsyncProtocolCallback s_readHeaderCallback = new AsyncProtocolCallback(ReadHeaderCallback); private static readonly AsyncProtocolCallback s_readFrameCallback = new AsyncProtocolCallback(ReadFrameCallback); private const int PinnableReadBufferSize = 4096 * 4 + 32; // We read in 16K chunks + headers. private static PinnableBufferCache s_PinnableReadBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableReadBufferSize); private const int PinnableWriteBufferSize = 4096 + 1024; // We write in 4K chunks + encryption overhead. private static PinnableBufferCache s_PinnableWriteBufferCache = new PinnableBufferCache("System.Net.SslStream", PinnableWriteBufferSize); private SslState _sslState; private int _nestedWrite; private int _nestedRead; // Never updated directly, special properties are used. This is the read buffer. private byte[] _internalBuffer; private bool _internalBufferFromPinnableCache; private byte[] _pinnableOutputBuffer; // Used for writes when we can do it. private byte[] _pinnableOutputBufferInUse; // Remembers what UNENCRYPTED buffer is using _PinnableOutputBuffer. private int _internalOffset; private int _internalBufferCount; private FixedSizeReader _reader; internal SslStreamInternal(SslState sslState) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("CTOR: In System.Net._SslStream.SslStream", this.GetHashCode()); } _sslState = sslState; _reader = new FixedSizeReader(_sslState.InnerStream); } // If we have a read buffer from the pinnable cache, return it. private void FreeReadBuffer() { if (_internalBufferFromPinnableCache) { s_PinnableReadBufferCache.FreeBuffer(_internalBuffer); _internalBufferFromPinnableCache = false; } _internalBuffer = null; } ~SslStreamInternal() { if (_internalBufferFromPinnableCache) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Read Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_internalBuffer)); } FreeReadBuffer(); } if (_pinnableOutputBuffer != null) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("DTOR: In System.Net._SslStream.~SslStream Freeing Write Buffer", this.GetHashCode(), PinnableBufferCacheEventSource.AddressOfByteArray(_pinnableOutputBuffer)); } s_PinnableWriteBufferCache.FreeBuffer(_pinnableOutputBuffer); } } internal int ReadByte() { if (Interlocked.Exchange(ref _nestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "ReadByte", "read")); } // If there's any data in the buffer, take one byte, and we're done. try { if (InternalBufferCount > 0) { int b = InternalBuffer[InternalOffset]; SkipBytes(1); return b; } } finally { // Regardless of whether we were able to read a byte from the buffer, // reset the read tracking. If we weren't able to read a byte, the // subsequent call to Read will set the flag again. _nestedRead = 0; } // Otherwise, fall back to reading a byte via Read, the same way Stream.ReadByte does. // This allocation is unfortunate but should be relatively rare, as it'll only occur once // per buffer fill internally by Read. byte[] oneByte = new byte[1]; int bytesRead = Read(oneByte, 0, 1); Debug.Assert(bytesRead == 0 || bytesRead == 1); return bytesRead == 1 ? oneByte[0] : -1; } internal int Read(byte[] buffer, int offset, int count) { return ProcessRead(buffer, offset, count, null); } internal void Write(byte[] buffer, int offset, int count) { ProcessWrite(buffer, offset, count, null); } internal IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { BufferAsyncResult bufferResult = new BufferAsyncResult(this, buffer, offset, count, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(bufferResult); ProcessRead(buffer, offset, count, asyncRequest); return bufferResult; } internal int EndRead(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult; if (bufferResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult"); } if (Interlocked.Exchange(ref _nestedRead, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. bufferResult.InternalWaitForCompletion(); if (bufferResult.Result is Exception) { if (bufferResult.Result is IOException) { throw (Exception)bufferResult.Result; } throw new IOException(SR.net_io_read, (Exception)bufferResult.Result); } return (int)bufferResult.Result; } internal IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState) { LazyAsyncResult lazyResult = new LazyAsyncResult(this, asyncState, asyncCallback); AsyncProtocolRequest asyncRequest = new AsyncProtocolRequest(lazyResult); ProcessWrite(buffer, offset, count, asyncRequest); return lazyResult; } internal void EndWrite(IAsyncResult asyncResult) { if (asyncResult == null) { throw new ArgumentNullException("asyncResult"); } LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult; if (lazyResult == null) { throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult"); } if (Interlocked.Exchange(ref _nestedWrite, 0) == 0) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite")); } // No "artificial" timeouts implemented so far, InnerStream controls timeout. lazyResult.InternalWaitForCompletion(); if (lazyResult.Result is Exception) { if (lazyResult.Result is IOException) { throw (Exception)lazyResult.Result; } throw new IOException(SR.net_io_write, (Exception)lazyResult.Result); } } internal bool DataAvailable { get { return InternalBufferCount != 0; } } private byte[] InternalBuffer { get { return _internalBuffer; } } private int InternalOffset { get { return _internalOffset; } } private int InternalBufferCount { get { return _internalBufferCount; } } private void SkipBytes(int decrCount) { _internalOffset += decrCount; _internalBufferCount -= decrCount; } // // This will set the internal offset to "curOffset" and ensure internal buffer. // If not enough, reallocate and copy up to "curOffset". // private void EnsureInternalBufferSize(int curOffset, int addSize) { if (_internalBuffer == null || _internalBuffer.Length < addSize + curOffset) { bool wasPinnable = _internalBufferFromPinnableCache; byte[] saved = _internalBuffer; int newSize = addSize + curOffset; if (newSize <= PinnableReadBufferSize) { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize IS pinnable", this.GetHashCode(), newSize); } _internalBufferFromPinnableCache = true; _internalBuffer = s_PinnableReadBufferCache.AllocateBuffer(); } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.EnsureInternalBufferSize NOT pinnable", this.GetHashCode(), newSize); } _internalBufferFromPinnableCache = false; _internalBuffer = new byte[newSize]; } if (saved != null && curOffset != 0) { Buffer.BlockCopy(saved, 0, _internalBuffer, 0, curOffset); } if (wasPinnable) { s_PinnableReadBufferCache.FreeBuffer(saved); } } _internalOffset = curOffset; _internalBufferCount = curOffset + addSize; } // // Validates user parameteres for all Read/Write methods. // private void ValidateParameters(byte[] buffer, int offset, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (offset < 0) { throw new ArgumentOutOfRangeException("offset"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (count > buffer.Length - offset) { throw new ArgumentOutOfRangeException("count", SR.net_offset_plus_count); } } // // Sync write method. // private void ProcessWrite(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _nestedWrite, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, "Write", "write")); } bool failed = false; try { StartWriting(buffer, offset, count, asyncRequest); } catch (Exception e) { _sslState.FinishWrite(); failed = true; if (e is IOException) { throw; } throw new IOException(SR.net_io_write, e); } finally { if (asyncRequest == null || failed) { _nestedWrite = 0; } } } private void StartWriting(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (asyncRequest != null) { asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncWriteCallback); } // We loop to this method from the callback. // If the last chunk was just completed from async callback (count < 0), we complete user request. if (count >= 0 ) { byte[] outBuffer = null; if (_pinnableOutputBufferInUse == null) { if (_pinnableOutputBuffer == null) { _pinnableOutputBuffer = s_PinnableWriteBufferCache.AllocateBuffer(); } _pinnableOutputBufferInUse = buffer; outBuffer = _pinnableOutputBuffer; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Trying Pinnable", this.GetHashCode(), count, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } } else { if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage2("In System.Net._SslStream.StartWriting BufferInUse", this.GetHashCode(), count); } } do { // Request a write IO slot. if (_sslState.CheckEnqueueWrite(asyncRequest)) { // Operation is async and has been queued, return. return; } int chunkBytes = Math.Min(count, _sslState.MaxDataSize); int encryptedBytes; SecurityStatusPal errorCode = _sslState.EncryptData(buffer, offset, chunkBytes, ref outBuffer, out encryptedBytes); if (errorCode != SecurityStatusPal.OK) { // Re-handshake status is not supported. ProtocolToken message = new ProtocolToken(null, errorCode); throw new IOException(SR.net_io_encrypt, message.GetException()); } if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage3("In System.Net._SslStream.StartWriting Got Encrypted Buffer", this.GetHashCode(), encryptedBytes, PinnableBufferCacheEventSource.AddressOfByteArray(outBuffer)); } if (asyncRequest != null) { // Prepare for the next request. asyncRequest.SetNextRequest(buffer, offset + chunkBytes, count - chunkBytes, s_resumeAsyncWriteCallback); IAsyncResult ar = _sslState.InnerStreamAPM.BeginWrite(outBuffer, 0, encryptedBytes, s_writeCallback, asyncRequest); if (!ar.CompletedSynchronously) { return; } _sslState.InnerStreamAPM.EndWrite(ar); } else { _sslState.InnerStream.Write(outBuffer, 0, encryptedBytes); } offset += chunkBytes; count -= chunkBytes; // Release write IO slot. _sslState.FinishWrite(); } while (count != 0); } if (asyncRequest != null) { asyncRequest.CompleteUser(); } if (buffer == _pinnableOutputBufferInUse) { _pinnableOutputBufferInUse = null; if (PinnableBufferCacheEventSource.Log.IsEnabled()) { PinnableBufferCacheEventSource.Log.DebugMessage1("In System.Net._SslStream.StartWriting Freeing buffer.", this.GetHashCode()); } } } // // Combined sync/async read method. For sync requet asyncRequest==null. // private int ProcessRead(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { ValidateParameters(buffer, offset, count); if (Interlocked.Exchange(ref _nestedRead, 1) == 1) { throw new NotSupportedException(SR.Format(SR.net_io_invalidnestedcall, (asyncRequest!=null? "BeginRead":"Read"), "read")); } bool failed = false; try { int copyBytes; if (InternalBufferCount != 0) { copyBytes = InternalBufferCount > count ? count : InternalBufferCount; if (copyBytes != 0) { Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, copyBytes); SkipBytes(copyBytes); } if (asyncRequest != null) { asyncRequest.CompleteUser((object) copyBytes); } return copyBytes; } return StartReading(buffer, offset, count, asyncRequest); } catch (Exception e) { _sslState.FinishRead(null); failed = true; if (e is IOException) { throw; } throw new IOException(SR.net_io_read, e); } finally { if (asyncRequest == null || failed) { _nestedRead = 0; } } } // // To avoid recursion when decrypted 0 bytes this method will loop until a decrypted result at least 1 byte. // private int StartReading(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { int result = 0; if (InternalBufferCount != 0) { if (GlobalLog.IsEnabled) { GlobalLog.AssertFormat("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:{0}", InternalBufferCount); } Debug.Fail("SslStream::StartReading()|Previous frame was not consumed. InternalBufferCount:" + InternalBufferCount); } do { if (asyncRequest != null) { asyncRequest.SetNextRequest(buffer, offset, count, s_resumeAsyncReadCallback); } int copyBytes = _sslState.CheckEnqueueRead(buffer, offset, count, asyncRequest); if (copyBytes == 0) { // Queued but not completed! return 0; } if (copyBytes != -1) { if (asyncRequest != null) { asyncRequest.CompleteUser((object)copyBytes); } return copyBytes; } } // When we read -1 bytes means we have decrypted 0 bytes or rehandshaking, need looping. while ((result = StartFrameHeader(buffer, offset, count, asyncRequest)) == -1); return result; } private int StartFrameHeader(byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { int readBytes = 0; // // Always pass InternalBuffer for SSPI "in place" decryption. // A user buffer can be shared by many threads in that case decryption/integrity check may fail cause of data corruption. // // Reset internal buffer for a new frame. EnsureInternalBufferSize(0, SecureChannel.ReadHeaderSize); if (asyncRequest != null) { asyncRequest.SetNextRequest(InternalBuffer, 0, SecureChannel.ReadHeaderSize, s_readHeaderCallback); _reader.AsyncReadPacket(asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return 0; } readBytes = asyncRequest.Result; } else { readBytes = _reader.ReadPacket(InternalBuffer, 0, SecureChannel.ReadHeaderSize); } return StartFrameBody(readBytes, buffer, offset, count, asyncRequest); } private int StartFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { //EOF : Reset the buffer as we did not read anything into it. SkipBytes(InternalBufferCount); if (asyncRequest != null) { asyncRequest.CompleteUser((object)0); } return 0; } // Now readBytes is a payload size. readBytes = _sslState.GetRemainingFrameSize(InternalBuffer, readBytes); if (readBytes < 0) { throw new IOException(SR.net_frame_read_size); } EnsureInternalBufferSize(SecureChannel.ReadHeaderSize, readBytes); if (asyncRequest != null) { asyncRequest.SetNextRequest(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes, s_readFrameCallback); _reader.AsyncReadPacket(asyncRequest); if (!asyncRequest.MustCompleteSynchronously) { return 0; } readBytes = asyncRequest.Result; } else { readBytes = _reader.ReadPacket(InternalBuffer, SecureChannel.ReadHeaderSize, readBytes); } return ProcessFrameBody(readBytes, buffer, offset, count, asyncRequest); } // // readBytes == SSL Data Payload size on input or 0 on EOF. // private int ProcessFrameBody(int readBytes, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest) { if (readBytes == 0) { // EOF throw new IOException(SR.net_io_eof); } // Set readBytes to total number of received bytes. readBytes += SecureChannel.ReadHeaderSize; // Decrypt into internal buffer, change "readBytes" to count now _Decrypted Bytes_. int data_offset = 0; SecurityStatusPal errorCode = _sslState.DecryptData(InternalBuffer, ref data_offset, ref readBytes); if (errorCode != SecurityStatusPal.OK) { byte[] extraBuffer = null; if (readBytes != 0) { extraBuffer = new byte[readBytes]; Buffer.BlockCopy(InternalBuffer, data_offset, extraBuffer, 0, readBytes); } // Reset internal buffer count. SkipBytes(InternalBufferCount); return ProcessReadErrorCode(errorCode, buffer, offset, count, asyncRequest, extraBuffer); } if (readBytes == 0 && count != 0) { // Read again since remote side has sent encrypted 0 bytes. SkipBytes(InternalBufferCount); return -1; } // Decrypted data start from "data_offset" offset, the total count can be shrunk after decryption. EnsureInternalBufferSize(0, data_offset + readBytes); SkipBytes(data_offset); if (readBytes > count) { readBytes = count; } Buffer.BlockCopy(InternalBuffer, InternalOffset, buffer, offset, readBytes); // This will adjust both the remaining internal buffer count and the offset. SkipBytes(readBytes); _sslState.FinishRead(null); if (asyncRequest != null) { asyncRequest.CompleteUser((object)readBytes); } return readBytes; } // // Only processing SEC_I_RENEGOTIATE. // private int ProcessReadErrorCode(SecurityStatusPal errorCode, byte[] buffer, int offset, int count, AsyncProtocolRequest asyncRequest, byte[] extraBuffer) { ProtocolToken message = new ProtocolToken(null, errorCode); if (GlobalLog.IsEnabled) { GlobalLog.Print("SecureChannel#" + LoggingHash.HashString(this) + "::***Processing an error Status = " + message.Status.ToString()); } if (message.Renegotiate) { _sslState.ReplyOnReAuthentication(extraBuffer); // Loop on read. return -1; } if (message.CloseConnection) { _sslState.FinishRead(null); if (asyncRequest != null) { asyncRequest.CompleteUser((object)0); } return 0; } throw new IOException(SR.net_io_decrypt, message.GetException()); } private static void WriteCallback(IAsyncResult transportResult) { if (transportResult.CompletedSynchronously) { return; } if (!(transportResult.AsyncState is AsyncProtocolRequest)) { if (GlobalLog.IsEnabled) { GlobalLog.Assert("SslStream::WriteCallback | State type is wrong, expected AsyncProtocolRequest."); } Debug.Fail("SslStream::WriteCallback|State type is wrong, expected AsyncProtocolRequest."); } AsyncProtocolRequest asyncRequest = (AsyncProtocolRequest)transportResult.AsyncState; var sslStream = (SslStreamInternal)asyncRequest.AsyncObject; try { sslStream._sslState.InnerStreamAPM.EndWrite(transportResult); sslStream._sslState.FinishWrite(); if (asyncRequest.Count == 0) { // This was the last chunk. asyncRequest.Count = -1; } sslStream.StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } sslStream._sslState.FinishWrite(); asyncRequest.CompleteWithError(e); } } // // This is used in a rare situation when async Read is resumed from completed handshake. // private static void ResumeAsyncReadCallback(AsyncProtocolRequest request) { try { ((SslStreamInternal)request.AsyncObject).StartReading(request.Buffer, request.Offset, request.Count, request); } catch (Exception e) { if (request.IsUserCompleted) { // This will throw on a worker thread. throw; } ((SslStreamInternal)request.AsyncObject)._sslState.FinishRead(null); request.CompleteWithError(e); } } // // This is used in a rare situation when async Write is resumed from completed handshake. // private static void ResumeAsyncWriteCallback(AsyncProtocolRequest asyncRequest) { try { ((SslStreamInternal)asyncRequest.AsyncObject).StartWriting(asyncRequest.Buffer, asyncRequest.Offset, asyncRequest.Count, asyncRequest); } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } ((SslStreamInternal)asyncRequest.AsyncObject)._sslState.FinishWrite(); asyncRequest.CompleteWithError(e); } } private static void ReadHeaderCallback(AsyncProtocolRequest asyncRequest) { try { SslStreamInternal sslStream = (SslStreamInternal)asyncRequest.AsyncObject; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; if (-1 == sslStream.StartFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest)) { // in case we decrypted 0 bytes start another reading. sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } asyncRequest.CompleteWithError(e); } } private static void ReadFrameCallback(AsyncProtocolRequest asyncRequest) { try { SslStreamInternal sslStream = (SslStreamInternal)asyncRequest.AsyncObject; BufferAsyncResult bufferResult = (BufferAsyncResult)asyncRequest.UserAsyncResult; if (-1 == sslStream.ProcessFrameBody(asyncRequest.Result, bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest)) { // in case we decrypted 0 bytes start another reading. sslStream.StartReading(bufferResult.Buffer, bufferResult.Offset, bufferResult.Count, asyncRequest); } } catch (Exception e) { if (asyncRequest.IsUserCompleted) { // This will throw on a worker thread. throw; } asyncRequest.CompleteWithError(e); } } } }
// // Literal.cs // // Author: // Gabriel Burt <gabriel.burt@gmail.com> // Stephane Delcroix <stephane@delcroix.org> // Stephen Shaw <sshaw@decriptor.com> // // Copyright (C) 2013 Stephen Shaw // Copyright (C) 2007-2009 Novell, Inc. // Copyright (C) 2007 Gabriel Burt // Copyright (C) 2007-2009 Stephane Delcroix // // 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 has to do with Finding photos based on tags // http://mail.gnome.org/archives/f-spot-list/2005-November/msg00053.html // http://bugzilla-attachments.gnome.org/attachment.cgi?id=54566 using System; using System.Collections.Generic; using System.Text; using Mono.Unix; using Gtk; using Gdk; using FSpot.Core; namespace FSpot.Query { // TODO rename to TagLiteral? public class Literal : AbstractLiteral { public Literal (Tag tag) : this (null, tag, null) { } public Literal (Term parent, Tag tag, Literal after) : base (parent, after) { Tag = tag; } static Literal () { FocusedLiterals = new List<Literal> (); } #region Properties public static List<Literal> FocusedLiterals { get; set; } public Tag Tag { get; private set; } public override bool IsNegated { get { return is_negated; } set { if (is_negated == value) return; is_negated = value; NormalIcon = null; NegatedIcon = null; Update (); if (NegatedToggled != null) NegatedToggled (this); } } Pixbuf NegatedIcon { get { if (negated_icon != null) return negated_icon; if (NormalIcon == null) return null; negated_icon = NormalIcon.Copy (); int offset = ICON_SIZE - overlay_size; NegatedOverlay.Composite (negated_icon, offset, 0, overlay_size, overlay_size, offset, 0, 1.0, 1.0, InterpType.Bilinear, 200); return negated_icon; } set { negated_icon = null; } } public Widget Widget { get { if (widget != null) return widget; container = new EventBox (); box = new HBox (); handle_box = new LiteralBox (); handle_box.BorderWidth = 1; label = new Label (System.Web.HttpUtility.HtmlEncode (Tag.Name)); label.UseMarkup = true; image = new Gtk.Image (NormalIcon); container.CanFocus = true; container.KeyPressEvent += KeyHandler; container.ButtonPressEvent += HandleButtonPress; container.ButtonReleaseEvent += HandleButtonRelease; container.EnterNotifyEvent += HandleMouseIn; container.LeaveNotifyEvent += HandleMouseOut; //new PopupManager (new LiteralPopup (container, this)); // Setup this widget as a drag source (so tags can be moved after being placed) container.DragDataGet += HandleDragDataGet; container.DragBegin += HandleDragBegin; container.DragEnd += HandleDragEnd; Gtk.Drag.SourceSet (container, Gdk.ModifierType.Button1Mask | Gdk.ModifierType.Button3Mask, tag_target_table, DragAction.Copy | DragAction.Move); // Setup this widget as a drag destination (so tags can be added to our parent's Term) container.DragDataReceived += HandleDragDataReceived; container.DragMotion += HandleDragMotion; container.DragLeave += HandleDragLeave; Gtk.Drag.DestSet (container, DestDefaults.All, tag_dest_target_table, DragAction.Copy | DragAction.Move); container.TooltipText = Tag.Name; label.Show (); image.Show (); if (Tag.Icon == null) handle_box.Add (label); else handle_box.Add (image); handle_box.Show (); box.Add (handle_box); box.Show (); container.Add (box); widget = container; return widget; } } Pixbuf NormalIcon { get { if (normal_icon != null) return normal_icon; Pixbuf scaled = null; scaled = Tag.Icon; for (Category category = Tag.Category; category != null && scaled == null; category = category.Category) { scaled = category.Icon; } if (scaled == null) return null; if (scaled.Width != ICON_SIZE) scaled = scaled.ScaleSimple (ICON_SIZE, ICON_SIZE, InterpType.Bilinear); normal_icon = scaled; return normal_icon; } set { normal_icon = null; } } #endregion #region Methods public void Update () { // Clear out the old icons normal_icon = null; negated_icon = null; if (IsNegated) { widget.TooltipText = string.Format (Catalog.GetString ("Not {0}"), Tag.Name); label.Text = "<s>" + System.Web.HttpUtility.HtmlEncode (Tag.Name) + "</s>"; image.Pixbuf = NegatedIcon; } else { widget.TooltipText = Tag.Name; label.Text = System.Web.HttpUtility.HtmlEncode (Tag.Name); image.Pixbuf = NormalIcon; } label.UseMarkup = true; // Show the icon unless it's null if (Tag.Icon == null && container.Children [0] == image) { container.Remove (image); container.Add (label); } else if (Tag.Icon != null && container.Children [0] == label) { container.Remove (label); container.Add (image); } if (isHoveredOver && image.Pixbuf != null) { // Brighten the image slightly Pixbuf brightened = image.Pixbuf.Copy (); image.Pixbuf.SaturateAndPixelate (brightened, 1.85f, false); //Pixbuf brightened = PixbufUtils.Glow (image.Pixbuf, .6f); image.Pixbuf = brightened; } } public void RemoveSelf () { if (Removing != null) Removing (this); if (Parent != null) Parent.Remove (this); if (Removed != null) Removed (this); } public override string SqlCondition () { var ids = new StringBuilder (Tag.Id.ToString ()); var category = Tag as Category; if (category != null) { var tags = new List<Tag> (); category.AddDescendentsTo (tags); foreach (var t in tags) { ids.Append (", " + t.Id); } } return string.Format ( "id {0}IN (SELECT photo_id FROM photo_tags WHERE tag_id IN ({1}))", (IsNegated ? "NOT " : string.Empty), ids); } public override Gtk.Widget SeparatorWidget () { return new Label ("ERR"); } static Pixbuf NegatedOverlay { get { if (negated_overlay == null) { System.Reflection.Assembly assembly = System.Reflection.Assembly.GetCallingAssembly (); negated_overlay = new Pixbuf (assembly.GetManifestResourceStream ("f-spot-not.png")); negated_overlay = negated_overlay.ScaleSimple (overlay_size, overlay_size, InterpType.Bilinear); } return negated_overlay; } } public static void RemoveFocusedLiterals () { if (focusedLiterals == null) return; foreach (var literal in focusedLiterals) literal.RemoveSelf (); } #endregion #region Handlers void KeyHandler (object o, KeyPressEventArgs args) { args.RetVal = false; switch (args.Event.Key) { case Gdk.Key.Delete: RemoveFocusedLiterals (); args.RetVal = true; return; } } void HandleButtonPress (object o, ButtonPressEventArgs args) { args.RetVal = true; switch (args.Event.Type) { case EventType.TwoButtonPress: if (args.Event.Button == 1) IsNegated = !IsNegated; else args.RetVal = false; return; case EventType.ButtonPress: Widget.GrabFocus (); if (args.Event.Button == 1) { // TODO allow multiple selection of literals so they can be deleted, modified all at once //if ((args.Event.State & ModifierType.ControlMask) != 0) { //} } else if (args.Event.Button == 3) { var popup = new LiteralPopup (); popup.Activate (args.Event, this); } return; default: args.RetVal = false; return; } } void HandleButtonRelease (object o, ButtonReleaseEventArgs args) { args.RetVal = true; switch (args.Event.Type) { case EventType.TwoButtonPress: args.RetVal = false; return; case EventType.ButtonPress: if (args.Event.Button == 1) { } return; default: args.RetVal = false; return; } } void HandleMouseIn (object o, EnterNotifyEventArgs args) { isHoveredOver = true; Update (); } void HandleMouseOut (object o, LeaveNotifyEventArgs args) { isHoveredOver = false; Update (); } void HandleDragDataGet (object sender, DragDataGetArgs args) { args.RetVal = true; if (args.Info == DragDropTargets.TagListEntry.Info || args.Info == DragDropTargets.TagQueryEntry.Info) { // FIXME: do really write data Byte [] data = Encoding.UTF8.GetBytes (string.Empty); Atom [] targets = args.Context.Targets; args.SelectionData.Set (targets [0], 8, data, data.Length); return; } // Drop cancelled args.RetVal = false; foreach (Widget w in hiddenWidgets) { w.Visible = true; } focusedLiterals = null; } void HandleDragBegin (object sender, DragBeginArgs args) { Gtk.Drag.SetIconPixbuf (args.Context, image.Pixbuf, 0, 0); focusedLiterals.Add (this); // Hide the tag and any separators that only exist because of it container.Visible = false; hiddenWidgets.Add (container); foreach (Widget w in LogicWidget.Box.HangersOn (this)) { hiddenWidgets.Add (w); w.Visible = false; } } void HandleDragEnd (object sender, DragEndArgs args) { // Remove any literals still marked as focused, because // the user is throwing them away. RemoveFocusedLiterals (); focusedLiterals = new List<Literal> (); args.RetVal = true; } void HandleDragDataReceived (object o, DragDataReceivedArgs args) { args.RetVal = true; if (args.Info == DragDropTargets.TagListEntry.Info) { TagsAdded?.Invoke (args.SelectionData.GetTagsData (), Parent, this); return; } if (args.Info == DragDropTargets.TagQueryEntry.Info) { if (!focusedLiterals.Contains (this)) LiteralsMoved?.Invoke (focusedLiterals, Parent, this); // Unmark the literals as focused so they don't get nixed focusedLiterals = null; } } bool preview; Gtk.Widget preview_widget; void HandleDragMotion (object o, DragMotionArgs args) { if (preview) return; if (preview_widget == null) { preview_widget = new Gtk.Label (" | "); box.Add (preview_widget); } preview_widget.Show (); } void HandleDragLeave (object o, EventArgs args) { preview = false; preview_widget.Hide (); } public void HandleToggleNegatedCommand (object o, EventArgs args) { IsNegated = !IsNegated; } public void HandleRemoveCommand (object o, EventArgs args) { RemoveSelf (); } public void HandleAttachTagCommand (Tag t) { AttachTag?.Invoke (t, Parent, this); } public void HandleRequireTag (object sender, EventArgs args) { RequireTag?.Invoke (new[] { Tag }); } public void HandleUnRequireTag (object sender, EventArgs args) { UnRequireTag?.Invoke (new[] { Tag }); } const int ICON_SIZE = 24; const int overlay_size = (int)(.40 * ICON_SIZE); static readonly TargetEntry[] tag_target_table = { DragDropTargets.TagQueryEntry }; static readonly TargetEntry[] tag_dest_target_table = { DragDropTargets.TagListEntry, DragDropTargets.TagQueryEntry }; static List<Literal> focusedLiterals = new List<Literal> (); static readonly List<Widget> hiddenWidgets = new List<Widget> (); Gtk.Container container; LiteralBox handle_box; Gtk.Box box; Gtk.Image image; Gtk.Label label; Pixbuf normal_icon; //EventBox widget; Widget widget; Pixbuf negated_icon; static Pixbuf negated_overlay; bool isHoveredOver; public delegate void NegatedToggleHandler (Literal group); public event NegatedToggleHandler NegatedToggled; public delegate void RemovingHandler (Literal group); public event RemovingHandler Removing; public delegate void RemovedHandler (Literal group); public event RemovedHandler Removed; public delegate void TagsAddedHandler (Tag[] tags,Term parent,Literal after); public event TagsAddedHandler TagsAdded; public delegate void AttachTagHandler (Tag tag,Term parent,Literal after); public event AttachTagHandler AttachTag; public delegate void TagRequiredHandler (Tag[] tags); public event TagRequiredHandler RequireTag; public delegate void TagUnRequiredHandler (Tag[] tags); public event TagUnRequiredHandler UnRequireTag; public delegate void LiteralsMovedHandler (List<Literal> literals,Term parent,Literal after); public event LiteralsMovedHandler LiteralsMoved; #endregion } }
namespace Bike_Share.Migrations { using System; using System.Data.Entity.Migrations; public partial class DeNormalizeRefactor : DbMigration { public override void Up() { DropForeignKey("dbo.CheckOuts", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.bikeUsers", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.Tracers", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.Tracers", "charge_chargeId", "dbo.Charges"); DropForeignKey("dbo.Tracers", "checkOut_checkOutId", "dbo.CheckOuts"); DropForeignKey("dbo.MaintenanceEvents", "bikeAffected_bikeId", "dbo.Bikes"); DropForeignKey("dbo.Tracers", "maint_MaintenanceEventId", "dbo.MaintenanceEvents"); DropForeignKey("dbo.MaintenanceEvents", "staffPerson_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.MaintenanceUpdates", "associatedEvent_MaintenanceEventId", "dbo.MaintenanceEvents"); DropForeignKey("dbo.MaintenanceUpdates", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.Tracers", "update_MaintenanceUpdateId", "dbo.MaintenanceUpdates"); DropForeignKey("dbo.MaintenanceUpdates", "postedBy_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.Tracers", "shop_workshopId", "dbo.Workshops"); DropForeignKey("dbo.Hours", "rack_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.Hours", "shop_workshopId", "dbo.Workshops"); DropForeignKey("dbo.MaintenanceEvents", "workshop_workshopId", "dbo.Workshops"); DropForeignKey("dbo.MaintenanceEvents", "Inspection_inspectionId", "dbo.Inspections"); DropForeignKey("dbo.Inspections", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.Tracers", "inspection_inspectionId", "dbo.Inspections"); DropForeignKey("dbo.Inspections", "inspector_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.Inspections", "placeInspected_workshopId", "dbo.Workshops"); DropForeignKey("dbo.Tracers", "rack_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.Tracers", "user_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.WorkHours", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.Tracers", "workHour_workHourId", "dbo.WorkHours"); DropForeignKey("dbo.WorkHours", "maint_MaintenanceEventId", "dbo.MaintenanceEvents"); DropForeignKey("dbo.WorkHours", "rack_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.WorkHours", "shop_workshopId", "dbo.Workshops"); DropForeignKey("dbo.WorkHours", "user_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.CheckOuts", "bikeUser_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.CheckOuts", "checkOutPerson_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.CheckOuts", "rackCheckedIn_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.CheckOuts", "rackCheckedOut_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.CheckOuts", "user_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.CheckOuts", "BikeRack_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.Bikes", "bikeRack_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.MailSubs", "bike_bikeId", "dbo.Bikes"); DropForeignKey("dbo.MailSubs", "rack_bikeRackId", "dbo.BikeRacks"); DropForeignKey("dbo.MailSubs", "subscriber_bikeUserId", "dbo.bikeUsers"); DropForeignKey("dbo.MailSubs", "workshop_workshopId", "dbo.Workshops"); DropIndex("dbo.Bikes", new[] { "bikeRack_bikeRackId" }); DropIndex("dbo.CheckOuts", new[] { "bike_bikeId" }); DropIndex("dbo.CheckOuts", new[] { "bikeUser_bikeUserId" }); DropIndex("dbo.CheckOuts", new[] { "checkOutPerson_bikeUserId" }); DropIndex("dbo.CheckOuts", new[] { "rackCheckedIn_bikeRackId" }); DropIndex("dbo.CheckOuts", new[] { "rackCheckedOut_bikeRackId" }); DropIndex("dbo.CheckOuts", new[] { "user_bikeUserId" }); DropIndex("dbo.CheckOuts", new[] { "BikeRack_bikeRackId" }); DropIndex("dbo.bikeUsers", new[] { "bike_bikeId" }); DropIndex("dbo.Tracers", new[] { "bike_bikeId" }); DropIndex("dbo.Tracers", new[] { "charge_chargeId" }); DropIndex("dbo.Tracers", new[] { "checkOut_checkOutId" }); DropIndex("dbo.Tracers", new[] { "maint_MaintenanceEventId" }); DropIndex("dbo.Tracers", new[] { "update_MaintenanceUpdateId" }); DropIndex("dbo.Tracers", new[] { "shop_workshopId" }); DropIndex("dbo.Tracers", new[] { "inspection_inspectionId" }); DropIndex("dbo.Tracers", new[] { "rack_bikeRackId" }); DropIndex("dbo.Tracers", new[] { "user_bikeUserId" }); DropIndex("dbo.Tracers", new[] { "workHour_workHourId" }); DropIndex("dbo.Inspections", new[] { "bike_bikeId" }); DropIndex("dbo.Inspections", new[] { "inspector_bikeUserId" }); DropIndex("dbo.Inspections", new[] { "placeInspected_workshopId" }); DropIndex("dbo.MaintenanceEvents", new[] { "bikeAffected_bikeId" }); DropIndex("dbo.MaintenanceEvents", new[] { "staffPerson_bikeUserId" }); DropIndex("dbo.MaintenanceEvents", new[] { "workshop_workshopId" }); DropIndex("dbo.MaintenanceEvents", new[] { "Inspection_inspectionId" }); DropIndex("dbo.MaintenanceUpdates", new[] { "associatedEvent_MaintenanceEventId" }); DropIndex("dbo.MaintenanceUpdates", new[] { "bike_bikeId" }); DropIndex("dbo.MaintenanceUpdates", new[] { "postedBy_bikeUserId" }); DropIndex("dbo.Hours", new[] { "rack_bikeRackId" }); DropIndex("dbo.Hours", new[] { "shop_workshopId" }); DropIndex("dbo.WorkHours", new[] { "bike_bikeId" }); DropIndex("dbo.WorkHours", new[] { "maint_MaintenanceEventId" }); DropIndex("dbo.WorkHours", new[] { "rack_bikeRackId" }); DropIndex("dbo.WorkHours", new[] { "shop_workshopId" }); DropIndex("dbo.WorkHours", new[] { "user_bikeUserId" }); DropIndex("dbo.MailSubs", new[] { "bike_bikeId" }); DropIndex("dbo.MailSubs", new[] { "rack_bikeRackId" }); DropIndex("dbo.MailSubs", new[] { "subscriber_bikeUserId" }); DropIndex("dbo.MailSubs", new[] { "workshop_workshopId" }); RenameColumn(table: "dbo.Charges", name: "user_bikeUserId", newName: "bikeUserId"); RenameIndex(table: "dbo.Charges", name: "IX_user_bikeUserId", newName: "IX_bikeUserId"); AddColumn("dbo.Bikes", "bikeRackId", c => c.Int()); AddColumn("dbo.Bikes", "onInspectionHold", c => c.Boolean(nullable: false)); AddColumn("dbo.Bikes", "onMaintenanceHold", c => c.Boolean(nullable: false)); AddColumn("dbo.BikeRacks", "hours", c => c.String()); AddColumn("dbo.CheckOuts", "checkOutPerson", c => c.Int(nullable: false)); AddColumn("dbo.CheckOuts", "rider", c => c.Int(nullable: false)); AddColumn("dbo.CheckOuts", "bike", c => c.Int(nullable: false)); AddColumn("dbo.CheckOuts", "rackCheckedOut", c => c.Int(nullable: false)); AddColumn("dbo.CheckOuts", "rackCheckedIn", c => c.Int(nullable: false)); AddColumn("dbo.Inspections", "inspectorId", c => c.Int(nullable: false)); AddColumn("dbo.Inspections", "bikeId", c => c.Int(nullable: false)); AddColumn("dbo.Inspections", "placeInspectedId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceEvents", "bikeId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceEvents", "submittedById", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceEvents", "maintainedById", c => c.Int()); AddColumn("dbo.MaintenanceEvents", "workshopId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceUpdates", "postedById", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceUpdates", "associatedEventId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceUpdates", "bikeId", c => c.Int(nullable: false)); AddColumn("dbo.Workshops", "hours", c => c.String()); AddColumn("dbo.WorkHours", "userid", c => c.Int(nullable: false)); AlterColumn("dbo.MaintenanceEvents", "timeResolved", c => c.DateTime()); DropColumn("dbo.Bikes", "lastPassedInspection"); DropColumn("dbo.Bikes", "bikeRack_bikeRackId"); DropColumn("dbo.CheckOuts", "bike_bikeId"); DropColumn("dbo.CheckOuts", "bikeUser_bikeUserId"); DropColumn("dbo.CheckOuts", "checkOutPerson_bikeUserId"); DropColumn("dbo.CheckOuts", "rackCheckedIn_bikeRackId"); DropColumn("dbo.CheckOuts", "rackCheckedOut_bikeRackId"); DropColumn("dbo.CheckOuts", "user_bikeUserId"); DropColumn("dbo.CheckOuts", "BikeRack_bikeRackId"); DropColumn("dbo.bikeUsers", "hasBike"); DropColumn("dbo.bikeUsers", "bike_bikeId"); DropColumn("dbo.Inspections", "bike_bikeId"); DropColumn("dbo.Inspections", "inspector_bikeUserId"); DropColumn("dbo.Inspections", "placeInspected_workshopId"); DropColumn("dbo.MaintenanceEvents", "resolved"); DropColumn("dbo.MaintenanceEvents", "bikeAffected_bikeId"); DropColumn("dbo.MaintenanceEvents", "staffPerson_bikeUserId"); DropColumn("dbo.MaintenanceEvents", "workshop_workshopId"); DropColumn("dbo.MaintenanceEvents", "Inspection_inspectionId"); DropColumn("dbo.MaintenanceUpdates", "associatedEvent_MaintenanceEventId"); DropColumn("dbo.MaintenanceUpdates", "bike_bikeId"); DropColumn("dbo.MaintenanceUpdates", "postedBy_bikeUserId"); DropColumn("dbo.WorkHours", "bike_bikeId"); DropColumn("dbo.WorkHours", "maint_MaintenanceEventId"); DropColumn("dbo.WorkHours", "rack_bikeRackId"); DropColumn("dbo.WorkHours", "shop_workshopId"); DropColumn("dbo.WorkHours", "user_bikeUserId"); DropTable("dbo.Tracers"); DropTable("dbo.Hours"); DropTable("dbo.MailSubs"); } public override void Down() { CreateTable( "dbo.MailSubs", c => new { subId = c.Int(nullable: false, identity: true), email = c.String(), bike_bikeId = c.Int(), rack_bikeRackId = c.Int(), subscriber_bikeUserId = c.Int(nullable: false), workshop_workshopId = c.Int(), }) .PrimaryKey(t => t.subId); CreateTable( "dbo.Hours", c => new { hourId = c.Int(nullable: false, identity: true), dayStart = c.String(), dayEnd = c.String(), hourStart = c.Int(nullable: false), hourEnd = c.Int(nullable: false), minuteStart = c.Int(nullable: false), minuteEnd = c.Int(nullable: false), isOpen = c.Boolean(nullable: false), comment = c.String(), rack_bikeRackId = c.Int(), shop_workshopId = c.Int(), }) .PrimaryKey(t => t.hourId); CreateTable( "dbo.Tracers", c => new { tracerId = c.Int(nullable: false, identity: true), comment = c.String(), time = c.DateTime(nullable: false), bike_bikeId = c.Int(), charge_chargeId = c.Int(), checkOut_checkOutId = c.Int(), maint_MaintenanceEventId = c.Int(), update_MaintenanceUpdateId = c.Int(), shop_workshopId = c.Int(), inspection_inspectionId = c.Int(), rack_bikeRackId = c.Int(), user_bikeUserId = c.Int(), workHour_workHourId = c.Int(), }) .PrimaryKey(t => t.tracerId); AddColumn("dbo.WorkHours", "user_bikeUserId", c => c.Int()); AddColumn("dbo.WorkHours", "shop_workshopId", c => c.Int()); AddColumn("dbo.WorkHours", "rack_bikeRackId", c => c.Int()); AddColumn("dbo.WorkHours", "maint_MaintenanceEventId", c => c.Int()); AddColumn("dbo.WorkHours", "bike_bikeId", c => c.Int()); AddColumn("dbo.MaintenanceUpdates", "postedBy_bikeUserId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceUpdates", "bike_bikeId", c => c.Int()); AddColumn("dbo.MaintenanceUpdates", "associatedEvent_MaintenanceEventId", c => c.Int()); AddColumn("dbo.MaintenanceEvents", "Inspection_inspectionId", c => c.Int()); AddColumn("dbo.MaintenanceEvents", "workshop_workshopId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceEvents", "staffPerson_bikeUserId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceEvents", "bikeAffected_bikeId", c => c.Int(nullable: false)); AddColumn("dbo.MaintenanceEvents", "resolved", c => c.Boolean(nullable: false)); AddColumn("dbo.Inspections", "placeInspected_workshopId", c => c.Int(nullable: false)); AddColumn("dbo.Inspections", "inspector_bikeUserId", c => c.Int(nullable: false)); AddColumn("dbo.Inspections", "bike_bikeId", c => c.Int(nullable: false)); AddColumn("dbo.bikeUsers", "bike_bikeId", c => c.Int()); AddColumn("dbo.bikeUsers", "hasBike", c => c.Boolean(nullable: false)); AddColumn("dbo.CheckOuts", "BikeRack_bikeRackId", c => c.Int()); AddColumn("dbo.CheckOuts", "user_bikeUserId", c => c.Int()); AddColumn("dbo.CheckOuts", "rackCheckedOut_bikeRackId", c => c.Int()); AddColumn("dbo.CheckOuts", "rackCheckedIn_bikeRackId", c => c.Int()); AddColumn("dbo.CheckOuts", "checkOutPerson_bikeUserId", c => c.Int()); AddColumn("dbo.CheckOuts", "bikeUser_bikeUserId", c => c.Int()); AddColumn("dbo.CheckOuts", "bike_bikeId", c => c.Int()); AddColumn("dbo.Bikes", "bikeRack_bikeRackId", c => c.Int(nullable: false)); AddColumn("dbo.Bikes", "lastPassedInspection", c => c.DateTime(nullable: false)); AlterColumn("dbo.MaintenanceEvents", "timeResolved", c => c.DateTime(nullable: false)); DropColumn("dbo.WorkHours", "userid"); DropColumn("dbo.Workshops", "hours"); DropColumn("dbo.MaintenanceUpdates", "bikeId"); DropColumn("dbo.MaintenanceUpdates", "associatedEventId"); DropColumn("dbo.MaintenanceUpdates", "postedById"); DropColumn("dbo.MaintenanceEvents", "workshopId"); DropColumn("dbo.MaintenanceEvents", "maintainedById"); DropColumn("dbo.MaintenanceEvents", "submittedById"); DropColumn("dbo.MaintenanceEvents", "bikeId"); DropColumn("dbo.Inspections", "placeInspectedId"); DropColumn("dbo.Inspections", "bikeId"); DropColumn("dbo.Inspections", "inspectorId"); DropColumn("dbo.CheckOuts", "rackCheckedIn"); DropColumn("dbo.CheckOuts", "rackCheckedOut"); DropColumn("dbo.CheckOuts", "bike"); DropColumn("dbo.CheckOuts", "rider"); DropColumn("dbo.CheckOuts", "checkOutPerson"); DropColumn("dbo.BikeRacks", "hours"); DropColumn("dbo.Bikes", "onMaintenanceHold"); DropColumn("dbo.Bikes", "onInspectionHold"); DropColumn("dbo.Bikes", "bikeRackId"); RenameIndex(table: "dbo.Charges", name: "IX_bikeUserId", newName: "IX_user_bikeUserId"); RenameColumn(table: "dbo.Charges", name: "bikeUserId", newName: "user_bikeUserId"); CreateIndex("dbo.MailSubs", "workshop_workshopId"); CreateIndex("dbo.MailSubs", "subscriber_bikeUserId"); CreateIndex("dbo.MailSubs", "rack_bikeRackId"); CreateIndex("dbo.MailSubs", "bike_bikeId"); CreateIndex("dbo.WorkHours", "user_bikeUserId"); CreateIndex("dbo.WorkHours", "shop_workshopId"); CreateIndex("dbo.WorkHours", "rack_bikeRackId"); CreateIndex("dbo.WorkHours", "maint_MaintenanceEventId"); CreateIndex("dbo.WorkHours", "bike_bikeId"); CreateIndex("dbo.Hours", "shop_workshopId"); CreateIndex("dbo.Hours", "rack_bikeRackId"); CreateIndex("dbo.MaintenanceUpdates", "postedBy_bikeUserId"); CreateIndex("dbo.MaintenanceUpdates", "bike_bikeId"); CreateIndex("dbo.MaintenanceUpdates", "associatedEvent_MaintenanceEventId"); CreateIndex("dbo.MaintenanceEvents", "Inspection_inspectionId"); CreateIndex("dbo.MaintenanceEvents", "workshop_workshopId"); CreateIndex("dbo.MaintenanceEvents", "staffPerson_bikeUserId"); CreateIndex("dbo.MaintenanceEvents", "bikeAffected_bikeId"); CreateIndex("dbo.Inspections", "placeInspected_workshopId"); CreateIndex("dbo.Inspections", "inspector_bikeUserId"); CreateIndex("dbo.Inspections", "bike_bikeId"); CreateIndex("dbo.Tracers", "workHour_workHourId"); CreateIndex("dbo.Tracers", "user_bikeUserId"); CreateIndex("dbo.Tracers", "rack_bikeRackId"); CreateIndex("dbo.Tracers", "inspection_inspectionId"); CreateIndex("dbo.Tracers", "shop_workshopId"); CreateIndex("dbo.Tracers", "update_MaintenanceUpdateId"); CreateIndex("dbo.Tracers", "maint_MaintenanceEventId"); CreateIndex("dbo.Tracers", "checkOut_checkOutId"); CreateIndex("dbo.Tracers", "charge_chargeId"); CreateIndex("dbo.Tracers", "bike_bikeId"); CreateIndex("dbo.bikeUsers", "bike_bikeId"); CreateIndex("dbo.CheckOuts", "BikeRack_bikeRackId"); CreateIndex("dbo.CheckOuts", "user_bikeUserId"); CreateIndex("dbo.CheckOuts", "rackCheckedOut_bikeRackId"); CreateIndex("dbo.CheckOuts", "rackCheckedIn_bikeRackId"); CreateIndex("dbo.CheckOuts", "checkOutPerson_bikeUserId"); CreateIndex("dbo.CheckOuts", "bikeUser_bikeUserId"); CreateIndex("dbo.CheckOuts", "bike_bikeId"); CreateIndex("dbo.Bikes", "bikeRack_bikeRackId"); AddForeignKey("dbo.MailSubs", "workshop_workshopId", "dbo.Workshops", "workshopId"); AddForeignKey("dbo.MailSubs", "subscriber_bikeUserId", "dbo.bikeUsers", "bikeUserId", cascadeDelete: true); AddForeignKey("dbo.MailSubs", "rack_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.MailSubs", "bike_bikeId", "dbo.Bikes", "bikeId"); AddForeignKey("dbo.Bikes", "bikeRack_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.CheckOuts", "BikeRack_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.CheckOuts", "user_bikeUserId", "dbo.bikeUsers", "bikeUserId"); AddForeignKey("dbo.CheckOuts", "rackCheckedOut_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.CheckOuts", "rackCheckedIn_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.CheckOuts", "checkOutPerson_bikeUserId", "dbo.bikeUsers", "bikeUserId"); AddForeignKey("dbo.CheckOuts", "bikeUser_bikeUserId", "dbo.bikeUsers", "bikeUserId"); AddForeignKey("dbo.WorkHours", "user_bikeUserId", "dbo.bikeUsers", "bikeUserId"); AddForeignKey("dbo.WorkHours", "shop_workshopId", "dbo.Workshops", "workshopId"); AddForeignKey("dbo.WorkHours", "rack_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.WorkHours", "maint_MaintenanceEventId", "dbo.MaintenanceEvents", "MaintenanceEventId"); AddForeignKey("dbo.Tracers", "workHour_workHourId", "dbo.WorkHours", "workHourId"); AddForeignKey("dbo.WorkHours", "bike_bikeId", "dbo.Bikes", "bikeId"); AddForeignKey("dbo.Tracers", "user_bikeUserId", "dbo.bikeUsers", "bikeUserId"); AddForeignKey("dbo.Tracers", "rack_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.Inspections", "placeInspected_workshopId", "dbo.Workshops", "workshopId", cascadeDelete: true); AddForeignKey("dbo.Inspections", "inspector_bikeUserId", "dbo.bikeUsers", "bikeUserId", cascadeDelete: true); AddForeignKey("dbo.Tracers", "inspection_inspectionId", "dbo.Inspections", "inspectionId"); AddForeignKey("dbo.Inspections", "bike_bikeId", "dbo.Bikes", "bikeId", cascadeDelete: true); AddForeignKey("dbo.MaintenanceEvents", "Inspection_inspectionId", "dbo.Inspections", "inspectionId"); AddForeignKey("dbo.MaintenanceEvents", "workshop_workshopId", "dbo.Workshops", "workshopId", cascadeDelete: true); AddForeignKey("dbo.Hours", "shop_workshopId", "dbo.Workshops", "workshopId"); AddForeignKey("dbo.Hours", "rack_bikeRackId", "dbo.BikeRacks", "bikeRackId"); AddForeignKey("dbo.Tracers", "shop_workshopId", "dbo.Workshops", "workshopId"); AddForeignKey("dbo.MaintenanceUpdates", "postedBy_bikeUserId", "dbo.bikeUsers", "bikeUserId", cascadeDelete: true); AddForeignKey("dbo.Tracers", "update_MaintenanceUpdateId", "dbo.MaintenanceUpdates", "MaintenanceUpdateId"); AddForeignKey("dbo.MaintenanceUpdates", "bike_bikeId", "dbo.Bikes", "bikeId"); AddForeignKey("dbo.MaintenanceUpdates", "associatedEvent_MaintenanceEventId", "dbo.MaintenanceEvents", "MaintenanceEventId"); AddForeignKey("dbo.MaintenanceEvents", "staffPerson_bikeUserId", "dbo.bikeUsers", "bikeUserId"); AddForeignKey("dbo.Tracers", "maint_MaintenanceEventId", "dbo.MaintenanceEvents", "MaintenanceEventId"); AddForeignKey("dbo.MaintenanceEvents", "bikeAffected_bikeId", "dbo.Bikes", "bikeId", cascadeDelete: true); AddForeignKey("dbo.Tracers", "checkOut_checkOutId", "dbo.CheckOuts", "checkOutId"); AddForeignKey("dbo.Tracers", "charge_chargeId", "dbo.Charges", "chargeId"); AddForeignKey("dbo.Tracers", "bike_bikeId", "dbo.Bikes", "bikeId"); AddForeignKey("dbo.bikeUsers", "bike_bikeId", "dbo.Bikes", "bikeId"); AddForeignKey("dbo.CheckOuts", "bike_bikeId", "dbo.Bikes", "bikeId"); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.Drawing.Drawing2D; namespace WeifenLuo.WinFormsUI.Docking { internal class VS2012AutoHideStrip : AutoHideStripBase { private class TabVS2012 : Tab { internal TabVS2012(IDockContent content) : base(content) { } private int m_tabX = 0; public int TabX { get { return m_tabX; } set { m_tabX = value; } } private int m_tabWidth = 0; public int TabWidth { get { return m_tabWidth; } set { m_tabWidth = value; } } public bool IsMouseOver { get; set; } } private const int _ImageHeight = 16; private const int _ImageWidth = 0; private const int _ImageGapTop = 2; private const int _ImageGapLeft = 4; private const int _ImageGapRight = 2; private const int _ImageGapBottom = 2; private const int _TextGapLeft = 0; private const int _TextGapRight = 0; private const int _TabGapTop = 3; private const int _TabGapBottom = 8; private const int _TabGapLeft = 4; private const int _TabGapBetween = 10; #region Customizable Properties public Font TextFont { get { return DockPanel.Skin.AutoHideStripSkin.TextFont; } } private static StringFormat _stringFormatTabHorizontal; private StringFormat StringFormatTabHorizontal { get { if (_stringFormatTabHorizontal == null) { _stringFormatTabHorizontal = new StringFormat(); _stringFormatTabHorizontal.Alignment = StringAlignment.Near; _stringFormatTabHorizontal.LineAlignment = StringAlignment.Center; _stringFormatTabHorizontal.FormatFlags = StringFormatFlags.NoWrap; _stringFormatTabHorizontal.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabHorizontal.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabHorizontal.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabHorizontal; } } private static StringFormat _stringFormatTabVertical; private StringFormat StringFormatTabVertical { get { if (_stringFormatTabVertical == null) { _stringFormatTabVertical = new StringFormat(); _stringFormatTabVertical.Alignment = StringAlignment.Near; _stringFormatTabVertical.LineAlignment = StringAlignment.Center; _stringFormatTabVertical.FormatFlags = StringFormatFlags.NoWrap | StringFormatFlags.DirectionVertical; _stringFormatTabVertical.Trimming = StringTrimming.None; } if (RightToLeft == RightToLeft.Yes) _stringFormatTabVertical.FormatFlags |= StringFormatFlags.DirectionRightToLeft; else _stringFormatTabVertical.FormatFlags &= ~StringFormatFlags.DirectionRightToLeft; return _stringFormatTabVertical; } } private static int ImageHeight { get { return _ImageHeight; } } private static int ImageWidth { get { return _ImageWidth; } } private static int ImageGapTop { get { return _ImageGapTop; } } private static int ImageGapLeft { get { return _ImageGapLeft; } } private static int ImageGapRight { get { return _ImageGapRight; } } private static int ImageGapBottom { get { return _ImageGapBottom; } } private static int TextGapLeft { get { return _TextGapLeft; } } private static int TextGapRight { get { return _TextGapRight; } } private static int TabGapTop { get { return _TabGapTop; } } private static int TabGapBottom { get { return _TabGapBottom; } } private static int TabGapLeft { get { return _TabGapLeft; } } private static int TabGapBetween { get { return _TabGapBetween; } } private static Pen PenTabBorder { get { return SystemPens.GrayText; } } #endregion private static Matrix _matrixIdentity = new Matrix(); private static Matrix MatrixIdentity { get { return _matrixIdentity; } } private static DockState[] _dockStates; private static DockState[] DockStates { get { if (_dockStates == null) { _dockStates = new DockState[4]; _dockStates[0] = DockState.DockLeftAutoHide; _dockStates[1] = DockState.DockRightAutoHide; _dockStates[2] = DockState.DockTopAutoHide; _dockStates[3] = DockState.DockBottomAutoHide; } return _dockStates; } } private static GraphicsPath _graphicsPath; internal static GraphicsPath GraphicsPath { get { if (_graphicsPath == null) _graphicsPath = new GraphicsPath(); return _graphicsPath; } } public VS2012AutoHideStrip(DockPanel panel) : base(panel) { SetStyle(ControlStyles.ResizeRedraw | ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); BackColor = SystemColors.ControlLight; } protected override void OnPaint(PaintEventArgs e) { Graphics g = e.Graphics; g.FillRectangle(new SolidBrush(DockPanel.Skin.AutoHideTabBarBG), ClientRectangle); DrawTabStrip(g); } protected override void OnLayout(LayoutEventArgs levent) { CalculateTabs(); base.OnLayout(levent); } private void DrawTabStrip(Graphics g) { DrawTabStrip(g, DockState.DockTopAutoHide); DrawTabStrip(g, DockState.DockBottomAutoHide); DrawTabStrip(g, DockState.DockLeftAutoHide); DrawTabStrip(g, DockState.DockRightAutoHide); } private void DrawTabStrip(Graphics g, DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); // Draw Splitter Rectangle rectSplitter; switch(dockState) { case DockState.DockLeftAutoHide: rectSplitter = new Rectangle( rectTabStrip.X + rectTabStrip.Height - Measures.SplitterSize, rectTabStrip.Y, Measures.SplitterSize, rectTabStrip.Width); break; case DockState.DockRightAutoHide: rectSplitter = new Rectangle( rectTabStrip.X, rectTabStrip.Y, Measures.SplitterSize, rectTabStrip.Width); break; case DockState.DockTopAutoHide: rectSplitter = new Rectangle( rectTabStrip.X - Measures.SplitterSize, rectTabStrip.Y + rectTabStrip.Height - Measures.SplitterSize, rectTabStrip.Width + Measures.SplitterSize * 2, Measures.SplitterSize); break; case DockState.DockBottomAutoHide: rectSplitter = new Rectangle( rectTabStrip.X - Measures.SplitterSize, rectTabStrip.Y, rectTabStrip.Width + Measures.SplitterSize * 2, Measures.SplitterSize); break; default: rectSplitter = new Rectangle(0, 0, 0, 0); break; } g.FillRectangle(new SolidBrush(DockPanel.Skin.PanelSplitter), rectSplitter); if (rectTabStrip.IsEmpty) return; Matrix matrixIdentity = g.Transform; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { Matrix matrixRotated = new Matrix(); matrixRotated.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); g.Transform = matrixRotated; } foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2012 tab in pane.AutoHideTabs) DrawTab(g, tab); } g.Transform = matrixIdentity; } private void CalculateTabs() { CalculateTabs(DockState.DockTopAutoHide); CalculateTabs(DockState.DockBottomAutoHide); CalculateTabs(DockState.DockLeftAutoHide); CalculateTabs(DockState.DockRightAutoHide); } private void CalculateTabs(DockState dockState) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); int imageHeight = rectTabStrip.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); int x = TabGapLeft + rectTabStrip.X; foreach (Pane pane in GetPanes(dockState)) { foreach (TabVS2012 tab in pane.AutoHideTabs) { int width = imageWidth + ImageGapLeft + ImageGapRight + TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width + TextGapLeft + TextGapRight; tab.TabX = x; tab.TabWidth = width; x += width; } x += TabGapBetween; } } private Rectangle RtlTransform(Rectangle rect, DockState dockState) { Rectangle rectTransformed; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) rectTransformed = rect; else rectTransformed = DrawHelper.RtlTransform(this, rect); return rectTransformed; } private GraphicsPath GetTabOutline(TabVS2012 tab, bool transformed, bool rtlTransform) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTab = GetTabRectangle(tab, transformed); if (rtlTransform) rectTab = RtlTransform(rectTab, dockState); if (GraphicsPath != null) { GraphicsPath.Reset(); GraphicsPath.AddRectangle(rectTab); } return GraphicsPath; } private void DrawTab(Graphics g, TabVS2012 tab) { Rectangle rectTabOrigin = GetTabRectangle(tab); if (rectTabOrigin.IsEmpty) return; DockState dockState = tab.Content.DockHandler.DockState; IDockContent content = tab.Content; Color textColor; if (tab.Content.DockHandler.IsActivated || tab.IsMouseOver) textColor = DockPanel.Skin.AutoHideTabActive; else textColor = DockPanel.Skin.AutoHideTabBarFG; Rectangle rectThickLine = rectTabOrigin; rectThickLine.X += _TabGapLeft + _TextGapLeft + _ImageGapLeft + _ImageWidth; rectThickLine.Width = TextRenderer.MeasureText(tab.Content.DockHandler.TabText, TextFont).Width - 8; rectThickLine.Height = Measures.AutoHideTabLineWidth; if (dockState == DockState.DockBottomAutoHide || dockState == DockState.DockLeftAutoHide) rectThickLine.Y += rectTabOrigin.Height - Measures.AutoHideTabLineWidth; else if (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide) rectThickLine.Y += 0; g.FillRectangle(new SolidBrush(textColor), rectThickLine); //Set no rotate for drawing icon and text Matrix matrixRotate = g.Transform; g.Transform = MatrixIdentity; // Draw the icon Rectangle rectImage = rectTabOrigin; rectImage.X += ImageGapLeft; rectImage.Y += ImageGapTop; int imageHeight = rectTabOrigin.Height - ImageGapTop - ImageGapBottom; int imageWidth = ImageWidth; if (imageHeight > ImageHeight) imageWidth = ImageWidth * (imageHeight / ImageHeight); rectImage.Height = imageHeight; rectImage.Width = imageWidth; rectImage = GetTransformedRectangle(dockState, rectImage); if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) { // The DockState is DockLeftAutoHide or DockRightAutoHide, so rotate the image 90 degrees to the right. Rectangle rectTransform = RtlTransform(rectImage, dockState); Point[] rotationPoints = { new Point(rectTransform.X + rectTransform.Width, rectTransform.Y), new Point(rectTransform.X + rectTransform.Width, rectTransform.Y + rectTransform.Height), new Point(rectTransform.X, rectTransform.Y) }; using (Icon rotatedIcon = new Icon(((Form)content).Icon, 16, 16)) { g.DrawImage(rotatedIcon.ToBitmap(), rotationPoints); } } else { // Draw the icon normally without any rotation. g.DrawIcon(((Form)content).Icon, RtlTransform(rectImage, dockState)); } // Draw the text Rectangle rectText = rectTabOrigin; rectText.X += ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText.Width -= ImageGapLeft + imageWidth + ImageGapRight + TextGapLeft; rectText = RtlTransform(GetTransformedRectangle(dockState, rectText), dockState); if (DockPanel.ActiveContent == content || tab.IsMouseOver) textColor = DockPanel.Skin.AutoHideTabActive; else textColor = DockPanel.Skin.AutoHideTabInactive; if (dockState == DockState.DockLeftAutoHide || dockState == DockState.DockRightAutoHide) g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabVertical); else g.DrawString(content.DockHandler.TabText, TextFont, new SolidBrush(textColor), rectText, StringFormatTabHorizontal); // Set rotate back g.Transform = matrixRotate; } private Rectangle GetLogicalTabStripRectangle(DockState dockState) { return GetLogicalTabStripRectangle(dockState, false); } private Rectangle GetLogicalTabStripRectangle(DockState dockState, bool transformed) { if (!DockHelper.IsDockStateAutoHide(dockState)) return Rectangle.Empty; int leftPanes = GetPanes(DockState.DockLeftAutoHide).Count; int rightPanes = GetPanes(DockState.DockRightAutoHide).Count; int topPanes = GetPanes(DockState.DockTopAutoHide).Count; int bottomPanes = GetPanes(DockState.DockBottomAutoHide).Count; int x, y, width, height; height = MeasureHeight(); if (dockState == DockState.DockLeftAutoHide && leftPanes > 0) { x = 0; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockRightAutoHide && rightPanes > 0) { x = Width - height; if (leftPanes != 0 && x < height) x = height; y = (topPanes == 0) ? 0 : height; width = Height - (topPanes == 0 ? 0 : height) - (bottomPanes == 0 ? 0 : height); } else if (dockState == DockState.DockTopAutoHide && topPanes > 0) { x = leftPanes == 0 ? 0 : height; y = 0; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else if (dockState == DockState.DockBottomAutoHide && bottomPanes > 0) { x = leftPanes == 0 ? 0 : height; y = Height - height; if (topPanes != 0 && y < height) y = height; width = Width - (leftPanes == 0 ? 0 : height) - (rightPanes == 0 ? 0 : height); } else return Rectangle.Empty; if (width == 0 || height == 0) { return Rectangle.Empty; } var rect = new Rectangle(x, y, width, height); return transformed ? GetTransformedRectangle(dockState, rect) : rect; } private Rectangle GetTabRectangle(TabVS2012 tab) { return GetTabRectangle(tab, false); } private Rectangle GetTabRectangle(TabVS2012 tab, bool transformed) { DockState dockState = tab.Content.DockHandler.DockState; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); if (rectTabStrip.IsEmpty) return Rectangle.Empty; int x = tab.TabX; int y = rectTabStrip.Y + (dockState == DockState.DockTopAutoHide || dockState == DockState.DockRightAutoHide ? 0 : TabGapTop); int width = tab.TabWidth; int height = rectTabStrip.Height - TabGapTop; if (!transformed) return new Rectangle(x, y, width, height); else return GetTransformedRectangle(dockState, new Rectangle(x, y, width, height)); } private Rectangle GetTransformedRectangle(DockState dockState, Rectangle rect) { if (dockState != DockState.DockLeftAutoHide && dockState != DockState.DockRightAutoHide) return rect; PointF[] pts = new PointF[1]; // the center of the rectangle pts[0].X = (float)rect.X + (float)rect.Width / 2; pts[0].Y = (float)rect.Y + (float)rect.Height / 2; Rectangle rectTabStrip = GetLogicalTabStripRectangle(dockState); using (var matrix = new Matrix()) { matrix.RotateAt(90, new PointF((float)rectTabStrip.X + (float)rectTabStrip.Height / 2, (float)rectTabStrip.Y + (float)rectTabStrip.Height / 2)); matrix.TransformPoints(pts); } return new Rectangle((int)(pts[0].X - (float)rect.Height / 2 + .5F), (int)(pts[0].Y - (float)rect.Width / 2 + .5F), rect.Height, rect.Width); } protected override IDockContent HitTest(Point ptMouse) { Tab tab = TabHitTest(ptMouse); if (tab != null) return tab.Content; else return null; } protected override Rectangle GetTabBounds(Tab tab) { GraphicsPath path = GetTabOutline((TabVS2012)tab, true, true); RectangleF bounds = path.GetBounds(); return new Rectangle((int)bounds.Left, (int)bounds.Top, (int)bounds.Width, (int)bounds.Height); } protected Tab TabHitTest(Point ptMouse) { foreach (DockState state in DockStates) { Rectangle rectTabStrip = GetLogicalTabStripRectangle(state, true); if (!rectTabStrip.Contains(ptMouse)) continue; foreach (Pane pane in GetPanes(state)) { foreach (TabVS2012 tab in pane.AutoHideTabs) { GraphicsPath path = GetTabOutline(tab, true, true); if (path.IsVisible(ptMouse)) return tab; } } } return null; } private TabVS2012 lastSelectedTab = null; protected override void OnMouseHover(EventArgs e) { var tab = (TabVS2012)TabHitTest(PointToClient(MousePosition)); if (tab != null) { tab.IsMouseOver = true; Invalidate(); } if (lastSelectedTab != tab) { if (lastSelectedTab != null) lastSelectedTab.IsMouseOver = false; lastSelectedTab = tab; } base.OnMouseHover(e); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); if (lastSelectedTab != null) lastSelectedTab.IsMouseOver = false; Invalidate(); } protected override int MeasureHeight() { return Math.Max(ImageGapBottom + ImageGapTop + ImageHeight, TextFont.Height) + TabGapTop + TabGapBottom; } protected override void OnRefreshChanges() { CalculateTabs(); Invalidate(); } protected override AutoHideStripBase.Tab CreateTab(IDockContent content) { return new TabVS2012(content); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using System.Net.Http; using Hyak.Common; using Microsoft.Azure; using Microsoft.Azure.Management.Sql; namespace Microsoft.Azure.Management.Sql { /// <summary> /// The Windows Azure SQL Database management API provides a RESTful set of /// web services that interact with Windows Azure SQL Database services to /// manage your databases. The API enables users to create, retrieve, /// update, and delete databases and servers. /// </summary> public partial class SqlManagementClient : ServiceClient<SqlManagementClient>, ISqlManagementClient { private string _apiVersion; /// <summary> /// Gets the API version. /// </summary> public string ApiVersion { get { return this._apiVersion; } } private Uri _baseUri; /// <summary> /// Gets the URI used as the base for all cloud service requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// Gets subscription credentials which uniquely identify Microsoft /// Azure subscription. The subscription ID forms part of the URI for /// every service call. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private int _longRunningOperationInitialTimeout; /// <summary> /// Gets or sets the initial timeout for Long Running Operations. /// </summary> public int LongRunningOperationInitialTimeout { get { return this._longRunningOperationInitialTimeout; } set { this._longRunningOperationInitialTimeout = value; } } private int _longRunningOperationRetryTimeout; /// <summary> /// Gets or sets the retry timeout for Long Running Operations. /// </summary> public int LongRunningOperationRetryTimeout { get { return this._longRunningOperationRetryTimeout; } set { this._longRunningOperationRetryTimeout = value; } } private IAuditingPolicyOperations _auditingPolicy; /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Database Server Audit policy. Contains operations to: Create, /// Retrieve and Update audit policy. /// </summary> public virtual IAuditingPolicyOperations AuditingPolicy { get { return this._auditingPolicy; } } private ICapabilitiesOperations _capabilities; /// <summary> /// Represents all the operations for determining the set of /// capabilites available in a specified region. /// </summary> public virtual ICapabilitiesOperations Capabilities { get { return this._capabilities; } } private IDatabaseActivationOperations _databaseActivation; /// <summary> /// Represents all the operations for operating pertaining to /// activation on Azure SQL Data Warehouse databases. Contains /// operations to: Pause and Resume databases /// </summary> public virtual IDatabaseActivationOperations DatabaseActivation { get { return this._databaseActivation; } } private IDatabaseBackupOperations _databaseBackup; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// database backups. /// </summary> public virtual IDatabaseBackupOperations DatabaseBackup { get { return this._databaseBackup; } } private IDatabaseOperations _databases; /// <summary> /// Represents all the operations for operating on Azure SQL Databases. /// Contains operations to: Create, Retrieve, Update, and Delete /// databases, and also includes the ability to get the event logs for /// a database. /// </summary> public virtual IDatabaseOperations Databases { get { return this._databases; } } private IDataMaskingOperations _dataMasking; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// data masking. Contains operations to: Create, Retrieve, Update, /// and Delete data masking rules, as well as Create, Retreive and /// Update data masking policy. /// </summary> public virtual IDataMaskingOperations DataMasking { get { return this._dataMasking; } } private IElasticPoolOperations _elasticPools; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Elastic Pools. Contains operations to: Create, Retrieve, Update, /// and Delete. /// </summary> public virtual IElasticPoolOperations ElasticPools { get { return this._elasticPools; } } private IFirewallRuleOperations _firewallRules; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Server Firewall Rules. Contains operations to: Create, Retrieve, /// Update, and Delete firewall rules. /// </summary> public virtual IFirewallRuleOperations FirewallRules { get { return this._firewallRules; } } private IImportExportOperations _importExport; /// <summary> /// Represents all the operations for import/export on Azure SQL /// Databases. Contains operations to: Import, Export, Get /// Import/Export status for a database. /// </summary> public virtual IImportExportOperations ImportExport { get { return this._importExport; } } private IRecommendedElasticPoolOperations _recommendedElasticPools; /// <summary> /// Represents all the operations for operating on Azure SQL /// Recommended Elastic Pools. Contains operations to: Retrieve. /// </summary> public virtual IRecommendedElasticPoolOperations RecommendedElasticPools { get { return this._recommendedElasticPools; } } private IRecommendedIndexOperations _recommendedIndexes; /// <summary> /// Represents all the operations for managing recommended indexes on /// Azure SQL Databases. Contains operations to retrieve recommended /// index and update state. /// </summary> public virtual IRecommendedIndexOperations RecommendedIndexes { get { return this._recommendedIndexes; } } private IReplicationLinkOperations _databaseReplicationLinks; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Replication Links. Contains operations to: Delete and Retrieve /// replication links. /// </summary> public virtual IReplicationLinkOperations DatabaseReplicationLinks { get { return this._databaseReplicationLinks; } } private ISecureConnectionPolicyOperations _secureConnection; /// <summary> /// Represents all the operations for managing Azure SQL Database /// secure connection. Contains operations to: Create, Retrieve and /// Update secure connection policy . /// </summary> public virtual ISecureConnectionPolicyOperations SecureConnection { get { return this._secureConnection; } } private ISecurityAlertPolicyOperations _securityAlertPolicy; /// <summary> /// Represents all the operations to manage Azure SQL Database and /// Database Server Security Alert policy. Contains operations to: /// Create, Retrieve and Update policy. /// </summary> public virtual ISecurityAlertPolicyOperations SecurityAlertPolicy { get { return this._securityAlertPolicy; } } private IServerAdministratorOperations _serverAdministrators; /// <summary> /// Represents all the operations for operating on Azure SQL Server /// Active Directory Administrators. Contains operations to: Create, /// Retrieve, Update, and Delete Azure SQL Server Active Directory /// Administrators. /// </summary> public virtual IServerAdministratorOperations ServerAdministrators { get { return this._serverAdministrators; } } private IServerCommunicationLinkOperations _communicationLinks; /// <summary> /// Represents all the operations for operating on Azure SQL Server /// communication links. Contains operations to: Create, Retrieve, /// Update, and Delete. /// </summary> public virtual IServerCommunicationLinkOperations CommunicationLinks { get { return this._communicationLinks; } } private IServerDisasterRecoveryConfigurationOperations _serverDisasterRecoveryConfigurations; /// <summary> /// Represents all the operations for operating on Azure SQL Server /// disaster recovery configurations. Contains operations to: Create, /// Retrieve, Update, Failover, and Delete. /// </summary> public virtual IServerDisasterRecoveryConfigurationOperations ServerDisasterRecoveryConfigurations { get { return this._serverDisasterRecoveryConfigurations; } } private IServerOperations _servers; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Servers. Contains operations to: Create, Retrieve, Update, and /// Delete servers. /// </summary> public virtual IServerOperations Servers { get { return this._servers; } } private IServerUpgradeOperations _serverUpgrades; /// <summary> /// Represents all the operations for Azure SQL Database Server Upgrade /// </summary> public virtual IServerUpgradeOperations ServerUpgrades { get { return this._serverUpgrades; } } private IServiceObjectiveOperations _serviceObjectives; /// <summary> /// Represents all the operations for operating on Azure SQL Database /// Service Objectives. Contains operations to: Retrieve service /// objectives. /// </summary> public virtual IServiceObjectiveOperations ServiceObjectives { get { return this._serviceObjectives; } } private IServiceTierAdvisorOperations _serviceTierAdvisors; /// <summary> /// Represents all the operations for operating on service tier /// advisors. Contains operations to: Retrieve. /// </summary> public virtual IServiceTierAdvisorOperations ServiceTierAdvisors { get { return this._serviceTierAdvisors; } } private ITransparentDataEncryptionOperations _transparentDataEncryption; /// <summary> /// Represents all the operations of Azure SQL Database Transparent /// Data Encryption. Contains operations to: Retrieve, and Update /// Transparent Data Encryption. /// </summary> public virtual ITransparentDataEncryptionOperations TransparentDataEncryption { get { return this._transparentDataEncryption; } } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> public SqlManagementClient() : base() { this._auditingPolicy = new AuditingPolicyOperations(this); this._capabilities = new CapabilitiesOperations(this); this._databaseActivation = new DatabaseActivationOperations(this); this._databaseBackup = new DatabaseBackupOperations(this); this._databases = new DatabaseOperations(this); this._dataMasking = new DataMaskingOperations(this); this._elasticPools = new ElasticPoolOperations(this); this._firewallRules = new FirewallRuleOperations(this); this._importExport = new ImportExportOperations(this); this._recommendedElasticPools = new RecommendedElasticPoolOperations(this); this._recommendedIndexes = new RecommendedIndexOperations(this); this._databaseReplicationLinks = new ReplicationLinkOperations(this); this._secureConnection = new SecureConnectionPolicyOperations(this); this._securityAlertPolicy = new SecurityAlertPolicyOperations(this); this._serverAdministrators = new ServerAdministratorOperations(this); this._communicationLinks = new ServerCommunicationLinkOperations(this); this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this); this._servers = new ServerOperations(this); this._serverUpgrades = new ServerUpgradeOperations(this); this._serviceObjectives = new ServiceObjectiveOperations(this); this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this); this._transparentDataEncryption = new TransparentDataEncryptionOperations(this); this._apiVersion = "2014-04-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='httpClient'> /// The Http client /// </param> public SqlManagementClient(HttpClient httpClient) : base(httpClient) { this._auditingPolicy = new AuditingPolicyOperations(this); this._capabilities = new CapabilitiesOperations(this); this._databaseActivation = new DatabaseActivationOperations(this); this._databaseBackup = new DatabaseBackupOperations(this); this._databases = new DatabaseOperations(this); this._dataMasking = new DataMaskingOperations(this); this._elasticPools = new ElasticPoolOperations(this); this._firewallRules = new FirewallRuleOperations(this); this._importExport = new ImportExportOperations(this); this._recommendedElasticPools = new RecommendedElasticPoolOperations(this); this._recommendedIndexes = new RecommendedIndexOperations(this); this._databaseReplicationLinks = new ReplicationLinkOperations(this); this._secureConnection = new SecureConnectionPolicyOperations(this); this._securityAlertPolicy = new SecurityAlertPolicyOperations(this); this._serverAdministrators = new ServerAdministratorOperations(this); this._communicationLinks = new ServerCommunicationLinkOperations(this); this._serverDisasterRecoveryConfigurations = new ServerDisasterRecoveryConfigurationOperations(this); this._servers = new ServerOperations(this); this._serverUpgrades = new ServerUpgradeOperations(this); this._serviceObjectives = new ServiceObjectiveOperations(this); this._serviceTierAdvisors = new ServiceTierAdvisorOperations(this); this._transparentDataEncryption = new TransparentDataEncryptionOperations(this); this._apiVersion = "2014-04-01"; this._longRunningOperationInitialTimeout = -1; this._longRunningOperationRetryTimeout = -1; this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='baseUri'> /// Optional. Gets the URI used as the base for all cloud service /// requests. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the SqlManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets subscription credentials which uniquely identify /// Microsoft Azure subscription. The subscription ID forms part of /// the URI for every service call. /// </param> /// <param name='httpClient'> /// The Http client /// </param> public SqlManagementClient(SubscriptionCloudCredentials credentials, HttpClient httpClient) : this(httpClient) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.azure.com"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// Clones properties from current instance to another /// SqlManagementClient instance /// </summary> /// <param name='client'> /// Instance of SqlManagementClient to clone to /// </param> protected override void Clone(ServiceClient<SqlManagementClient> client) { base.Clone(client); if (client is SqlManagementClient) { SqlManagementClient clonedClient = ((SqlManagementClient)client); clonedClient._credentials = this._credentials; clonedClient._baseUri = this._baseUri; clonedClient._apiVersion = this._apiVersion; clonedClient._longRunningOperationInitialTimeout = this._longRunningOperationInitialTimeout; clonedClient._longRunningOperationRetryTimeout = this._longRunningOperationRetryTimeout; clonedClient.Credentials.InitializeServiceClient(clonedClient); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void AddScalarSingle() { var test = new SimpleBinaryOpTest__AddScalarSingle(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); if (Sse.IsSupported) { // Validates passing a static member works, using pinning and Load test.RunClsVarScenario_Load(); } // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local class works, using pinning and Load test.RunClassLclFldScenario_Load(); } // Validates passing an instance member of a class works test.RunClassFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a class works, using pinning and Load test.RunClassFldScenario_Load(); } // Validates passing the field of a local struct works test.RunStructLclFldScenario(); if (Sse.IsSupported) { // Validates passing the field of a local struct works, using pinning and Load test.RunStructLclFldScenario_Load(); } // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (Sse.IsSupported) { // Validates passing an instance member of a struct works, using pinning and Load test.RunStructFldScenario_Load(); } } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddScalarSingle { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private byte[] outArray; private GCHandle inHandle1; private GCHandle inHandle2; private GCHandle outHandle; private ulong alignment; public DataTable(Single[] inArray1, Single[] inArray2, Single[] outArray, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Single>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Single>(); int sizeOfoutArray = outArray.Length * Unsafe.SizeOf<Single>(); if ((alignment != 32 && alignment != 16) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2 || (alignment * 2) < sizeOfoutArray) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.outArray = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.outHandle = GCHandle.Alloc(this.outArray, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Single, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Single, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void* outArrayPtr => Align((byte*)(outHandle.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); outHandle.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Single> _fld1; public Vector128<Single> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref testStruct._fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); return testStruct; } public void RunStructFldScenario(SimpleBinaryOpTest__AddScalarSingle testClass) { var result = Sse.AddScalar(_fld1, _fld2); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } public void RunStructFldScenario_Load(SimpleBinaryOpTest__AddScalarSingle testClass) { fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.AddScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld1, _fld2, testClass._dataTable.outArrayPtr); } } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Single>>() / sizeof(Single); private static Single[] _data1 = new Single[Op1ElementCount]; private static Single[] _data2 = new Single[Op2ElementCount]; private static Vector128<Single> _clsVar1; private static Vector128<Single> _clsVar2; private Vector128<Single> _fld1; private Vector128<Single> _fld2; private DataTable _dataTable; static SimpleBinaryOpTest__AddScalarSingle() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); } public SimpleBinaryOpTest__AddScalarSingle() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Single>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetSingle(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetSingle(); } _dataTable = new DataTable(_data1, _data2, new Single[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse.AddScalar( Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse.AddScalar( Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse.AddScalar( Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse).GetMethod(nameof(Sse.AddScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse).GetMethod(nameof(Sse.AddScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse).GetMethod(nameof(Sse.AddScalar), new Type[] { typeof(Vector128<Single>), typeof(Vector128<Single>) }) .Invoke(null, new object[] { Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)), Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Single>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse.AddScalar( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunClsVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario_Load)); fixed (Vector128<Single>* pClsVar1 = &_clsVar1) fixed (Vector128<Single>* pClsVar2 = &_clsVar2) { var result = Sse.AddScalar( Sse.LoadVector128((Single*)(pClsVar1)), Sse.LoadVector128((Single*)(pClsVar2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var op1 = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var op1 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var op2 = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.AddScalar(op1, op2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(op1, op2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new SimpleBinaryOpTest__AddScalarSingle(); var result = Sse.AddScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunClassLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario_Load)); var test = new SimpleBinaryOpTest__AddScalarSingle(); fixed (Vector128<Single>* pFld1 = &test._fld1) fixed (Vector128<Single>* pFld2 = &test._fld2) { var result = Sse.AddScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse.AddScalar(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunClassFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario_Load)); fixed (Vector128<Single>* pFld1 = &_fld1) fixed (Vector128<Single>* pFld2 = &_fld2) { var result = Sse.AddScalar( Sse.LoadVector128((Single*)(pFld1)), Sse.LoadVector128((Single*)(pFld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse.AddScalar(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructLclFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario_Load)); var test = TestStruct.Create(); var result = Sse.AddScalar( Sse.LoadVector128((Single*)(&test._fld1)), Sse.LoadVector128((Single*)(&test._fld2)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunStructFldScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario_Load)); var test = TestStruct.Create(); test.RunStructFldScenario_Load(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Single> op1, Vector128<Single> op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), op2); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* op1, void* op2, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Single>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Single>>()); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (BitConverter.SingleToInt32Bits(left[0] + right[0]) != BitConverter.SingleToInt32Bits(result[0])) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(left[i]) != BitConverter.SingleToInt32Bits(result[i])) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse)}.{nameof(Sse.AddScalar)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the PnMu class. /// </summary> [Serializable] public partial class PnMuCollection : ActiveList<PnMu, PnMuCollection> { public PnMuCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>PnMuCollection</returns> public PnMuCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { PnMu o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the PN_mu table. /// </summary> [Serializable] public partial class PnMu : ActiveRecord<PnMu>, IActiveRecord { #region .ctors and Default Settings public PnMu() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public PnMu(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public PnMu(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public PnMu(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("PN_mu", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarIdMu = new TableSchema.TableColumn(schema); colvarIdMu.ColumnName = "id_mu"; colvarIdMu.DataType = DbType.Int32; colvarIdMu.MaxLength = 0; colvarIdMu.AutoIncrement = true; colvarIdMu.IsNullable = false; colvarIdMu.IsPrimaryKey = true; colvarIdMu.IsForeignKey = false; colvarIdMu.IsReadOnly = false; colvarIdMu.DefaultSetting = @""; colvarIdMu.ForeignKeyTableName = ""; schema.Columns.Add(colvarIdMu); TableSchema.TableColumn colvarCuie = new TableSchema.TableColumn(schema); colvarCuie.ColumnName = "cuie"; colvarCuie.DataType = DbType.AnsiString; colvarCuie.MaxLength = -1; colvarCuie.AutoIncrement = false; colvarCuie.IsNullable = false; colvarCuie.IsPrimaryKey = false; colvarCuie.IsForeignKey = false; colvarCuie.IsReadOnly = false; colvarCuie.DefaultSetting = @""; colvarCuie.ForeignKeyTableName = ""; schema.Columns.Add(colvarCuie); TableSchema.TableColumn colvarTipoDoc = new TableSchema.TableColumn(schema); colvarTipoDoc.ColumnName = "tipo_doc"; colvarTipoDoc.DataType = DbType.AnsiString; colvarTipoDoc.MaxLength = -1; colvarTipoDoc.AutoIncrement = false; colvarTipoDoc.IsNullable = true; colvarTipoDoc.IsPrimaryKey = false; colvarTipoDoc.IsForeignKey = false; colvarTipoDoc.IsReadOnly = false; colvarTipoDoc.DefaultSetting = @""; colvarTipoDoc.ForeignKeyTableName = ""; schema.Columns.Add(colvarTipoDoc); TableSchema.TableColumn colvarNumDoc = new TableSchema.TableColumn(schema); colvarNumDoc.ColumnName = "num_doc"; colvarNumDoc.DataType = DbType.Decimal; colvarNumDoc.MaxLength = 0; colvarNumDoc.AutoIncrement = false; colvarNumDoc.IsNullable = true; colvarNumDoc.IsPrimaryKey = false; colvarNumDoc.IsForeignKey = false; colvarNumDoc.IsReadOnly = false; colvarNumDoc.DefaultSetting = @""; colvarNumDoc.ForeignKeyTableName = ""; schema.Columns.Add(colvarNumDoc); TableSchema.TableColumn colvarApellido = new TableSchema.TableColumn(schema); colvarApellido.ColumnName = "apellido"; colvarApellido.DataType = DbType.AnsiString; colvarApellido.MaxLength = -1; colvarApellido.AutoIncrement = false; colvarApellido.IsNullable = true; colvarApellido.IsPrimaryKey = false; colvarApellido.IsForeignKey = false; colvarApellido.IsReadOnly = false; colvarApellido.DefaultSetting = @""; colvarApellido.ForeignKeyTableName = ""; schema.Columns.Add(colvarApellido); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = -1; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = true; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); TableSchema.TableColumn colvarFechaDefuncion = new TableSchema.TableColumn(schema); colvarFechaDefuncion.ColumnName = "fecha_defuncion"; colvarFechaDefuncion.DataType = DbType.DateTime; colvarFechaDefuncion.MaxLength = 0; colvarFechaDefuncion.AutoIncrement = false; colvarFechaDefuncion.IsNullable = true; colvarFechaDefuncion.IsPrimaryKey = false; colvarFechaDefuncion.IsForeignKey = false; colvarFechaDefuncion.IsReadOnly = false; colvarFechaDefuncion.DefaultSetting = @""; colvarFechaDefuncion.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaDefuncion); TableSchema.TableColumn colvarFechaAuditoria = new TableSchema.TableColumn(schema); colvarFechaAuditoria.ColumnName = "fecha_auditoria"; colvarFechaAuditoria.DataType = DbType.DateTime; colvarFechaAuditoria.MaxLength = 0; colvarFechaAuditoria.AutoIncrement = false; colvarFechaAuditoria.IsNullable = true; colvarFechaAuditoria.IsPrimaryKey = false; colvarFechaAuditoria.IsForeignKey = false; colvarFechaAuditoria.IsReadOnly = false; colvarFechaAuditoria.DefaultSetting = @""; colvarFechaAuditoria.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaAuditoria); TableSchema.TableColumn colvarFechaParInt = new TableSchema.TableColumn(schema); colvarFechaParInt.ColumnName = "fecha_par_int"; colvarFechaParInt.DataType = DbType.DateTime; colvarFechaParInt.MaxLength = 0; colvarFechaParInt.AutoIncrement = false; colvarFechaParInt.IsNullable = true; colvarFechaParInt.IsPrimaryKey = false; colvarFechaParInt.IsForeignKey = false; colvarFechaParInt.IsReadOnly = false; colvarFechaParInt.DefaultSetting = @""; colvarFechaParInt.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaParInt); TableSchema.TableColumn colvarFechaNac = new TableSchema.TableColumn(schema); colvarFechaNac.ColumnName = "fecha_nac"; colvarFechaNac.DataType = DbType.DateTime; colvarFechaNac.MaxLength = 0; colvarFechaNac.AutoIncrement = false; colvarFechaNac.IsNullable = true; colvarFechaNac.IsPrimaryKey = false; colvarFechaNac.IsForeignKey = false; colvarFechaNac.IsReadOnly = false; colvarFechaNac.DefaultSetting = @""; colvarFechaNac.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaNac); TableSchema.TableColumn colvarObservaciones = new TableSchema.TableColumn(schema); colvarObservaciones.ColumnName = "observaciones"; colvarObservaciones.DataType = DbType.AnsiString; colvarObservaciones.MaxLength = -1; colvarObservaciones.AutoIncrement = false; colvarObservaciones.IsNullable = true; colvarObservaciones.IsPrimaryKey = false; colvarObservaciones.IsForeignKey = false; colvarObservaciones.IsReadOnly = false; colvarObservaciones.DefaultSetting = @""; colvarObservaciones.ForeignKeyTableName = ""; schema.Columns.Add(colvarObservaciones); TableSchema.TableColumn colvarFechaCarga = new TableSchema.TableColumn(schema); colvarFechaCarga.ColumnName = "fecha_carga"; colvarFechaCarga.DataType = DbType.DateTime; colvarFechaCarga.MaxLength = 0; colvarFechaCarga.AutoIncrement = false; colvarFechaCarga.IsNullable = true; colvarFechaCarga.IsPrimaryKey = false; colvarFechaCarga.IsForeignKey = false; colvarFechaCarga.IsReadOnly = false; colvarFechaCarga.DefaultSetting = @""; colvarFechaCarga.ForeignKeyTableName = ""; schema.Columns.Add(colvarFechaCarga); TableSchema.TableColumn colvarUsuario = new TableSchema.TableColumn(schema); colvarUsuario.ColumnName = "usuario"; colvarUsuario.DataType = DbType.AnsiString; colvarUsuario.MaxLength = -1; colvarUsuario.AutoIncrement = false; colvarUsuario.IsNullable = true; colvarUsuario.IsPrimaryKey = false; colvarUsuario.IsForeignKey = false; colvarUsuario.IsReadOnly = false; colvarUsuario.DefaultSetting = @""; colvarUsuario.ForeignKeyTableName = ""; schema.Columns.Add(colvarUsuario); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("PN_mu",schema); } } #endregion #region Props [XmlAttribute("IdMu")] [Bindable(true)] public int IdMu { get { return GetColumnValue<int>(Columns.IdMu); } set { SetColumnValue(Columns.IdMu, value); } } [XmlAttribute("Cuie")] [Bindable(true)] public string Cuie { get { return GetColumnValue<string>(Columns.Cuie); } set { SetColumnValue(Columns.Cuie, value); } } [XmlAttribute("TipoDoc")] [Bindable(true)] public string TipoDoc { get { return GetColumnValue<string>(Columns.TipoDoc); } set { SetColumnValue(Columns.TipoDoc, value); } } [XmlAttribute("NumDoc")] [Bindable(true)] public decimal? NumDoc { get { return GetColumnValue<decimal?>(Columns.NumDoc); } set { SetColumnValue(Columns.NumDoc, value); } } [XmlAttribute("Apellido")] [Bindable(true)] public string Apellido { get { return GetColumnValue<string>(Columns.Apellido); } set { SetColumnValue(Columns.Apellido, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } [XmlAttribute("FechaDefuncion")] [Bindable(true)] public DateTime? FechaDefuncion { get { return GetColumnValue<DateTime?>(Columns.FechaDefuncion); } set { SetColumnValue(Columns.FechaDefuncion, value); } } [XmlAttribute("FechaAuditoria")] [Bindable(true)] public DateTime? FechaAuditoria { get { return GetColumnValue<DateTime?>(Columns.FechaAuditoria); } set { SetColumnValue(Columns.FechaAuditoria, value); } } [XmlAttribute("FechaParInt")] [Bindable(true)] public DateTime? FechaParInt { get { return GetColumnValue<DateTime?>(Columns.FechaParInt); } set { SetColumnValue(Columns.FechaParInt, value); } } [XmlAttribute("FechaNac")] [Bindable(true)] public DateTime? FechaNac { get { return GetColumnValue<DateTime?>(Columns.FechaNac); } set { SetColumnValue(Columns.FechaNac, value); } } [XmlAttribute("Observaciones")] [Bindable(true)] public string Observaciones { get { return GetColumnValue<string>(Columns.Observaciones); } set { SetColumnValue(Columns.Observaciones, value); } } [XmlAttribute("FechaCarga")] [Bindable(true)] public DateTime? FechaCarga { get { return GetColumnValue<DateTime?>(Columns.FechaCarga); } set { SetColumnValue(Columns.FechaCarga, value); } } [XmlAttribute("Usuario")] [Bindable(true)] public string Usuario { get { return GetColumnValue<string>(Columns.Usuario); } set { SetColumnValue(Columns.Usuario, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(string varCuie,string varTipoDoc,decimal? varNumDoc,string varApellido,string varNombre,DateTime? varFechaDefuncion,DateTime? varFechaAuditoria,DateTime? varFechaParInt,DateTime? varFechaNac,string varObservaciones,DateTime? varFechaCarga,string varUsuario) { PnMu item = new PnMu(); item.Cuie = varCuie; item.TipoDoc = varTipoDoc; item.NumDoc = varNumDoc; item.Apellido = varApellido; item.Nombre = varNombre; item.FechaDefuncion = varFechaDefuncion; item.FechaAuditoria = varFechaAuditoria; item.FechaParInt = varFechaParInt; item.FechaNac = varFechaNac; item.Observaciones = varObservaciones; item.FechaCarga = varFechaCarga; item.Usuario = varUsuario; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varIdMu,string varCuie,string varTipoDoc,decimal? varNumDoc,string varApellido,string varNombre,DateTime? varFechaDefuncion,DateTime? varFechaAuditoria,DateTime? varFechaParInt,DateTime? varFechaNac,string varObservaciones,DateTime? varFechaCarga,string varUsuario) { PnMu item = new PnMu(); item.IdMu = varIdMu; item.Cuie = varCuie; item.TipoDoc = varTipoDoc; item.NumDoc = varNumDoc; item.Apellido = varApellido; item.Nombre = varNombre; item.FechaDefuncion = varFechaDefuncion; item.FechaAuditoria = varFechaAuditoria; item.FechaParInt = varFechaParInt; item.FechaNac = varFechaNac; item.Observaciones = varObservaciones; item.FechaCarga = varFechaCarga; item.Usuario = varUsuario; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdMuColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn CuieColumn { get { return Schema.Columns[1]; } } public static TableSchema.TableColumn TipoDocColumn { get { return Schema.Columns[2]; } } public static TableSchema.TableColumn NumDocColumn { get { return Schema.Columns[3]; } } public static TableSchema.TableColumn ApellidoColumn { get { return Schema.Columns[4]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[5]; } } public static TableSchema.TableColumn FechaDefuncionColumn { get { return Schema.Columns[6]; } } public static TableSchema.TableColumn FechaAuditoriaColumn { get { return Schema.Columns[7]; } } public static TableSchema.TableColumn FechaParIntColumn { get { return Schema.Columns[8]; } } public static TableSchema.TableColumn FechaNacColumn { get { return Schema.Columns[9]; } } public static TableSchema.TableColumn ObservacionesColumn { get { return Schema.Columns[10]; } } public static TableSchema.TableColumn FechaCargaColumn { get { return Schema.Columns[11]; } } public static TableSchema.TableColumn UsuarioColumn { get { return Schema.Columns[12]; } } #endregion #region Columns Struct public struct Columns { public static string IdMu = @"id_mu"; public static string Cuie = @"cuie"; public static string TipoDoc = @"tipo_doc"; public static string NumDoc = @"num_doc"; public static string Apellido = @"apellido"; public static string Nombre = @"nombre"; public static string FechaDefuncion = @"fecha_defuncion"; public static string FechaAuditoria = @"fecha_auditoria"; public static string FechaParInt = @"fecha_par_int"; public static string FechaNac = @"fecha_nac"; public static string Observaciones = @"observaciones"; public static string FechaCarga = @"fecha_carga"; public static string Usuario = @"usuario"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.ExtractMethod; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.ExtractMethod { public class ExtractMethodTests : AbstractCSharpCodeActionTest { protected override object CreateCodeRefactoringProvider(Workspace workspace) { return new ExtractMethodCodeRefactoringProvider(); } [WorkItem(540799)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestPartialSelection() { await TestAsync( @"class Program { static void Main ( string [ ] args ) { bool b = true ; System . Console . WriteLine ( [|b != true|] ? b = true : b = false ) ; } } ", @"class Program { static void Main ( string [ ] args ) { bool b = true ; System . Console . WriteLine ( {|Rename:NewMethod|} ( b ) ? b = true : b = false ) ; } private static bool NewMethod ( bool b ) { return b != true ; } } ", index: 0); } [WorkItem(540796)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestReadOfDataThatDoesNotFlowIn() { await TestAsync( @"class Program { static void Main ( string [ ] args ) { int x = 1 ; object y = 0 ; [|int s = true ? fun ( x ) : fun ( y ) ;|] } private static T fun < T > ( T t ) { return t ; } } ", @"class Program { static void Main ( string [ ] args ) { int x = 1 ; object y = 0 ; {|Rename:NewMethod|} ( x , y ) ; } private static void NewMethod ( int x , object y ) { int s = true ? fun ( x ) : fun ( y ) ; } private static T fun < T > ( T t ) { return t ; } } ", index: 0); } [WorkItem(540819)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnGoto() { await TestMissingAsync(@"delegate int del ( int i ) ; class C { static void Main ( string [ ] args ) { del q = x => { [|goto label2 ; return x * x ;|] } ; label2 : return ; } } "); } [WorkItem(540819)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnStatementAfterUnconditionalGoto() { await TestAsync( @"delegate int del ( int i ) ; class C { static void Main ( string [ ] args ) { del q = x => { goto label2 ; [|return x * x ;|] } ; label2 : return ; } } ", @"delegate int del ( int i ) ; class C { static void Main ( string [ ] args ) { del q = x => { goto label2 ; return {|Rename:NewMethod|} ( x ) ; } ; label2 : return ; } private static int NewMethod ( int x ) { return x * x ; } } ", index: 0); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnNamespace() { await TestAsync( @"class Program { void Main ( ) { [|System|] . Console . WriteLine ( 4 ) ; } } ", @"class Program { void Main ( ) { {|Rename:NewMethod|} ( ) ; } private static void NewMethod ( ) { System . Console . WriteLine ( 4 ) ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnType() { await TestAsync( @"class Program { void Main ( ) { [|System . Console|] . WriteLine ( 4 ) ; } } ", @"class Program { void Main ( ) { {|Rename:NewMethod|} ( ) ; } private static void NewMethod ( ) { System . Console . WriteLine ( 4 ) ; } } "); } [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestMissingOnBase() { await TestAsync( @"class Program { void Main ( ) { [|base|] . ToString ( ) ; } } ", @"class Program { void Main ( ) { {|Rename:NewMethod|} ( ) ; } private void NewMethod ( ) { base . ToString ( ) ; } } "); } [WorkItem(545623)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task TestOnActionInvocation() { await TestAsync( @"using System ; class C { public static Action X { get ; set ; } } class Program { void Main ( ) { [|C . X|] ( ) ; } } ", @"using System ; class C { public static Action X { get ; set ; } } class Program { void Main ( ) { {|Rename:GetX|} ( ) ( ) ; } private static Action GetX ( ) { return C . X ; } } "); } [WorkItem(529841), WorkItem(714632)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary1() { await TestAsync( @"using System; class Program { static void Main() { byte z = 0; Foo([|x => 0|], y => 0, z, z); } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Foo<byte, byte>({|Rename:NewMethod|}(), y => 0, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", compareTokens: false); } [WorkItem(529841), WorkItem(714632)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DisambiguateCallSiteIfNecessary2() { await TestAsync( @"using System; class Program { static void Main() { byte z = 0; Foo([|x => 0|], y => { return 0; }, z, z); } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", @"using System; class Program { static void Main() { byte z = 0; Foo<byte, byte>({|Rename:NewMethod|}(), y => { return 0; }, z, z); } private static Func<byte, byte> NewMethod() { return x => 0; } static void Foo<T, S>(Func<S, T> p, Func<T, S> q, T r, S s) { Console.WriteLine(1); } static void Foo(Func<byte, byte> p, Func<byte, byte> q, int r, int s) { Console.WriteLine(2); } }", compareTokens: false); } [WorkItem(530709)] [WorkItem(632182)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesize() { await TestAsync( @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex(), y), - -1); } } static class E { public static void Ex(this int x) { } }", @"using System; static class C { static void Ex(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(632182)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task DontOverparenthesizeGenerics() { await TestAsync( @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => [|x|].Ex<int>(), y), - -1); } } static class E { public static void Ex<T>(this int x) { } }", @"using System; static class C { static void Ex<T>(this string x) { } static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, int y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => {|Rename:GetX|}(x).Ex<int>(), y), (object)- -1); } private static string GetX(string x) { return x; } } static class E { public static void Ex<T>(this int x) { } }", parseOptions: Options.Regular); } [WorkItem(984831)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_1() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do();|] obj1.Do(); obj2.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2; {|Rename:NewMethod|}(out obj1, out obj2); obj1.Do(); obj2.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); } }", compareTokens: false); } [WorkItem(984831)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_2() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ Construct obj3 = new Construct(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj2.Do(); /* Second Interesting comment. */ obj3 = new Construct(); obj3.Do(); } }", compareTokens: false); } [WorkItem(984831)] [WpfFact, Trait(Traits.Feature, Traits.Features.CodeActionsExtractMethod)] public async Task PreserveCommentsBeforeDeclaration_3() { await TestAsync( @"class Construct { public void Do() { } static void Main(string[] args) { [|Construct obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ Construct obj2 = new Construct(), obj3 = new Construct(); obj2.Do(); obj3.Do();|] obj1.Do(); obj2.Do(); obj3.Do(); } }", @"class Construct { public void Do() { } static void Main(string[] args) { Construct obj1, obj2, obj3; {|Rename:NewMethod|}(out obj1, out obj2, out obj3); obj1.Do(); obj2.Do(); obj3.Do(); } private static void NewMethod(out Construct obj1, out Construct obj2, out Construct obj3) { obj1 = new Construct(); obj1.Do(); /* Interesting comment. */ obj2 = new Construct(); obj3 = new Construct(); obj2.Do(); obj3.Do(); } }", compareTokens: false); } } }
// DataTableMappingCollectionTest.cs - NUnit Test Cases for Testing the // DataTableMappingCollection class // // Author: Ameya Sailesh Gargesh (ameya_13@yahoo.com) // // (C) Ameya Gargesh // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using NUnit.Framework; using System; using System.Data; using System.Data.Common; namespace MonoTests.System.Data.Common { [TestFixture] public class DataTableMappingCollectionTest : Assertion { DataTableMappingCollection tableMapCollection; DataTableMapping [] tabs; [SetUp] public void GetReady() { tabs=new DataTableMapping[5]; tabs[0]=new DataTableMapping("sourceCustomers","dataSetCustomers"); tabs[1]=new DataTableMapping("sourceEmployees","dataSetEmployees"); tabs[2]=new DataTableMapping("sourceBooks","dataSetBooks"); tabs[3]=new DataTableMapping("sourceStore","dataSetStore"); tabs[4]=new DataTableMapping("sourceInventory","dataSetInventory"); tableMapCollection=new DataTableMappingCollection(); } [TearDown] public void Clean() { tableMapCollection.Clear(); } [Test] public void Add() { int t=tableMapCollection.Add((Object)tabs[0]); AssertEquals("test1",0,t); bool eq1=tabs[0].Equals(tableMapCollection[0]); AssertEquals("test2",true,eq1); AssertEquals("test3",1,tableMapCollection.Count); DataTableMapping tab2; tab2=tableMapCollection.Add("sourceEmployees","dataSetEmployees"); bool eq2=tab2.Equals(tableMapCollection[1]); AssertEquals("test4",true,eq2); AssertEquals("test5",2,tableMapCollection.Count); } [Test] [ExpectedException(typeof(InvalidCastException))] public void AddException1() { DataTableMappingCollection c=new DataTableMappingCollection(); tableMapCollection.Add((Object)c); } [Test] public void AddRange() { tableMapCollection.Add(new DataTableMapping("sourceFactory","dataSetFactory")); AssertEquals("test1",1,tableMapCollection.Count); tableMapCollection.AddRange(tabs); AssertEquals("test2",6,tableMapCollection.Count); bool eq; eq=tabs[0].Equals(tableMapCollection[1]); AssertEquals("test3",true,eq); eq=tabs[1].Equals(tableMapCollection[2]); AssertEquals("test4",true,eq); eq=tabs[0].Equals(tableMapCollection[0]); AssertEquals("test5",false,eq); eq=tabs[1].Equals(tableMapCollection[0]); AssertEquals("test6",false,eq); } [Test] public void Clear() { DataTableMapping tab1=new DataTableMapping("sourceSuppliers","dataSetSuppliers"); tableMapCollection.Add((Object)tab1); AssertEquals("test1",1,tableMapCollection.Count); tableMapCollection.Clear(); AssertEquals("test2",0,tableMapCollection.Count); tableMapCollection.AddRange(tabs); AssertEquals("test3",5,tableMapCollection.Count); tableMapCollection.Clear(); AssertEquals("test4",0,tableMapCollection.Count); } [Test] public void Contains() { DataTableMapping tab1=new DataTableMapping("sourceCustomers","dataSetCustomers"); tableMapCollection.AddRange(tabs); bool eq; eq=tableMapCollection.Contains((Object)tabs[0]); AssertEquals("test1",true,eq); eq=tableMapCollection.Contains((Object)tabs[1]); AssertEquals("test2",true,eq); eq=tableMapCollection.Contains((Object)tab1); AssertEquals("test3",false,eq); eq=tableMapCollection.Contains(tabs[0].SourceTable); AssertEquals("test4",true,eq); eq=tableMapCollection.Contains(tabs[1].SourceTable); AssertEquals("test5",true,eq); eq=tableMapCollection.Contains(tab1.SourceTable); AssertEquals("test6",true,eq); eq=tableMapCollection.Contains(tabs[0].DataSetTable); AssertEquals("test7",false,eq); eq=tableMapCollection.Contains(tabs[1].DataSetTable); AssertEquals("test8",false,eq); eq=tableMapCollection.Contains(tab1.DataSetTable); AssertEquals("test9",false,eq); } [Test] public void CopyTo() { DataTableMapping [] tabcops=new DataTableMapping[5]; tableMapCollection.AddRange(tabs); tableMapCollection.CopyTo(tabcops,0); bool eq; for (int i=0;i<5;i++) { eq=tableMapCollection[i].Equals(tabcops[i]); AssertEquals("test1"+i,true,eq); } tabcops=null; tabcops=new DataTableMapping[7]; tableMapCollection.CopyTo(tabcops,2); for (int i=0;i<5;i++) { eq=tableMapCollection[i].Equals(tabcops[i+2]); AssertEquals("test2"+i,true,eq); } eq=tableMapCollection[0].Equals(tabcops[0]); AssertEquals("test31",false,eq); eq=tableMapCollection[0].Equals(tabcops[1]); AssertEquals("test32",false,eq); } [Test] public void Equals() { // DataTableMappingCollection collect2=new DataTableMappingCollection(); tableMapCollection.AddRange(tabs); // collect2.AddRange(tabs); DataTableMappingCollection copy1; copy1=tableMapCollection; // AssertEquals("test1",false,tableMapCollection.Equals(collect2)); AssertEquals("test2",true,tableMapCollection.Equals(copy1)); // AssertEquals("test3",false,collect2.Equals(tableMapCollection)); AssertEquals("test4",true,copy1.Equals(tableMapCollection)); // AssertEquals("test5",false,collect2.Equals(copy1)); AssertEquals("test6",true,copy1.Equals(tableMapCollection)); AssertEquals("test7",true,tableMapCollection.Equals(tableMapCollection)); // AssertEquals("test8",true,collect2.Equals(collect2)); AssertEquals("test9",true,copy1.Equals(copy1)); // AssertEquals("test10",false,Object.Equals(collect2,tableMapCollection)); AssertEquals("test11",true,Object.Equals(copy1,tableMapCollection)); // AssertEquals("test12",false,Object.Equals(tableMapCollection,collect2)); AssertEquals("test13",true,Object.Equals(tableMapCollection,copy1)); // AssertEquals("test14",false,Object.Equals(copy1,collect2)); AssertEquals("test15",true,Object.Equals(tableMapCollection,copy1)); AssertEquals("test16",true,Object.Equals(tableMapCollection,tableMapCollection)); // AssertEquals("test17",true,Object.Equals(collect2,collect2)); AssertEquals("test18",true,Object.Equals(copy1,copy1)); // AssertEquals("test10",false,Object.Equals(tableMapCollection,collect2)); AssertEquals("test11",true,Object.Equals(tableMapCollection,copy1)); // AssertEquals("test12",false,Object.Equals(collect2,tableMapCollection)); AssertEquals("test13",true,Object.Equals(copy1,tableMapCollection)); // AssertEquals("test14",false,Object.Equals(collect2,copy1)); AssertEquals("test15",true,Object.Equals(copy1,tableMapCollection)); } [Test] public void GetByDataSetTable() { tableMapCollection.AddRange(tabs); bool eq; DataTableMapping tab1; tab1=tableMapCollection.GetByDataSetTable("dataSetCustomers"); eq=(tab1.DataSetTable.Equals("dataSetCustomers") && tab1.SourceTable.Equals("sourceCustomers")); AssertEquals("test1",true,eq); tab1=tableMapCollection.GetByDataSetTable("dataSetEmployees"); eq=(tab1.DataSetTable.Equals("dataSetEmployees") && tab1.SourceTable.Equals("sourceEmployees")); AssertEquals("test2",true,eq); tab1=tableMapCollection.GetByDataSetTable("datasetcustomers"); eq=(tab1.DataSetTable.Equals("dataSetCustomers") && tab1.SourceTable.Equals("sourceCustomers")); AssertEquals("test3",true,eq); tab1=tableMapCollection.GetByDataSetTable("datasetemployees"); eq=(tab1.DataSetTable.Equals("dataSetEmployees") && tab1.SourceTable.Equals("sourceEmployees")); AssertEquals("test4",true,eq); } [Test] public void GetTableMappingBySchemaAction() { tableMapCollection.AddRange(tabs); bool eq; DataTableMapping tab1; tab1=DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection,"sourceCustomers","dataSetCustomers",MissingMappingAction.Passthrough); eq=(tab1.DataSetTable.Equals("dataSetCustomers") && tab1.SourceTable.Equals("sourceCustomers")); AssertEquals("test1",true,eq); tab1=DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection,"sourceEmployees","dataSetEmployees",MissingMappingAction.Passthrough); eq=(tab1.DataSetTable.Equals("dataSetEmployees") && tab1.SourceTable.Equals("sourceEmployees")); AssertEquals("test2",true,eq); tab1=DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection,"sourceData","dataSetData",MissingMappingAction.Passthrough); eq=(tab1.DataSetTable.Equals("sourceData") && tab1.SourceTable.Equals("dataSetData")); AssertEquals("test3",false, eq); eq=tableMapCollection.Contains(tab1); AssertEquals("test4",false,eq); tab1=DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection,"sourceData","dataSetData",MissingMappingAction.Ignore); AssertEquals("test5",null,tab1); } [Test] [ExpectedException(typeof(InvalidOperationException))] public void GetTableMappingBySchemaActionException1() { DataTableMappingCollection.GetTableMappingBySchemaAction(tableMapCollection,"sourceCustomers","dataSetCustomers",MissingMappingAction.Error); } [Test] public void IndexOf() { tableMapCollection.AddRange(tabs); int ind; ind=tableMapCollection.IndexOf(tabs[0]); AssertEquals("test1",0,ind); ind=tableMapCollection.IndexOf(tabs[1]); AssertEquals("test2",1,ind); ind=tableMapCollection.IndexOf(tabs[0].SourceTable); AssertEquals("test3",0,ind); ind=tableMapCollection.IndexOf(tabs[1].SourceTable); AssertEquals("test4",1,ind); } [Test] public void IndexOfDataSetTable() { tableMapCollection.AddRange(tabs); int ind; ind=tableMapCollection.IndexOfDataSetTable(tabs[0].DataSetTable); AssertEquals("test1",0,ind); ind=tableMapCollection.IndexOfDataSetTable(tabs[1].DataSetTable); AssertEquals("test2",1,ind); ind=tableMapCollection.IndexOfDataSetTable("datasetcustomers"); AssertEquals("test3",0,ind); ind=tableMapCollection.IndexOfDataSetTable("datasetemployees"); AssertEquals("test4",1,ind); ind=tableMapCollection.IndexOfDataSetTable("sourcedeter"); AssertEquals("test5",-1,ind); } [Test] public void Insert() { tableMapCollection.AddRange(tabs); DataTableMapping mymap=new DataTableMapping("sourceTestAge","datatestSetAge"); tableMapCollection.Insert(3,mymap); int ind=tableMapCollection.IndexOfDataSetTable("datatestSetAge"); AssertEquals("test1",3,ind); } [Test] [Ignore ("This test is invalid; a mapping in a mapcollection must be identical.")] public void Remove() { tableMapCollection.AddRange(tabs); DataTableMapping mymap=new DataTableMapping("sourceCustomers","dataSetCustomers"); tableMapCollection.Add(mymap); tableMapCollection.Remove((Object)mymap); bool eq=tableMapCollection.Contains((Object)mymap); AssertEquals("test1",false,eq); } [Test] [ExpectedException(typeof(InvalidCastException))] public void RemoveException1() { String te="testingdata"; tableMapCollection.AddRange(tabs); tableMapCollection.Remove(te); } [Test] [ExpectedException(typeof(ArgumentException))] public void RemoveException2() { tableMapCollection.AddRange(tabs); DataTableMapping mymap=new DataTableMapping("sourceAge","dataSetAge"); tableMapCollection.Remove(mymap); } [Test] public void RemoveAt() { tableMapCollection.AddRange(tabs); bool eq; tableMapCollection.RemoveAt(0); eq=tableMapCollection.Contains(tabs[0]); AssertEquals("test1",false,eq); eq=tableMapCollection.Contains(tabs[1]); AssertEquals("test2",true,eq); tableMapCollection.RemoveAt("sourceEmployees"); eq=tableMapCollection.Contains(tabs[1]); AssertEquals("test3",false,eq); eq=tableMapCollection.Contains(tabs[2]); AssertEquals("test4",true,eq); } [Test] [ExpectedException(typeof(IndexOutOfRangeException))] public void RemoveAtException1() { tableMapCollection.RemoveAt(3); } [Test] [ExpectedException(typeof(IndexOutOfRangeException))] public void RemoveAtException2() { tableMapCollection.RemoveAt("sourceAge"); } [Test] public void ToStringTest() { AssertEquals("test1","System.Data.Common.DataTableMappingCollection",tableMapCollection.ToString()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.ComponentModel; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using System.Reflection; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Diagnostics; namespace System.Runtime.Serialization { internal static class Globals { /// <SecurityNote> /// Review - changes to const could affect code generation logic; any changes should be reviewed. /// </SecurityNote> internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; private static XmlQualifiedName s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get { if (s_idQualifiedName == null) s_idQualifiedName = new XmlQualifiedName(Globals.IdLocalName, Globals.SerializationNamespace); return s_idQualifiedName; } } private static XmlQualifiedName s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get { if (s_refQualifiedName == null) s_refQualifiedName = new XmlQualifiedName(Globals.RefLocalName, Globals.SerializationNamespace); return s_refQualifiedName; } } private static Type s_typeOfObject; internal static Type TypeOfObject { get { if (s_typeOfObject == null) s_typeOfObject = typeof(object); return s_typeOfObject; } } private static Type s_typeOfValueType; internal static Type TypeOfValueType { get { if (s_typeOfValueType == null) s_typeOfValueType = typeof(ValueType); return s_typeOfValueType; } } private static Type s_typeOfArray; internal static Type TypeOfArray { get { if (s_typeOfArray == null) s_typeOfArray = typeof(Array); return s_typeOfArray; } } private static Type s_typeOfString; internal static Type TypeOfString { get { if (s_typeOfString == null) s_typeOfString = typeof(string); return s_typeOfString; } } private static Type s_typeOfInt; internal static Type TypeOfInt { get { if (s_typeOfInt == null) s_typeOfInt = typeof(int); return s_typeOfInt; } } private static Type s_typeOfULong; internal static Type TypeOfULong { get { if (s_typeOfULong == null) s_typeOfULong = typeof(ulong); return s_typeOfULong; } } private static Type s_typeOfVoid; internal static Type TypeOfVoid { get { if (s_typeOfVoid == null) s_typeOfVoid = typeof(void); return s_typeOfVoid; } } private static Type s_typeOfByteArray; internal static Type TypeOfByteArray { get { if (s_typeOfByteArray == null) s_typeOfByteArray = typeof(byte[]); return s_typeOfByteArray; } } private static Type s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get { if (s_typeOfTimeSpan == null) s_typeOfTimeSpan = typeof(TimeSpan); return s_typeOfTimeSpan; } } private static Type s_typeOfGuid; internal static Type TypeOfGuid { get { if (s_typeOfGuid == null) s_typeOfGuid = typeof(Guid); return s_typeOfGuid; } } private static Type s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get { if (s_typeOfDateTimeOffset == null) s_typeOfDateTimeOffset = typeof(DateTimeOffset); return s_typeOfDateTimeOffset; } } private static Type s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get { if (s_typeOfDateTimeOffsetAdapter == null) s_typeOfDateTimeOffsetAdapter = typeof(DateTimeOffsetAdapter); return s_typeOfDateTimeOffsetAdapter; } } private static Type s_typeOfUri; internal static Type TypeOfUri { get { if (s_typeOfUri == null) s_typeOfUri = typeof(Uri); return s_typeOfUri; } } private static Type s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get { if (s_typeOfTypeEnumerable == null) s_typeOfTypeEnumerable = typeof(IEnumerable<Type>); return s_typeOfTypeEnumerable; } } private static Type s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get { if (s_typeOfStreamingContext == null) s_typeOfStreamingContext = typeof(StreamingContext); return s_typeOfStreamingContext; } } private static Type s_typeOfISerializable; internal static Type TypeOfISerializable { get { if (s_typeOfISerializable == null) s_typeOfISerializable = typeof(ISerializable); return s_typeOfISerializable; } } private static Type s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get { if (s_typeOfIDeserializationCallback == null) s_typeOfIDeserializationCallback = typeof(IDeserializationCallback); return s_typeOfIDeserializationCallback; } } private static Type s_typeOfIObjectReference; internal static Type TypeOfIObjectReference { get { if (s_typeOfIObjectReference == null) s_typeOfIObjectReference = typeof(IObjectReference); return s_typeOfIObjectReference; } } private static Type s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get { if (s_typeOfXmlFormatClassWriterDelegate == null) s_typeOfXmlFormatClassWriterDelegate = typeof(XmlFormatClassWriterDelegate); return s_typeOfXmlFormatClassWriterDelegate; } } private static Type s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get { if (s_typeOfXmlFormatCollectionWriterDelegate == null) s_typeOfXmlFormatCollectionWriterDelegate = typeof(XmlFormatCollectionWriterDelegate); return s_typeOfXmlFormatCollectionWriterDelegate; } } private static Type s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get { if (s_typeOfXmlFormatClassReaderDelegate == null) s_typeOfXmlFormatClassReaderDelegate = typeof(XmlFormatClassReaderDelegate); return s_typeOfXmlFormatClassReaderDelegate; } } private static Type s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get { if (s_typeOfXmlFormatCollectionReaderDelegate == null) s_typeOfXmlFormatCollectionReaderDelegate = typeof(XmlFormatCollectionReaderDelegate); return s_typeOfXmlFormatCollectionReaderDelegate; } } private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get { if (s_typeOfXmlFormatGetOnlyCollectionReaderDelegate == null) s_typeOfXmlFormatGetOnlyCollectionReaderDelegate = typeof(XmlFormatGetOnlyCollectionReaderDelegate); return s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; } } private static Type s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get { if (s_typeOfKnownTypeAttribute == null) s_typeOfKnownTypeAttribute = typeof(KnownTypeAttribute); return s_typeOfKnownTypeAttribute; } } private static Type s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get { if (s_typeOfDataContractAttribute == null) s_typeOfDataContractAttribute = typeof(DataContractAttribute); return s_typeOfDataContractAttribute; } } private static Type s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get { if (s_typeOfDataMemberAttribute == null) s_typeOfDataMemberAttribute = typeof(DataMemberAttribute); return s_typeOfDataMemberAttribute; } } private static Type s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get { if (s_typeOfEnumMemberAttribute == null) s_typeOfEnumMemberAttribute = typeof(EnumMemberAttribute); return s_typeOfEnumMemberAttribute; } } private static Type s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get { if (s_typeOfCollectionDataContractAttribute == null) s_typeOfCollectionDataContractAttribute = typeof(CollectionDataContractAttribute); return s_typeOfCollectionDataContractAttribute; } } private static Type s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get { if (s_typeOfOptionalFieldAttribute == null) { s_typeOfOptionalFieldAttribute = typeof(OptionalFieldAttribute); } return s_typeOfOptionalFieldAttribute; } } private static Type s_typeOfObjectArray; internal static Type TypeOfObjectArray { get { if (s_typeOfObjectArray == null) s_typeOfObjectArray = typeof(object[]); return s_typeOfObjectArray; } } private static Type s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get { if (s_typeOfOnSerializingAttribute == null) s_typeOfOnSerializingAttribute = typeof(OnSerializingAttribute); return s_typeOfOnSerializingAttribute; } } private static Type s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get { if (s_typeOfOnSerializedAttribute == null) s_typeOfOnSerializedAttribute = typeof(OnSerializedAttribute); return s_typeOfOnSerializedAttribute; } } private static Type s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get { if (s_typeOfOnDeserializingAttribute == null) s_typeOfOnDeserializingAttribute = typeof(OnDeserializingAttribute); return s_typeOfOnDeserializingAttribute; } } private static Type s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get { if (s_typeOfOnDeserializedAttribute == null) s_typeOfOnDeserializedAttribute = typeof(OnDeserializedAttribute); return s_typeOfOnDeserializedAttribute; } } private static Type s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get { if (s_typeOfFlagsAttribute == null) s_typeOfFlagsAttribute = typeof(FlagsAttribute); return s_typeOfFlagsAttribute; } } private static Type s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get { if (s_typeOfIXmlSerializable == null) s_typeOfIXmlSerializable = typeof(IXmlSerializable); return s_typeOfIXmlSerializable; } } private static Type s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get { if (s_typeOfXmlSchemaProviderAttribute == null) s_typeOfXmlSchemaProviderAttribute = typeof(XmlSchemaProviderAttribute); return s_typeOfXmlSchemaProviderAttribute; } } private static Type s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get { if (s_typeOfXmlRootAttribute == null) s_typeOfXmlRootAttribute = typeof(XmlRootAttribute); return s_typeOfXmlRootAttribute; } } private static Type s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get { if (s_typeOfXmlQualifiedName == null) s_typeOfXmlQualifiedName = typeof(XmlQualifiedName); return s_typeOfXmlQualifiedName; } } private static Type s_typeOfXmlSchemaType; internal static Type TypeOfXmlSchemaType { get { if (s_typeOfXmlSchemaType == null) { s_typeOfXmlSchemaType = typeof(XmlSchemaType); } return s_typeOfXmlSchemaType; } } private static Type s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject)); private static Type s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject)); private static Type s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get { if (s_typeOfISerializableDataNode == null) s_typeOfISerializableDataNode = typeof(ISerializableDataNode); return s_typeOfISerializableDataNode; } } private static Type s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get { if (s_typeOfClassDataNode == null) s_typeOfClassDataNode = typeof(ClassDataNode); return s_typeOfClassDataNode; } } private static Type s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get { if (s_typeOfCollectionDataNode == null) s_typeOfCollectionDataNode = typeof(CollectionDataNode); return s_typeOfCollectionDataNode; } } private static Type s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode)); private static Type s_typeOfNullable; internal static Type TypeOfNullable { get { if (s_typeOfNullable == null) s_typeOfNullable = typeof(Nullable<>); return s_typeOfNullable; } } private static Type s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get { if (s_typeOfIDictionaryGeneric == null) s_typeOfIDictionaryGeneric = typeof(IDictionary<,>); return s_typeOfIDictionaryGeneric; } } private static Type s_typeOfIDictionary; internal static Type TypeOfIDictionary { get { if (s_typeOfIDictionary == null) s_typeOfIDictionary = typeof(IDictionary); return s_typeOfIDictionary; } } private static Type s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get { if (s_typeOfIListGeneric == null) s_typeOfIListGeneric = typeof(IList<>); return s_typeOfIListGeneric; } } private static Type s_typeOfIList; internal static Type TypeOfIList { get { if (s_typeOfIList == null) s_typeOfIList = typeof(IList); return s_typeOfIList; } } private static Type s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get { if (s_typeOfICollectionGeneric == null) s_typeOfICollectionGeneric = typeof(ICollection<>); return s_typeOfICollectionGeneric; } } private static Type s_typeOfICollection; internal static Type TypeOfICollection { get { if (s_typeOfICollection == null) s_typeOfICollection = typeof(ICollection); return s_typeOfICollection; } } private static Type s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get { if (s_typeOfIEnumerableGeneric == null) s_typeOfIEnumerableGeneric = typeof(IEnumerable<>); return s_typeOfIEnumerableGeneric; } } private static Type s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get { if (s_typeOfIEnumerable == null) s_typeOfIEnumerable = typeof(IEnumerable); return s_typeOfIEnumerable; } } private static Type s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get { if (s_typeOfIEnumeratorGeneric == null) s_typeOfIEnumeratorGeneric = typeof(IEnumerator<>); return s_typeOfIEnumeratorGeneric; } } private static Type s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get { if (s_typeOfIEnumerator == null) s_typeOfIEnumerator = typeof(IEnumerator); return s_typeOfIEnumerator; } } private static Type s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get { if (s_typeOfKeyValuePair == null) s_typeOfKeyValuePair = typeof(KeyValuePair<,>); return s_typeOfKeyValuePair; } } private static Type s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get { if (s_typeOfKeyValuePairAdapter == null) s_typeOfKeyValuePairAdapter = typeof(KeyValuePairAdapter<,>); return s_typeOfKeyValuePairAdapter; } } private static Type s_typeOfKeyValue; internal static Type TypeOfKeyValue { get { if (s_typeOfKeyValue == null) s_typeOfKeyValue = typeof(KeyValue<,>); return s_typeOfKeyValue; } } private static Type s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get { if (s_typeOfIDictionaryEnumerator == null) s_typeOfIDictionaryEnumerator = typeof(IDictionaryEnumerator); return s_typeOfIDictionaryEnumerator; } } private static Type s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get { if (s_typeOfDictionaryEnumerator == null) s_typeOfDictionaryEnumerator = typeof(CollectionDataContract.DictionaryEnumerator); return s_typeOfDictionaryEnumerator; } } private static Type s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get { if (s_typeOfGenericDictionaryEnumerator == null) s_typeOfGenericDictionaryEnumerator = typeof(CollectionDataContract.GenericDictionaryEnumerator<,>); return s_typeOfGenericDictionaryEnumerator; } } private static Type s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get { if (s_typeOfDictionaryGeneric == null) s_typeOfDictionaryGeneric = typeof(Dictionary<,>); return s_typeOfDictionaryGeneric; } } private static Type s_typeOfHashtable; internal static Type TypeOfHashtable { get { if (s_typeOfHashtable == null) s_typeOfHashtable = TypeOfDictionaryGeneric.MakeGenericType(TypeOfObject, TypeOfObject); return s_typeOfHashtable; } } private static Type s_typeOfXmlElement; internal static Type TypeOfXmlElement { get { if (s_typeOfXmlElement == null) s_typeOfXmlElement = typeof(XmlElement); return s_typeOfXmlElement; } } private static Type s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get { if (s_typeOfXmlNodeArray == null) s_typeOfXmlNodeArray = typeof(XmlNode[]); return s_typeOfXmlNodeArray; } } private static Type s_typeOfDBNull; internal static Type TypeOfDBNull { get { if (s_typeOfDBNull == null) s_typeOfDBNull = typeof(DBNull); return s_typeOfDBNull; } } private static Uri s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get { if (s_dataContractXsdBaseNamespaceUri == null) s_dataContractXsdBaseNamespaceUri = new Uri(DataContractXsdBaseNamespace); return s_dataContractXsdBaseNamespaceUri; } } #region Contract compliance for System.Type private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2) { if (seq1 == null || seq2 == null || seq1.Length != seq2.Length) return false; for (int i = 0; i < seq1.Length; i++) { if (!seq1[i].Equals(seq2[i]) && !seq1[i].IsAssignableFrom(seq2[i])) return false; } return true; } private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName) { if (methodBases == null || string.IsNullOrEmpty(methodName)) return null; var matchedMethods = methodBases.Where(method => method.Name.Equals(methodName)); matchedMethods = matchedMethods.Where(method => TypeSequenceEqual(method.GetParameters().Select(param => param.ParameterType).ToArray(), parameterTypes)); return matchedMethods.FirstOrDefault(); } internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { var constructorInfos = type.GetConstructors(bindingFlags); var constructorInfo = FilterMethodBases(constructorInfos.Cast<MethodBase>().ToArray(), parameterTypes, ".ctor"); return constructorInfo != null ? (ConstructorInfo)constructorInfo : null; } internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) { var methodInfos = type.GetMethods(bindingFlags); var methodInfo = FilterMethodBases(methodInfos.Cast<MethodBase>().ToArray(), parameterTypes, methodName); return methodInfo != null ? (MethodInfo)methodInfo : null; } #endregion private static Type s_typeOfScriptObject; internal static ClassDataContract CreateScriptObjectClassDataContract() { Debug.Assert(s_typeOfScriptObject != null); return new ClassDataContract(s_typeOfScriptObject); } internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) { return s_typeOfScriptObject != null && s_typeOfScriptObject.IsAssignableFrom(type); } public const bool DefaultIsRequired = false; public const bool DefaultEmitDefaultValue = true; public const int DefaultOrder = 0; public const bool DefaultIsReference = false; // The value string.Empty aids comparisons (can do simple length checks // instead of string comparison method calls in IL.) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; public const string SerPrefix = "z"; public const string SerPrefixForSchema = "ser"; public const string ElementPrefix = "q"; public const string DataContractXsdBaseNamespace = "http://schemas.datacontract.org/2004/07/"; public const string DataContractXmlNamespace = DataContractXsdBaseNamespace + "System.Xml"; public const string SchemaInstanceNamespace = "http://www.w3.org/2001/XMLSchema-instance"; public const string SchemaNamespace = "http://www.w3.org/2001/XMLSchema"; public const string XsiNilLocalName = "nil"; public const string XsiTypeLocalName = "type"; public const string TnsPrefix = "tns"; public const string OccursUnbounded = "unbounded"; public const string AnyTypeLocalName = "anyType"; public const string StringLocalName = "string"; public const string IntLocalName = "int"; public const string True = "true"; public const string False = "false"; public const string ArrayPrefix = "ArrayOf"; public const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; public const string XmlnsPrefix = "xmlns"; public const string SchemaLocalName = "schema"; public const string CollectionsNamespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays"; public const string DefaultClrNamespace = "GeneratedNamespace"; public const string DefaultTypeName = "GeneratedType"; public const string DefaultGeneratedMember = "GeneratedMember"; public const string DefaultFieldSuffix = "Field"; public const string DefaultPropertySuffix = "Property"; public const string DefaultMemberSuffix = "Member"; public const string NameProperty = "Name"; public const string NamespaceProperty = "Namespace"; public const string OrderProperty = "Order"; public const string IsReferenceProperty = "IsReference"; public const string IsRequiredProperty = "IsRequired"; public const string EmitDefaultValueProperty = "EmitDefaultValue"; public const string ClrNamespaceProperty = "ClrNamespace"; public const string ItemNameProperty = "ItemName"; public const string KeyNameProperty = "KeyName"; public const string ValueNameProperty = "ValueName"; public const string SerializationInfoPropertyName = "SerializationInfo"; public const string SerializationInfoFieldName = "info"; public const string NodeArrayPropertyName = "Nodes"; public const string NodeArrayFieldName = "nodesField"; public const string ExportSchemaMethod = "ExportSchema"; public const string IsAnyProperty = "IsAny"; public const string ContextFieldName = "context"; public const string GetObjectDataMethodName = "GetObjectData"; public const string GetEnumeratorMethodName = "GetEnumerator"; public const string MoveNextMethodName = "MoveNext"; public const string AddValueMethodName = "AddValue"; public const string CurrentPropertyName = "Current"; public const string ValueProperty = "Value"; public const string EnumeratorFieldName = "enumerator"; public const string SerializationEntryFieldName = "entry"; public const string ExtensionDataSetMethod = "set_ExtensionData"; public const string ExtensionDataSetExplicitMethod = "System.Runtime.Serialization.IExtensibleDataObject.set_ExtensionData"; public const string ExtensionDataObjectPropertyName = "ExtensionData"; public const string ExtensionDataObjectFieldName = "extensionDataField"; public const string AddMethodName = "Add"; public const string GetCurrentMethodName = "get_Current"; // NOTE: These values are used in schema below. If you modify any value, please make the same change in the schema. public const string SerializationNamespace = "http://schemas.microsoft.com/2003/10/Serialization/"; public const string ClrTypeLocalName = "Type"; public const string ClrAssemblyLocalName = "Assembly"; public const string IsValueTypeLocalName = "IsValueType"; public const string EnumerationValueLocalName = "EnumerationValue"; public const string SurrogateDataLocalName = "Surrogate"; public const string GenericTypeLocalName = "GenericType"; public const string GenericParameterLocalName = "GenericParameter"; public const string GenericNameAttribute = "Name"; public const string GenericNamespaceAttribute = "Namespace"; public const string GenericParameterNestedLevelAttribute = "NestedLevel"; public const string IsDictionaryLocalName = "IsDictionary"; public const string ActualTypeLocalName = "ActualType"; public const string ActualTypeNameAttribute = "Name"; public const string ActualTypeNamespaceAttribute = "Namespace"; public const string DefaultValueLocalName = "DefaultValue"; public const string EmitDefaultValueAttribute = "EmitDefaultValue"; public const string IdLocalName = "Id"; public const string RefLocalName = "Ref"; public const string ArraySizeLocalName = "Size"; public const string KeyLocalName = "Key"; public const string ValueLocalName = "Value"; public const string MscorlibAssemblyName = "0"; public const string ParseMethodName = "Parse"; public const string SafeSerializationManagerName = "SafeSerializationManager"; public const string SafeSerializationManagerNamespace = "http://schemas.datacontract.org/2004/07/System.Runtime.Serialization"; public const string ISerializableFactoryTypeLocalName = "FactoryType"; public const string SerializationSchema = @"<?xml version='1.0' encoding='utf-8'?> <xs:schema elementFormDefault='qualified' attributeFormDefault='qualified' xmlns:tns='http://schemas.microsoft.com/2003/10/Serialization/' targetNamespace='http://schemas.microsoft.com/2003/10/Serialization/' xmlns:xs='http://www.w3.org/2001/XMLSchema'> <xs:element name='anyType' nillable='true' type='xs:anyType' /> <xs:element name='anyURI' nillable='true' type='xs:anyURI' /> <xs:element name='base64Binary' nillable='true' type='xs:base64Binary' /> <xs:element name='boolean' nillable='true' type='xs:boolean' /> <xs:element name='byte' nillable='true' type='xs:byte' /> <xs:element name='dateTime' nillable='true' type='xs:dateTime' /> <xs:element name='decimal' nillable='true' type='xs:decimal' /> <xs:element name='double' nillable='true' type='xs:double' /> <xs:element name='float' nillable='true' type='xs:float' /> <xs:element name='int' nillable='true' type='xs:int' /> <xs:element name='long' nillable='true' type='xs:long' /> <xs:element name='QName' nillable='true' type='xs:QName' /> <xs:element name='short' nillable='true' type='xs:short' /> <xs:element name='string' nillable='true' type='xs:string' /> <xs:element name='unsignedByte' nillable='true' type='xs:unsignedByte' /> <xs:element name='unsignedInt' nillable='true' type='xs:unsignedInt' /> <xs:element name='unsignedLong' nillable='true' type='xs:unsignedLong' /> <xs:element name='unsignedShort' nillable='true' type='xs:unsignedShort' /> <xs:element name='char' nillable='true' type='tns:char' /> <xs:simpleType name='char'> <xs:restriction base='xs:int'/> </xs:simpleType> <xs:element name='duration' nillable='true' type='tns:duration' /> <xs:simpleType name='duration'> <xs:restriction base='xs:duration'> <xs:pattern value='\-?P(\d*D)?(T(\d*H)?(\d*M)?(\d*(\.\d*)?S)?)?' /> <xs:minInclusive value='-P10675199DT2H48M5.4775808S' /> <xs:maxInclusive value='P10675199DT2H48M5.4775807S' /> </xs:restriction> </xs:simpleType> <xs:element name='guid' nillable='true' type='tns:guid' /> <xs:simpleType name='guid'> <xs:restriction base='xs:string'> <xs:pattern value='[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}' /> </xs:restriction> </xs:simpleType> <xs:attribute name='FactoryType' type='xs:QName' /> <xs:attribute name='Id' type='xs:ID' /> <xs:attribute name='Ref' type='xs:IDREF' /> </xs:schema> "; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl { using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Unmanaged; using UU = Apache.Ignite.Core.Impl.Unmanaged.UnmanagedUtils; /// <summary> /// Native interface manager. /// </summary> public static unsafe class IgniteManager { /** Java Command line argument: Xms. Case sensitive. */ private const string CmdJvmMinMemJava = "-Xms"; /** Java Command line argument: Xmx. Case sensitive. */ private const string CmdJvmMaxMemJava = "-Xmx"; /** Monitor for DLL load synchronization. */ private static readonly object SyncRoot = new object(); /** First created context. */ private static void* _ctx; /** Configuration used on JVM start. */ private static JvmConfiguration _jvmCfg; /** Memory manager. */ private static PlatformMemoryManager _mem; /// <summary> /// Create JVM. /// </summary> /// <param name="cfg">Configuration.</param> /// <param name="cbs">Callbacks.</param> /// <returns>Context.</returns> internal static void CreateJvmContext(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { lock (SyncRoot) { // 1. Warn about possible configuration inconsistency. JvmConfiguration jvmCfg = JvmConfig(cfg); if (!cfg.SuppressWarnings && _jvmCfg != null) { if (!_jvmCfg.Equals(jvmCfg)) { Console.WriteLine("Attempting to start Ignite node with different Java " + "configuration; current Java configuration will be ignored (consider " + "starting node in separate process) [oldConfig=" + _jvmCfg + ", newConfig=" + jvmCfg + ']'); } } // 2. Create unmanaged pointer. void* ctx = CreateJvm(cfg, cbs); cbs.SetContext(ctx); // 3. If this is the first JVM created, preserve it. if (_ctx == null) { _ctx = ctx; _jvmCfg = jvmCfg; _mem = new PlatformMemoryManager(1024); } } } /// <summary> /// Memory manager attached to currently running JVM. /// </summary> internal static PlatformMemoryManager Memory { get { return _mem; } } /// <summary> /// Blocks until JVM stops. /// </summary> public static void DestroyJvm() { lock (SyncRoot) { if (_ctx != null) { UU.DestroyJvm(_ctx); _ctx = null; } } } /// <summary> /// Create JVM. /// </summary> /// <returns>JVM.</returns> private static void* CreateJvm(IgniteConfiguration cfg, UnmanagedCallbacks cbs) { var ggHome = IgniteHome.Resolve(cfg); var cp = Classpath.CreateClasspath(ggHome, cfg, false); var jvmOpts = GetMergedJvmOptions(cfg); var hasGgHome = !string.IsNullOrWhiteSpace(ggHome); var opts = new sbyte*[1 + jvmOpts.Count + (hasGgHome ? 1 : 0)]; int idx = 0; opts[idx++] = IgniteUtils.StringToUtf8Unmanaged(cp); if (hasGgHome) opts[idx++] = IgniteUtils.StringToUtf8Unmanaged("-DIGNITE_HOME=" + ggHome); foreach (string cfgOpt in jvmOpts) opts[idx++] = IgniteUtils.StringToUtf8Unmanaged(cfgOpt); try { IntPtr mem = Marshal.AllocHGlobal(opts.Length * 8); fixed (sbyte** opts0 = opts) { PlatformMemoryUtils.CopyMemory(opts0, mem.ToPointer(), opts.Length * 8); } try { return UU.CreateContext(mem.ToPointer(), opts.Length, cbs.CallbacksPointer); } finally { Marshal.FreeHGlobal(mem); } } finally { foreach (sbyte* opt in opts) Marshal.FreeHGlobal((IntPtr)opt); } } /// <summary> /// Gets JvmOptions collection merged with individual properties (Min/Max mem, etc) according to priority. /// </summary> private static IList<string> GetMergedJvmOptions(IgniteConfiguration cfg) { var jvmOpts = cfg.JvmOptions == null ? new List<string>() : cfg.JvmOptions.ToList(); // JvmInitialMemoryMB / JvmMaxMemoryMB have lower priority than CMD_JVM_OPT if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMinMemJava, StringComparison.OrdinalIgnoreCase))) jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMinMemJava, cfg.JvmInitialMemoryMb)); if (!jvmOpts.Any(opt => opt.StartsWith(CmdJvmMaxMemJava, StringComparison.OrdinalIgnoreCase))) jvmOpts.Add(string.Format(CultureInfo.InvariantCulture, "{0}{1}m", CmdJvmMaxMemJava, cfg.JvmMaxMemoryMb)); return jvmOpts; } /// <summary> /// Create JVM configuration value object. /// </summary> /// <param name="cfg">Configuration.</param> /// <returns>JVM configuration.</returns> private static JvmConfiguration JvmConfig(IgniteConfiguration cfg) { return new JvmConfiguration { Home = cfg.IgniteHome, Dll = cfg.JvmDllPath, Classpath = cfg.JvmClasspath, Options = cfg.JvmOptions }; } /// <summary> /// JVM configuration. /// </summary> private class JvmConfiguration { /// <summary> /// Gets or sets the home. /// </summary> public string Home { get; set; } /// <summary> /// Gets or sets the DLL. /// </summary> public string Dll { get; set; } /// <summary> /// Gets or sets the cp. /// </summary> public string Classpath { get; set; } /// <summary> /// Gets or sets the options. /// </summary> public ICollection<string> Options { get; set; } /** <inheritDoc /> */ public override int GetHashCode() { return 0; } /** <inheritDoc /> */ [SuppressMessage("ReSharper", "FunctionComplexityOverflow")] public override bool Equals(object obj) { JvmConfiguration other = obj as JvmConfiguration; if (other == null) return false; if (!string.Equals(Home, other.Home, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Classpath, other.Classpath, StringComparison.OrdinalIgnoreCase)) return false; if (!string.Equals(Dll, other.Dll, StringComparison.OrdinalIgnoreCase)) return false; return (Options == null && other.Options == null) || (Options != null && other.Options != null && Options.Count == other.Options.Count && !Options.Except(other.Options).Any()); } /** <inheritDoc /> */ public override string ToString() { var sb = new StringBuilder("[IgniteHome=" + Home + ", JvmDllPath=" + Dll); if (Options != null && Options.Count > 0) { sb.Append(", JvmOptions=["); bool first = true; foreach (string opt in Options) { if (first) first = false; else sb.Append(", "); sb.Append(opt); } sb.Append(']'); } sb.Append(", Classpath=" + Classpath + ']'); return sb.ToString(); } } } }
using System; using System.Collections.Generic; namespace FlatRedBall.Input { /// <summary> /// Provides a common interface for input devices which can return values on the X and Y axis, such as an analog stick. /// </summary> public interface I2DInput { /// <summary> /// The X value of the input device, typically between 0 and 1. /// </summary> /// <example> /// // Assuming inputDevice is an I2DInput instance /// this.XVelocity = inputDevice.X * this.MaxSpeed; /// </example> float X { get; } /// <summary> /// The Y value of the input device, typically between 0 and 1. /// </summary> /// <example> /// // Assuming inputDevice is an I2DInput instance /// this.YVelocity = inputDevice.Y * this.MaxSpeed; /// </example> float Y { get; } /// <summary> /// The rate of change of the input device on the X axis. This measures how fast the user is changing the device. For example, /// it can be used to tell how fast the user's thumb is moving on an analog stick. /// </summary> float XVelocity { get; } /// <summary> /// The rate of change of the input device on the Y axis. This measures how fast the user is changing the device. For example, /// it can be used to tell how fast the user's thumb is moving on an analog stick. /// </summary> float YVelocity { get; } /// <summary> /// The distance from (0,0) of the input device. It can be used to detect if any input is being applied on this input device. /// </summary> float Magnitude { get; } } /// <summary> /// Implementation of I2DInput which always returns 0s. Can be used for classes /// requiring an I2DInput implementation /// (like IInputDevice) which should always return 0. /// </summary> public class Zero2DInput : I2DInput { public static Zero2DInput Instance = new Zero2DInput(); public float X => 0; public float Y => 0; public float XVelocity => 0; public float YVelocity => 0; public float Magnitude => 0; } public class DelegateBased2DInput : I2DInput { Func<float> x; Func<float> y; Func<float> xVelocity; Func<float> yVelocity; public float X { get { return this.x(); } } public float Y { get { return this.y(); } } public float XVelocity { get { return this.xVelocity(); } } public float YVelocity { get { return this.yVelocity(); } } public float Magnitude { get { float xValue = x(); float yValue = y(); float toReturn = (float)System.Math.Sqrt(xValue * xValue + yValue * yValue); return toReturn; } } float Zero() => 0; public DelegateBased2DInput(Func<float> x, Func<float> y) { this.x = x; this.y = y; this.xVelocity = Zero; this.yVelocity = Zero; } public DelegateBased2DInput(Func<float> x, Func<float> y, Func<float> xVelocity, Func<float> yVelocity) { this.x = x; this.y = y; this.xVelocity = xVelocity; this.yVelocity = yVelocity; } } public static class I2DInputExtensions { public static Multiple2DInputs Or(this I2DInput thisInput, I2DInput input) { Multiple2DInputs toReturn; if(thisInput is Multiple2DInputs) { toReturn = (Multiple2DInputs)thisInput; } else { toReturn = new Multiple2DInputs(); toReturn.Inputs.Add(thisInput); } toReturn.Inputs.Add(input); return toReturn; } /// <summary> /// Returns the angle in radians of the input object, where 0 is to the right, rotating counterclockwise. /// Returns null if the X and Y values are 0 (meaning the input device is centered) /// </summary> /// <param name="instance">The I2DInput instance</param> /// <returns>The angle, or null if X and Y are 0</returns> public static float? GetAngle(this I2DInput instance) { if(instance.X == 0 && instance.Y == 0) { return null; } else { return (float)System.Math.Atan2(instance.Y, instance.X); } } /// <summary> /// Creates a new 1DInput that returns the horizontal values from the argument /// I2DInput. /// </summary> /// <param name="instance">The instance to use for the horizontal (X) values</param> /// <returns>A new I1DInput which reflects the 2D horizontal values.</returns> public static I1DInput CreateHorizontal(this I2DInput instance) { return new DelegateBased1DInput( () => instance.X, () => instance.XVelocity); } /// <summary> /// Creates a new 1DInput that returns the vertical value from the argument /// I2DInput. /// </summary> /// <param name="instance">The instance to use for the vertical (Y) values</param> /// <returns>A new I1DInput which reflects the 2D vertical values.</returns> public static I1DInput CreateVertical(this I2DInput instance) { return new DelegateBased1DInput( () => instance.Y, () => instance.YVelocity); } } /// <summary> /// Provides a single I2DInput implementation which can read from multiple I2DInputs at once. /// </summary> /// <remarks> /// This is useful for games which want to read from multiple devices, such as letting all controllers /// control one character, or letting keyboard and gamepad control a character at the same time. /// </remarks> public class Multiple2DInputs : I2DInput { public float X { get { float toReturn = 0; foreach(var input in Inputs) { if(System.Math.Abs(input.X) > (System.Math.Abs(toReturn))) { toReturn = input.X; } } return toReturn; } } public float Y { get { float toReturn = 0; foreach (var input in Inputs) { if (System.Math.Abs(input.Y) > (System.Math.Abs(toReturn))) { toReturn = input.Y; } } return toReturn; } } public float XVelocity { get { float toReturn = 0; foreach (var input in Inputs) { if (System.Math.Abs(input.XVelocity) > (System.Math.Abs(toReturn))) { toReturn = input.XVelocity; } } return toReturn; } } public float YVelocity { get { float toReturn = 0; foreach (var input in Inputs) { if (System.Math.Abs(input.YVelocity) > (System.Math.Abs(toReturn))) { toReturn = input.YVelocity; } } return toReturn; } } public float Magnitude { get { float toReturn = 0; foreach (var input in Inputs) { if (System.Math.Abs(input.Magnitude) > (System.Math.Abs(toReturn))) { toReturn = input.Magnitude; } } return toReturn; } } /// <summary> /// Contains the list of inputs to read from. Any number of inputs can be added to this using the Add method. /// </summary> /// <example> /// // Assuming that keyboard2DInput and gamepad2DInput exist: /// var multipleInputs = new Multiple2DInputs(); /// multipleInputs.Inputs.Add(keyboard2DInput); /// multipleInputs.Inputs.Add(gamepad2DInput); /// </example> public List<I2DInput> Inputs { get; private set; } public Multiple2DInputs() { Inputs = new List<I2DInput>(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Xunit; #pragma warning disable 618 // obsolete types namespace System.Collections.Tests { public static class HashtableTests { [Fact] public static void Ctor_Empty() { var hash = new ComparableHashtable(); VerifyHashtable(hash, null, null); } [Fact] public static void Ctor_HashCodeProvider_Comparer() { var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); Assert.Same(CaseInsensitiveHashCodeProvider.DefaultInvariant, hash.HashCodeProvider); Assert.Same(StringComparer.OrdinalIgnoreCase, hash.Comparer); } [Theory] [InlineData(false, false)] [InlineData(false, true)] [InlineData(true, false)] [InlineData(true, true)] public static void Ctor_HashCodeProvider_Comparer_NullInputs(bool nullProvider, bool nullComparer) { var hash = new ComparableHashtable( nullProvider ? null : CaseInsensitiveHashCodeProvider.DefaultInvariant, nullComparer ? null : StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); } [Fact] public static void Ctor_IDictionary() { // No exception var hash1 = new ComparableHashtable(new Hashtable()); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable()))))); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2); VerifyHashtable(hash1, hash2, null); } [Fact] public static void Ctor_IDictionary_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null)); // Dictionary is null } [Fact] public static void Ctor_IDictionary_HashCodeProvider_Comparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable())))), CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash1, hash2, hash1.EqualityComparer); } [Fact] public static void Ctor_IDictionary_HashCodeProvider_Comparer_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, CaseInsensitiveHashCodeProvider.Default, StringComparer.OrdinalIgnoreCase)); // Dictionary is null } [Fact] public static void Ctor_IEqualityComparer() { // Null comparer var hash = new ComparableHashtable((IEqualityComparer)null); VerifyHashtable(hash, null, null); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(comparer); VerifyHashtable(hash, null, comparer); }); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] public static void Ctor_Int(int capacity) { var hash = new ComparableHashtable(capacity); VerifyHashtable(hash, null, null); } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] public static void Ctor_Int_HashCodeProvider_Comparer(int capacity) { var hash = new ComparableHashtable(capacity, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); } [Fact] public static void Ctor_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue)); // Capacity / load factor > int.MaxValue } [Fact] public static void Ctor_IDictionary_Int() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash1, hash2, hash1.EqualityComparer); } [Fact] public static void Ctor_IDictionary_Int_Invalid() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f)); // Dictionary is null AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity)); // Load factor is infinity } [Fact] public static void Ctor_IDictionary_Int_HashCodeProvider_Comparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), 1f), 1f), 1f), 1f), 1f); Assert.Equal(0, hash1.Count); Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f); VerifyHashtable(hash1, hash2, null); } [Fact] public static void Ctor_IDictionary_IEqualityComparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), null); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(new Hashtable(), null), null), null), null), null); Assert.Equal(0, hash1.Count); // Null comparer Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, null); VerifyHashtable(hash1, hash2, null); // Custom comparer hash2 = Helpers.CreateIntHashtable(100); Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash1 = new ComparableHashtable(hash2, comparer); VerifyHashtable(hash1, hash2, comparer); }); } [Fact] public static void Ctor_IDictionary_IEqualityComparer_NullDictionary_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable((IDictionary)null, null)); // Dictionary is null } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public static void Ctor_Int_Int(int capacity, float loadFactor) { var hash = new ComparableHashtable(capacity, loadFactor); VerifyHashtable(hash, null, null); } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public static void Ctor_Int_Int_HashCodeProvider_Comparer(int capacity, float loadFactor) { var hash = new ComparableHashtable(capacity, loadFactor, CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); VerifyHashtable(hash, null, hash.EqualityComparer); } [Fact] public static void Ctor_Int_Int_GenerateNewPrime() { // The ctor for Hashtable performs the following calculation: // rawSize = capacity / (loadFactor * 0.72) // If rawSize is > 3, then it calls HashHelpers.GetPrime(rawSize) to generate a prime. // Then, if the rawSize > 7,199,369 (the largest number in a list of known primes), we have to generate a prime programatically // This test makes sure this works. int capacity = 8000000; float loadFactor = 0.1f / 0.72f; try { var hash = new ComparableHashtable(capacity, loadFactor); } catch (OutOfMemoryException) { // On memory constrained devices, we can get an OutOfMemoryException, which we can safely ignore. } } [Fact] public static void Ctor_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f)); // Capacity / load factor > int.MaxValue AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity)); // Load factor is infinity } [Theory] [InlineData(0)] [InlineData(10)] [InlineData(100)] [InlineData(1000)] public static void Ctor_Int_IEqualityComparer(int capacity) { // Null comparer var hash = new ComparableHashtable(capacity, null); VerifyHashtable(hash, null, null); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(capacity, comparer); VerifyHashtable(hash, null, comparer); }); } [Fact] public static void Ctor_Int_IEqualityComparer_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, null)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, null)); // Capacity / load factor > int.MaxValue } [Fact] public static void Ctor_IDictionary_Int_IEqualityComparer() { // No exception var hash1 = new ComparableHashtable(new Hashtable(), 1f, null); Assert.Equal(0, hash1.Count); hash1 = new ComparableHashtable(new Hashtable(new Hashtable( new Hashtable(new Hashtable(new Hashtable(), 1f, null), 1f, null), 1f, null), 1f, null), 1f, null); Assert.Equal(0, hash1.Count); // Null comparer Hashtable hash2 = Helpers.CreateIntHashtable(100); hash1 = new ComparableHashtable(hash2, 1f, null); VerifyHashtable(hash1, hash2, null); hash2 = Helpers.CreateIntHashtable(100); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash1 = new ComparableHashtable(hash2, 1f, comparer); VerifyHashtable(hash1, hash2, comparer); }); } [Fact] public static void Ctor_IDictionary_LoadFactor_IEqualityComparer_Invalid() { AssertExtensions.Throws<ArgumentNullException>("d", () => new Hashtable(null, 1f, null)); // Dictionary is null AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 0.09f, null)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), 1.01f, null)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NaN, null)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.PositiveInfinity, null)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(new Hashtable(), float.NegativeInfinity, null)); // Load factor is infinity } [Theory] [InlineData(0, 0.1)] [InlineData(10, 0.2)] [InlineData(100, 0.3)] [InlineData(1000, 1)] public static void Ctor_Int_Int_IEqualityComparer(int capacity, float loadFactor) { // Null comparer var hash = new ComparableHashtable(capacity, loadFactor, null); VerifyHashtable(hash, null, null); Assert.Null(hash.EqualityComparer); // Custom comparer Helpers.PerformActionOnCustomCulture(() => { IEqualityComparer comparer = StringComparer.CurrentCulture; hash = new ComparableHashtable(capacity, loadFactor, comparer); VerifyHashtable(hash, null, comparer); }); } [Fact] public static void Ctor_Capacity_LoadFactor_IEqualityComparer_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new Hashtable(-1, 1f, null)); // Capacity < 0 AssertExtensions.Throws<ArgumentException>("capacity", null, () => new Hashtable(int.MaxValue, 0.1f, null)); // Capacity / load factor > int.MaxValue AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 0.09f, null)); // Load factor < 0.1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, 1.01f, null)); // Load factor > 1f AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NaN, null)); // Load factor is NaN AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.PositiveInfinity, null)); // Load factor is infinity AssertExtensions.Throws<ArgumentOutOfRangeException>("loadFactor", () => new Hashtable(100, float.NegativeInfinity, null)); // Load factor is infinity } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void DebuggerAttribute() { DebuggerAttributes.ValidateDebuggerDisplayReferences(new Hashtable()); var hash = new Hashtable() { { "a", 1 }, { "b", 2 } }; DebuggerAttributes.ValidateDebuggerTypeProxyProperties(hash); DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), Hashtable.Synchronized(hash)); bool threwNull = false; try { DebuggerAttributes.ValidateDebuggerTypeProxyProperties(typeof(Hashtable), null); } catch (TargetInvocationException ex) { threwNull = ex.InnerException is ArgumentNullException; } Assert.True(threwNull); } [Fact] public static void Add_ReferenceType() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { // Value is a reference var foo = new Foo(); hash2.Add("Key", foo); Assert.Equal("Hello World", ((Foo)hash2["Key"]).StringValue); // Changing original object should change the object stored in the Hashtable foo.StringValue = "Goodbye"; Assert.Equal("Goodbye", ((Foo)hash2["Key"]).StringValue); }); } [Fact] public static void Add_ClearRepeatedly() { const int Iterations = 2; const int Count = 2; var hash = new Hashtable(); for (int i = 0; i < Iterations; i++) { for (int j = 0; j < Count; j++) { string key = "Key: i=" + i + ", j=" + j; string value = "Value: i=" + i + ", j=" + j; hash.Add(key, value); } Assert.Equal(Count, hash.Count); hash.Clear(); } } [Fact] [OuterLoop] public static void AddRemove_LargeAmountNumbers() { // Generate a random 100,000 array of ints as test data var inputData = new int[100000]; var random = new Random(341553); for (int i = 0; i < inputData.Length; i++) { inputData[i] = random.Next(7500000, int.MaxValue); } var hash = new Hashtable(); int count = 0; foreach (long number in inputData) { hash.Add(number, count++); } count = 0; foreach (long number in inputData) { Assert.Equal(hash[number], count); Assert.True(hash.ContainsKey(number)); count++; } foreach (long number in inputData) { hash.Remove(number); } Assert.Equal(0, hash.Count); } [Fact] public static void DuplicatedKeysWithInitialCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var hash = new Hashtable(200); const int Iterations = 1600; for (int i = 0; i < Iterations; i += 2) { hash.Add(new BadHashCode(i), i.ToString()); hash.Add(new BadHashCode(i + 1), (i + 1).ToString()); hash.Remove(new BadHashCode(i)); hash.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < Iterations; i++) { hash.Add(i.ToString(), i); } for (int i = 0; i < Iterations; i++) { Assert.Equal(i, hash[i.ToString()]); } } [Fact] public static void DuplicatedKeysWithDefaultCapacity() { // Make rehash get called because to many items with duplicated keys have been added to the hashtable var hash = new Hashtable(); const int Iterations = 1600; for (int i = 0; i < Iterations; i += 2) { hash.Add(new BadHashCode(i), i.ToString()); hash.Add(new BadHashCode(i + 1), (i + 1).ToString()); hash.Remove(new BadHashCode(i)); hash.Remove(new BadHashCode(i + 1)); } for (int i = 0; i < Iterations; i++) { hash.Add(i.ToString(), i); } for (int i = 0; i < Iterations; i++) { Assert.Equal(i, hash[i.ToString()]); } } [Theory] [InlineData(0)] [InlineData(100)] public static void Clone(int count) { Hashtable hash1 = Helpers.CreateStringHashtable(count); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { Hashtable clone = (Hashtable)hash2.Clone(); Assert.Equal(hash2.Count, clone.Count); Assert.Equal(hash2.IsSynchronized, clone.IsSynchronized); Assert.Equal(hash2.IsFixedSize, clone.IsFixedSize); Assert.Equal(hash2.IsReadOnly, clone.IsReadOnly); for (int i = 0; i < clone.Count; i++) { string key = "Key_" + i; string value = "Value_" + i; Assert.True(clone.ContainsKey(key)); Assert.True(clone.ContainsValue(value)); Assert.Equal(value, clone[key]); } }); } [Fact] public static void Clone_IsShallowCopy() { var hash = new Hashtable(); for (int i = 0; i < 10; i++) { hash.Add(i, new Foo()); } Hashtable clone = (Hashtable)hash.Clone(); for (int i = 0; i < clone.Count; i++) { Assert.Equal("Hello World", ((Foo)clone[i]).StringValue); Assert.Same(hash[i], clone[i]); } // Change object in original hashtable ((Foo)hash[1]).StringValue = "Goodbye"; Assert.Equal("Goodbye", ((Foo)clone[1]).StringValue); // Removing an object from the original hashtable doesn't change the clone hash.Remove(0); Assert.True(clone.Contains(0)); } [Fact] public static void Clone_HashtableCastedToInterfaces() { // Try to cast the returned object from Clone() to different types Hashtable hash = Helpers.CreateIntHashtable(100); ICollection collection = (ICollection)hash.Clone(); Assert.Equal(hash.Count, collection.Count); IDictionary dictionary = (IDictionary)hash.Clone(); Assert.Equal(hash.Count, dictionary.Count); } [Fact] public static void ContainsKey() { Hashtable hash1 = Helpers.CreateStringHashtable(100); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { for (int i = 0; i < hash2.Count; i++) { string key = "Key_" + i; Assert.True(hash2.ContainsKey(key)); Assert.True(hash2.Contains(key)); } Assert.False(hash2.ContainsKey("Non Existent Key")); Assert.False(hash2.Contains("Non Existent Key")); Assert.False(hash2.ContainsKey(101)); Assert.False(hash2.Contains("Non Existent Key")); string removedKey = "Key_1"; hash2.Remove(removedKey); Assert.False(hash2.ContainsKey(removedKey)); Assert.False(hash2.Contains(removedKey)); }); } [Fact] public static void ContainsKey_EqualObjects() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { var foo1 = new Foo() { StringValue = "Goodbye" }; var foo2 = new Foo() { StringValue = "Goodbye" }; hash2.Add(foo1, 101); Assert.True(hash2.ContainsKey(foo2)); Assert.True(hash2.Contains(foo2)); int i1 = 0x10; int i2 = 0x100; long l1 = (((long)i1) << 32) + i2; // Create two longs with same hashcode long l2 = (((long)i2) << 32) + i1; hash2.Add(l1, 101); hash2.Add(l2, 101); // This will cause collision bit of the first entry to be set Assert.True(hash2.ContainsKey(l1)); Assert.True(hash2.Contains(l1)); hash2.Remove(l1); // Remove the first item Assert.False(hash2.ContainsKey(l1)); Assert.False(hash2.Contains(l1)); Assert.True(hash2.ContainsKey(l2)); Assert.True(hash2.Contains(l2)); }); } [Fact] public static void ContainsKey_NullKey_ThrowsArgumentNullException() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.ContainsKey(null)); // Key is null AssertExtensions.Throws<ArgumentNullException>("key", () => hash2.Contains(null)); // Key is null }); } [Fact] public static void ContainsValue() { Hashtable hash1 = Helpers.CreateStringHashtable(100); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { for (int i = 0; i < hash2.Count; i++) { string value = "Value_" + i; Assert.True(hash2.ContainsValue(value)); } Assert.False(hash2.ContainsValue("Non Existent Value")); Assert.False(hash2.ContainsValue(101)); Assert.False(hash2.ContainsValue(null)); hash2.Add("Key_101", null); Assert.True(hash2.ContainsValue(null)); string removedKey = "Key_1"; string removedValue = "Value_1"; hash2.Remove(removedKey); Assert.False(hash2.ContainsValue(removedValue)); }); } [Fact] public static void ContainsValue_EqualObjects() { var hash1 = new Hashtable(); Helpers.PerformActionOnAllHashtableWrappers(hash1, hash2 => { var foo1 = new Foo() { StringValue = "Goodbye" }; var foo2 = new Foo() { StringValue = "Goodbye" }; hash2.Add(101, foo1); Assert.True(hash2.ContainsValue(foo2)); }); } [Fact] public static void Keys_ModifyingHashtable_ModifiesCollection() { Hashtable hash = Helpers.CreateStringHashtable(100); ICollection keys = hash.Keys; // Removing a key from the hashtable should update the Keys ICollection. // This means that the Keys ICollection no longer contains the key. hash.Remove("Key_0"); IEnumerator enumerator = keys.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotEqual("Key_0", enumerator.Current); } } [Fact] public static void Remove_SameHashcode() { // We want to add and delete items (with the same hashcode) to the hashtable in such a way that the hashtable // does not expand but have to tread through collision bit set positions to insert the new elements. We do this // by creating a default hashtable of size 11 (with the default load factor of 0.72), this should mean that // the hashtable does not expand as long as we have at most 7 elements at any given time? var hash = new Hashtable(); var arrList = new ArrayList(); for (int i = 0; i < 7; i++) { var hashConfuse = new BadHashCode(i); arrList.Add(hashConfuse); hash.Add(hashConfuse, i); } var rand = new Random(-55); int iCount = 7; for (int i = 0; i < 100; i++) { for (int j = 0; j < 7; j++) { Assert.Equal(hash[arrList[j]], ((BadHashCode)arrList[j]).Value); } // Delete 3 elements from the hashtable for (int j = 0; j < 3; j++) { int iElement = rand.Next(6); hash.Remove(arrList[iElement]); Assert.False(hash.ContainsValue(null)); arrList.RemoveAt(iElement); int testInt = iCount++; var hashConfuse = new BadHashCode(testInt); arrList.Add(hashConfuse); hash.Add(hashConfuse, testInt); } } } [Fact] public static void SynchronizedProperties() { // Ensure Synchronized correctly reflects a wrapped hashtable var hash1 = Helpers.CreateStringHashtable(100); var hash2 = Hashtable.Synchronized(hash1); Assert.Equal(hash1.Count, hash2.Count); Assert.Equal(hash1.IsReadOnly, hash2.IsReadOnly); Assert.Equal(hash1.IsFixedSize, hash2.IsFixedSize); Assert.True(hash2.IsSynchronized); Assert.Equal(hash1.SyncRoot, hash2.SyncRoot); for (int i = 0; i < hash2.Count; i++) { Assert.Equal("Value_" + i, hash2["Key_" + i]); } } [Fact] public static void Synchronized_NullTable_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("table", () => Hashtable.Synchronized(null)); // Table is null } [Fact] public static void Values_ModifyingHashtable_ModifiesCollection() { Hashtable hash = Helpers.CreateStringHashtable(100); ICollection values = hash.Values; // Removing a value from the hashtable should update the Values ICollection. // This means that the Values ICollection no longer contains the value. hash.Remove("Key_0"); IEnumerator enumerator = values.GetEnumerator(); while (enumerator.MoveNext()) { Assert.NotEqual("Value_0", enumerator.Current); } } [Fact] public static void HashCodeProvider_Set_ImpactsSearch() { var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); hash.Add("test", "test"); // Should be able to find with the same and different casing Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); // Changing the hash code provider, we shouldn't be able to find either hash.HashCodeProvider = new FixedHashCodeProvider { FixedHashCode = CaseInsensitiveHashCodeProvider.DefaultInvariant.GetHashCode("test") + 1 }; Assert.False(hash.ContainsKey("test")); Assert.False(hash.ContainsKey("TEST")); // Changing it back, should be able to find both again hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant; Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); } [Fact] public static void HashCodeProvider_Comparer_CompatibleGetSet_Success() { var hash = new ComparableHashtable(); Assert.Null(hash.HashCodeProvider); Assert.Null(hash.Comparer); hash = new ComparableHashtable(); hash.HashCodeProvider = null; hash.Comparer = null; hash = new ComparableHashtable(); hash.Comparer = null; hash.HashCodeProvider = null; hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant; hash.Comparer = StringComparer.OrdinalIgnoreCase; } [Fact] public static void HashCodeProvider_Comparer_IncompatibleGetSet_Throws() { var hash = new ComparableHashtable(StringComparer.CurrentCulture); AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider); AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer); AssertExtensions.Throws<ArgumentException>(null, () => hash.HashCodeProvider = CaseInsensitiveHashCodeProvider.DefaultInvariant); AssertExtensions.Throws<ArgumentException>(null, () => hash.Comparer = StringComparer.OrdinalIgnoreCase); } [Fact] public static void Comparer_Set_ImpactsSearch() { var hash = new ComparableHashtable(CaseInsensitiveHashCodeProvider.DefaultInvariant, StringComparer.OrdinalIgnoreCase); hash.Add("test", "test"); // Should be able to find with the same and different casing Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); // Changing the comparer, should only be able to find the matching case hash.Comparer = StringComparer.Ordinal; Assert.True(hash.ContainsKey("test")); Assert.False(hash.ContainsKey("TEST")); // Changing it back, should be able to find both again hash.Comparer = StringComparer.OrdinalIgnoreCase; Assert.True(hash.ContainsKey("test")); Assert.True(hash.ContainsKey("TEST")); } private class FixedHashCodeProvider : IHashCodeProvider { public int FixedHashCode; public int GetHashCode(object obj) => FixedHashCode; } private static void VerifyHashtable(ComparableHashtable hash1, Hashtable hash2, IEqualityComparer ikc) { if (hash2 == null) { Assert.Equal(0, hash1.Count); } else { // Make sure that construtor imports all keys and values Assert.Equal(hash2.Count, hash1.Count); for (int i = 0; i < 100; i++) { Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } // Make sure the new and old hashtables are not linked hash2.Clear(); for (int i = 0; i < 100; i++) { Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } } Assert.Equal(ikc, hash1.EqualityComparer); Assert.False(hash1.IsFixedSize); Assert.False(hash1.IsReadOnly); Assert.False(hash1.IsSynchronized); // Make sure we can add to the hashtable int count = hash1.Count; for (int i = count; i < count + 100; i++) { hash1.Add(i, i); Assert.True(hash1.ContainsKey(i)); Assert.True(hash1.ContainsValue(i)); } } private class ComparableHashtable : Hashtable { public ComparableHashtable() : base() { } public ComparableHashtable(int capacity) : base(capacity) { } public ComparableHashtable(int capacity, float loadFactor) : base(capacity, loadFactor) { } public ComparableHashtable(int capacity, IHashCodeProvider hcp, IComparer comparer) : base(capacity, hcp, comparer) { } public ComparableHashtable(int capacity, IEqualityComparer ikc) : base(capacity, ikc) { } public ComparableHashtable(IHashCodeProvider hcp, IComparer comparer) : base(hcp, comparer) { } public ComparableHashtable(IEqualityComparer ikc) : base(ikc) { } public ComparableHashtable(IDictionary d) : base(d) { } public ComparableHashtable(IDictionary d, float loadFactor) : base(d, loadFactor) { } public ComparableHashtable(IDictionary d, IHashCodeProvider hcp, IComparer comparer) : base(d, hcp, comparer) { } public ComparableHashtable(IDictionary d, IEqualityComparer ikc) : base(d, ikc) { } public ComparableHashtable(IDictionary d, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(d, loadFactor, hcp, comparer) { } public ComparableHashtable(IDictionary d, float loadFactor, IEqualityComparer ikc) : base(d, loadFactor, ikc) { } public ComparableHashtable(int capacity, float loadFactor, IHashCodeProvider hcp, IComparer comparer) : base(capacity, loadFactor, hcp, comparer) { } public ComparableHashtable(int capacity, float loadFactor, IEqualityComparer ikc) : base(capacity, loadFactor, ikc) { } public new IEqualityComparer EqualityComparer => base.EqualityComparer; public IHashCodeProvider HashCodeProvider { get { return hcp; } set { hcp = value; } } public IComparer Comparer { get { return comparer; } set { comparer = value; } } } private class BadHashCode { public BadHashCode(int value) { Value = value; } public int Value { get; private set; } public override bool Equals(object o) { BadHashCode rhValue = o as BadHashCode; if (rhValue != null) { return Value.Equals(rhValue.Value); } else { throw new ArgumentException("is not BadHashCode type actual " + o.GetType(), nameof(o)); } } // Return 0 for everything to force hash collisions. public override int GetHashCode() => 0; public override string ToString() => Value.ToString(); } private class Foo { public string StringValue { get; set; } = "Hello World"; public override bool Equals(object obj) { Foo foo = obj as Foo; return foo != null && StringValue == foo.StringValue; } public override int GetHashCode() => StringValue.GetHashCode(); } } /// <summary> /// A hashtable can have a race condition: /// A read operation on hashtable has three steps: /// (1) calculate the hash and find the slot number. /// (2) compare the hashcode, if equal, go to step 3. Otherwise end. /// (3) compare the key, if equal, go to step 4. Otherwise end. /// (4) return the value contained in the bucket. /// The problem is that after step 3 and before step 4. A writer can kick in a remove the old item and add a new one /// in the same bukcet. In order to make this happen easily, I created two long with same hashcode. /// </summary> public class Hashtable_ItemThreadSafetyTests { private object _key1; private object _key2; private object _value1 = "value1"; private object _value2 = "value2"; private Hashtable _hash; private bool _errorOccurred = false; private bool _timeExpired = false; private const int MAX_TEST_TIME_MS = 10000; // 10 seconds [Fact] [OuterLoop] public void GetItem_ThreadSafety() { int i1 = 0x10; int i2 = 0x100; // Setup key1 and key2 so they are different values but have the same hashcode // To produce a hashcode long XOR's the first 32bits with the last 32 bits long l1 = (((long)i1) << 32) + i2; long l2 = (((long)i2) << 32) + i1; _key1 = l1; _key2 = l2; _hash = new Hashtable(3); // Just one item will be in the hashtable at a time int taskCount = 3; var readers1 = new Task[taskCount]; var readers2 = new Task[taskCount]; Stopwatch stopwatch = Stopwatch.StartNew(); for (int i = 0; i < readers1.Length; i++) { readers1[i] = Task.Run(new Action(ReaderFunction1)); } for (int i = 0; i < readers2.Length; i++) { readers2[i] = Task.Run(new Action(ReaderFunction2)); } Task writer = Task.Run(new Action(WriterFunction)); var spin = new SpinWait(); while (!_errorOccurred && !_timeExpired) { if (MAX_TEST_TIME_MS < stopwatch.ElapsedMilliseconds) { _timeExpired = true; } spin.SpinOnce(); } Task.WaitAll(readers1); Task.WaitAll(readers2); writer.Wait(); Assert.False(_errorOccurred); } private void ReaderFunction1() { while (!_timeExpired) { object value = _hash[_key1]; if (value != null) { Assert.NotEqual(value, _value2); } } } private void ReaderFunction2() { while (!_errorOccurred && !_timeExpired) { object value = _hash[_key2]; if (value != null) { Assert.NotEqual(value, _value1); } } } private void WriterFunction() { while (!_errorOccurred && !_timeExpired) { _hash.Add(_key1, _value1); _hash.Remove(_key1); _hash.Add(_key2, _value2); _hash.Remove(_key2); } } } public class Hashtable_SynchronizedTests { private Hashtable _hash2; private int _iNumberOfElements = 20; [Fact] [OuterLoop] public void SynchronizedThreadSafety() { const int NumberOfWorkers = 3; // Synchronized returns a hashtable that is thread safe // We will try to test this by getting a number of threads to write some items // to a synchronized IList var hash1 = new Hashtable(); _hash2 = Hashtable.Synchronized(hash1); var workers = new Task[NumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { var name = "Thread worker " + i; var task = new Action(() => AddElements(name)); workers[i] = Task.Run(task); } Task.WaitAll(workers); // Check time Assert.Equal(_hash2.Count, _iNumberOfElements * NumberOfWorkers); for (int i = 0; i < NumberOfWorkers; i++) { for (int j = 0; j < _iNumberOfElements; j++) { string strValue = "Thread worker " + i + "_" + j; Assert.True(_hash2.Contains(strValue)); } } // We cannot can make an assumption on the order of these items but // now we are going to remove all of these workers = new Task[NumberOfWorkers]; for (int i = 0; i < workers.Length; i++) { string name = "Thread worker " + i; var task = new Action(() => RemoveElements(name)); workers[i] = Task.Run(task); } Task.WaitAll(workers); Assert.Equal(_hash2.Count, 0); } private void AddElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hash2.Add(strName + "_" + i, "string_" + i); } } private void RemoveElements(string strName) { for (int i = 0; i < _iNumberOfElements; i++) { _hash2.Remove(strName + "_" + i); } } } public class Hashtable_SyncRootTests { private Hashtable _hashDaughter; private Hashtable _hashGrandDaughter; private const int NumberOfElements = 100; [Fact] public void SyncRoot() { // Different hashtables have different SyncRoots var hash1 = new Hashtable(); var hash2 = new Hashtable(); Assert.NotEqual(hash1.SyncRoot, hash2.SyncRoot); Assert.Equal(hash1.SyncRoot.GetType(), typeof(object)); // Cloned hashtables have different SyncRoots hash1 = new Hashtable(); hash2 = Hashtable.Synchronized(hash1); Hashtable hash3 = (Hashtable)hash2.Clone(); Assert.NotEqual(hash2.SyncRoot, hash3.SyncRoot); Assert.NotEqual(hash1.SyncRoot, hash3.SyncRoot); // Testing SyncRoot is not as simple as its implementation looks like. This is the working // scenario we have in mind. // 1) Create your Down to earth mother Hashtable // 2) Get a synchronized wrapper from it // 3) Get a Synchronized wrapper from 2) // 4) Get a synchronized wrapper of the mother from 1) // 5) all of these should SyncRoot to the mother earth var hashMother = new Hashtable(); for (int i = 0; i < NumberOfElements; i++) { hashMother.Add("Key_" + i, "Value_" + i); } Hashtable hashSon = Hashtable.Synchronized(hashMother); _hashGrandDaughter = Hashtable.Synchronized(hashSon); _hashDaughter = Hashtable.Synchronized(hashMother); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashGrandDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(_hashDaughter.SyncRoot, hashMother.SyncRoot); Assert.Equal(hashSon.SyncRoot, hashMother.SyncRoot); // We are going to rumble with the Hashtables with some threads int iNumberOfWorkers = 30; var workers = new Task[iNumberOfWorkers]; var ts2 = new Action(RemoveElements); for (int iThreads = 0; iThreads < iNumberOfWorkers; iThreads += 2) { var name = "Thread_worker_" + iThreads; var ts1 = new Action(() => AddMoreElements(name)); workers[iThreads] = Task.Run(ts1); workers[iThreads + 1] = Task.Run(ts2); } Task.WaitAll(workers); // Check: // Either there should be some elements (the new ones we added and/or the original ones) or none var hshPossibleValues = new Hashtable(); for (int i = 0; i < NumberOfElements; i++) { hshPossibleValues.Add("Key_" + i, "Value_" + i); } for (int i = 0; i < iNumberOfWorkers; i++) { hshPossibleValues.Add("Key_Thread_worker_" + i, "Thread_worker_" + i); } IDictionaryEnumerator idic = hashMother.GetEnumerator(); while (idic.MoveNext()) { Assert.True(hshPossibleValues.ContainsKey(idic.Key)); Assert.True(hshPossibleValues.ContainsValue(idic.Value)); } } private void AddMoreElements(string threadName) { _hashGrandDaughter.Add("Key_" + threadName, threadName); } private void RemoveElements() { _hashDaughter.Clear(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.IO.PortsTests; using System.Text; using System.Threading; using Legacy.Support; using Xunit; namespace System.IO.Ports.Tests { public class SerialStream_BeginWrite : PortsTest { // The string size used for large byte array testing private const int LARGE_BUFFER_SIZE = 2048; // When we test Write and do not care about actually writing anything we must still // create an byte array to pass into the method the following is the size of the // byte array used in this situation private const int DEFAULT_BUFFER_SIZE = 1; private const int DEFAULT_BUFFER_OFFSET = 0; private const int DEFAULT_BUFFER_COUNT = 1; // The maximum buffer size when a exception occurs private const int MAX_BUFFER_SIZE_FOR_EXCEPTION = 255; // The maximum buffer size when a exception is not expected private const int MAX_BUFFER_SIZE = 8; // The default number of times the write method is called when verifying write private const int DEFAULT_NUM_WRITES = 3; // The default number of bytes to write private const int DEFAULT_NUM_BYTES_TO_WRITE = 128; // Maximum time to wait for processing the read command to complete private const int MAX_WAIT_WRITE_COMPLETE = 1000; #region Test Cases [ConditionalFact(nameof(HasOneSerialPort))] public void Buffer_Null() { VerifyWriteException(null, 0, 1, typeof(ArgumentNullException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEG1() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], -1, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_NEGRND() { Random rndGen = new Random(-55); VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], rndGen.Next(int.MinValue, 0), DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_MinInt() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], int.MinValue, DEFAULT_BUFFER_COUNT, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEG1() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, -1, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_NEGRND() { Random rndGen = new Random(-55); VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, rndGen.Next(int.MinValue, 0), typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_MinInt() { VerifyWriteException(new byte[DEFAULT_BUFFER_SIZE], DEFAULT_BUFFER_OFFSET, int.MinValue, typeof(ArgumentOutOfRangeException)); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_EQ_Length_Plus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = bufferLength + 1 - offset; Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void OffsetCount_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(0, bufferLength); int count = rndGen.Next(bufferLength + 1 - offset, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void Offset_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = rndGen.Next(bufferLength, int.MaxValue); int count = DEFAULT_BUFFER_COUNT; Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasOneSerialPort))] public void Count_GT_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE_FOR_EXCEPTION); int offset = DEFAULT_BUFFER_OFFSET; int count = rndGen.Next(bufferLength + 1, int.MaxValue); Type expectedException = typeof(ArgumentException); VerifyWriteException(new byte[bufferLength], offset, count, expectedException); } [ConditionalFact(nameof(HasNullModem))] public void OffsetCount_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = bufferLength - offset; VerifyWrite(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Offset_EQ_Length_Minus_1() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = bufferLength - 1; int count = 1; VerifyWrite(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void Count_EQ_Length() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = 0; int count = bufferLength; VerifyWrite(new byte[bufferLength], offset, count); } [ConditionalFact(nameof(HasNullModem))] public void ASCIIEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new ASCIIEncoding()); } [ConditionalFact(nameof(HasNullModem))] public void UTF8Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new UTF8Encoding()); } [ConditionalFact(nameof(HasNullModem))] public void UTF32Encoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new UTF32Encoding()); } [ConditionalFact(nameof(HasNullModem))] public void UnicodeEncoding() { Random rndGen = new Random(-55); int bufferLength = rndGen.Next(1, MAX_BUFFER_SIZE); int offset = rndGen.Next(0, bufferLength - 1); int count = rndGen.Next(1, bufferLength - offset); VerifyWrite(new byte[bufferLength], offset, count, new UnicodeEncoding()); } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void LargeBuffer() { int bufferLength = LARGE_BUFFER_SIZE; int offset = 0; int count = bufferLength; VerifyWrite(new byte[bufferLength], offset, count, 1); } [ConditionalFact(nameof(HasNullModem))] public void Callback() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { CallbackHandler callbackHandler = new CallbackHandler(); Debug.WriteLine("Verifying BeginWrite with a callback specified"); com1.Open(); com2.Open(); IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(new byte[DEFAULT_NUM_BYTES_TO_WRITE], 0, DEFAULT_NUM_BYTES_TO_WRITE, callbackHandler.Callback, this); callbackHandler.BeginWriteAysncResult = writeAsyncResult; Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync"); Assert.False(writeAsyncResult.IsCompleted, "Should not have completed yet"); com2.RtsEnable = true; // callbackHandler.WriteAysncResult guarantees that the callback has been called however it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackWriteAsyncResult = callbackHandler.WriteAysncResult; // No we have to wait for the callbackHandler to complete int elapsedTime = 0; while (!callbackWriteAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_WRITE_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Equal(this, callbackWriteAsyncResult.AsyncState); Assert.False(callbackWriteAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackWriteAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (write)"); Assert.True(writeAsyncResult.IsCompleted, "Should have completed (write)"); } } [ConditionalFact(nameof(HasNullModem), nameof(HasHardwareFlowControl))] public void Callback_State() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { CallbackHandler callbackHandler = new CallbackHandler(); Debug.WriteLine("Verifying BeginWrite with a callback and state specified"); com1.Handshake = Handshake.RequestToSend; com1.Open(); com2.Open(); IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(new byte[DEFAULT_NUM_BYTES_TO_WRITE], 0, DEFAULT_NUM_BYTES_TO_WRITE, callbackHandler.Callback, this); callbackHandler.BeginWriteAysncResult = writeAsyncResult; Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync"); Assert.False(writeAsyncResult.IsCompleted, "Should not have completed yet"); com2.RtsEnable = true; // callbackHandler.WriteAysncResult guarantees that the callback has been called however it does not gauarentee that // the code calling the callback has finished it's processing IAsyncResult callbackWriteAsyncResult = callbackHandler.WriteAysncResult; // No we have to wait for the callbackHandler to complete int elapsedTime = 0; while (!callbackWriteAsyncResult.IsCompleted && elapsedTime < MAX_WAIT_WRITE_COMPLETE) { Thread.Sleep(10); elapsedTime += 10; } Assert.Equal(this, callbackWriteAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackWriteAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (write)"); Assert.True(writeAsyncResult.IsCompleted, "Should have completed (write)"); } } [ConditionalFact(nameof(HasOneSerialPort))] public void InBreak() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { Debug.WriteLine("Verifying BeginWrite throws InvalidOperationException while in a Break"); com1.Open(); com1.BreakState = true; Assert.Throws<InvalidOperationException>(() => com1.BaseStream.BeginWrite(new byte[8], 0, 8, null, null)); } } #endregion #region Verification for Test Cases private void VerifyWriteException(byte[] buffer, int offset, int count, Type expectedException) { using (SerialPort com = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) { int bufferLength = null == buffer ? 0 : buffer.Length; Debug.WriteLine("Verifying write method throws {0} buffer.Lenght={1}, offset={2}, count={3}", expectedException, bufferLength, offset, count); com.Open(); Assert.Throws(expectedException, () => com.BaseStream.BeginWrite(buffer, offset, count, null, null)); } } private void VerifyWrite(byte[] buffer, int offset, int count) { VerifyWrite(buffer, offset, count, new ASCIIEncoding()); } private void VerifyWrite(byte[] buffer, int offset, int count, int numWrites) { VerifyWrite(buffer, offset, count, new ASCIIEncoding(), numWrites); } private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding) { VerifyWrite(buffer, offset, count, encoding, DEFAULT_NUM_WRITES); } private void VerifyWrite(byte[] buffer, int offset, int count, Encoding encoding, int numWrites) { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { Random rndGen = new Random(-55); Debug.WriteLine("Verifying write method buffer.Lenght={0}, offset={1}, count={2}, endocing={3}", buffer.Length, offset, count, encoding.EncodingName); com1.Encoding = encoding; com2.Encoding = encoding; com1.Open(); com2.Open(); for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)rndGen.Next(0, 256); } VerifyWriteByteArray(buffer, offset, count, com1, com2, numWrites); } } private void VerifyWriteByteArray(byte[] buffer, int offset, int count, SerialPort com1, SerialPort com2, int numWrites) { int index = 0; CallbackHandler callbackHandler = new CallbackHandler(); var oldBuffer = (byte[])buffer.Clone(); var expectedBytes = new byte[count]; var actualBytes = new byte[expectedBytes.Length * numWrites]; for (int i = 0; i < count; i++) { expectedBytes[i] = buffer[i + offset]; } for (int i = 0; i < numWrites; i++) { IAsyncResult writeAsyncResult = com1.BaseStream.BeginWrite(buffer, offset, count, callbackHandler.Callback, this); writeAsyncResult.AsyncWaitHandle.WaitOne(); callbackHandler.BeginWriteAysncResult = writeAsyncResult; com1.BaseStream.EndWrite(writeAsyncResult); IAsyncResult callbackWriteAsyncResult = callbackHandler.WriteAysncResult; Assert.Equal(this, callbackWriteAsyncResult.AsyncState); Assert.False(callbackWriteAsyncResult.CompletedSynchronously, "Should not have completed sync (cback)"); Assert.True(callbackWriteAsyncResult.IsCompleted, "Should have completed (cback)"); Assert.Equal(this, writeAsyncResult.AsyncState); Assert.False(writeAsyncResult.CompletedSynchronously, "Should not have completed sync (write)"); Assert.True(writeAsyncResult.IsCompleted, "Should have completed (write)"); } com2.ReadTimeout = 500; Thread.Sleep((int)(((expectedBytes.Length * numWrites * 10.0) / com1.BaudRate) * 1000) + 250); // Make sure buffer was not altered during the write call for (int i = 0; i < buffer.Length; i++) { if (buffer[i] != oldBuffer[i]) { Fail("ERROR!!!: The contents of the buffer were changed from {0} to {1} at {2}", oldBuffer[i], buffer[i], i); } } while (true) { int byteRead; try { byteRead = com2.ReadByte(); } catch (TimeoutException) { break; } if (actualBytes.Length <= index) { // If we have read in more bytes then we expect Fail("ERROR!!!: We have received more bytes then were sent"); break; } actualBytes[index] = (byte)byteRead; index++; if (actualBytes.Length - index != com2.BytesToRead) { Fail("ERROR!!!: Expected BytesToRead={0} actual={1}", actualBytes.Length - index, com2.BytesToRead); } } // Compare the bytes that were read with the ones we expected to read for (int j = 0; j < numWrites; j++) { for (int i = 0; i < expectedBytes.Length; i++) { if (expectedBytes[i] != actualBytes[i + expectedBytes.Length * j]) { Fail("ERROR!!!: Expected to read byte {0} actual read {1} at {2}", (int)expectedBytes[i], (int)actualBytes[i + expectedBytes.Length * j], i); } } } } private class CallbackHandler { private IAsyncResult _writeAysncResult; private IAsyncResult _beginWriteAysncResult; private readonly SerialPort _com; public CallbackHandler() : this(null) { } private CallbackHandler(SerialPort com) { _com = com; } public void Callback(IAsyncResult writeAysncResult) { Debug.WriteLine("About to enter callback lock (already entered {0})", Monitor.IsEntered(this)); lock (this) { Debug.WriteLine("Inside callback lock"); _writeAysncResult = writeAysncResult; if (!writeAysncResult.IsCompleted) { throw new Exception("Err_23984afaea Expected IAsyncResult passed into callback to not be completed"); } while (null == _beginWriteAysncResult) { Assert.True(Monitor.Wait(this, 5000), "Monitor.Wait in Callback"); } if (null != _beginWriteAysncResult && !_beginWriteAysncResult.IsCompleted) { throw new Exception("Err_7907azpu Expected IAsyncResult returned from begin write to not be completed"); } if (null != _com) { _com.BaseStream.EndWrite(_beginWriteAysncResult); if (!_beginWriteAysncResult.IsCompleted) { throw new Exception("Err_6498afead Expected IAsyncResult returned from begin write to not be completed"); } if (!writeAysncResult.IsCompleted) { throw new Exception("Err_1398ehpo Expected IAsyncResult passed into callback to not be completed"); } } Monitor.Pulse(this); } } public IAsyncResult WriteAysncResult { get { lock (this) { while (null == _writeAysncResult) { Monitor.Wait(this); } return _writeAysncResult; } } } public IAsyncResult BeginWriteAysncResult { get { return _beginWriteAysncResult; } set { lock (this) { _beginWriteAysncResult = value; Monitor.Pulse(this); } } } } #endregion } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using lro = Google.LongRunning; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.LifeSciences.V2Beta { /// <summary>Settings for <see cref="WorkflowsServiceV2BetaClient"/> instances.</summary> public sealed partial class WorkflowsServiceV2BetaSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="WorkflowsServiceV2BetaSettings"/>.</summary> /// <returns>A new instance of the default <see cref="WorkflowsServiceV2BetaSettings"/>.</returns> public static WorkflowsServiceV2BetaSettings GetDefault() => new WorkflowsServiceV2BetaSettings(); /// <summary> /// Constructs a new <see cref="WorkflowsServiceV2BetaSettings"/> object with default settings. /// </summary> public WorkflowsServiceV2BetaSettings() { } private WorkflowsServiceV2BetaSettings(WorkflowsServiceV2BetaSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); RunPipelineSettings = existing.RunPipelineSettings; RunPipelineOperationsSettings = existing.RunPipelineOperationsSettings.Clone(); OnCopy(existing); } partial void OnCopy(WorkflowsServiceV2BetaSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>WorkflowsServiceV2BetaClient.RunPipeline</c> and <c>WorkflowsServiceV2BetaClient.RunPipelineAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>This call will not be retried.</description></item> /// <item><description>Timeout: 60 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings RunPipelineSettings { get; set; } = gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(60000))); /// <summary> /// Long Running Operation settings for calls to <c>WorkflowsServiceV2BetaClient.RunPipeline</c> and /// <c>WorkflowsServiceV2BetaClient.RunPipelineAsync</c>. /// </summary> /// <remarks> /// Uses default <see cref="gax::PollSettings"/> of: /// <list type="bullet"> /// <item><description>Initial delay: 20 seconds.</description></item> /// <item><description>Delay multiplier: 1.5</description></item> /// <item><description>Maximum delay: 45 seconds.</description></item> /// <item><description>Total timeout: 24 hours.</description></item> /// </list> /// </remarks> public lro::OperationsSettings RunPipelineOperationsSettings { get; set; } = new lro::OperationsSettings { DefaultPollSettings = new gax::PollSettings(gax::Expiration.FromTimeout(sys::TimeSpan.FromHours(24)), sys::TimeSpan.FromSeconds(20), 1.5, sys::TimeSpan.FromSeconds(45)), }; /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="WorkflowsServiceV2BetaSettings"/> object.</returns> public WorkflowsServiceV2BetaSettings Clone() => new WorkflowsServiceV2BetaSettings(this); } /// <summary> /// Builder class for <see cref="WorkflowsServiceV2BetaClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> public sealed partial class WorkflowsServiceV2BetaClientBuilder : gaxgrpc::ClientBuilderBase<WorkflowsServiceV2BetaClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public WorkflowsServiceV2BetaSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public WorkflowsServiceV2BetaClientBuilder() { UseJwtAccessWithScopes = WorkflowsServiceV2BetaClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref WorkflowsServiceV2BetaClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<WorkflowsServiceV2BetaClient> task); /// <summary>Builds the resulting client.</summary> public override WorkflowsServiceV2BetaClient Build() { WorkflowsServiceV2BetaClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<WorkflowsServiceV2BetaClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<WorkflowsServiceV2BetaClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private WorkflowsServiceV2BetaClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return WorkflowsServiceV2BetaClient.Create(callInvoker, Settings); } private async stt::Task<WorkflowsServiceV2BetaClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return WorkflowsServiceV2BetaClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => WorkflowsServiceV2BetaClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => WorkflowsServiceV2BetaClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => WorkflowsServiceV2BetaClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>WorkflowsServiceV2Beta client wrapper, for convenient use.</summary> /// <remarks> /// A service for running workflows, such as pipelines consisting of Docker /// containers. /// </remarks> public abstract partial class WorkflowsServiceV2BetaClient { /// <summary> /// The default endpoint for the WorkflowsServiceV2Beta service, which is a host of /// "lifesciences.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "lifesciences.googleapis.com:443"; /// <summary>The default WorkflowsServiceV2Beta scopes.</summary> /// <remarks> /// The default WorkflowsServiceV2Beta scopes are: /// <list type="bullet"> /// <item><description>https://www.googleapis.com/auth/cloud-platform</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="WorkflowsServiceV2BetaClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="WorkflowsServiceV2BetaClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="WorkflowsServiceV2BetaClient"/>.</returns> public static stt::Task<WorkflowsServiceV2BetaClient> CreateAsync(st::CancellationToken cancellationToken = default) => new WorkflowsServiceV2BetaClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="WorkflowsServiceV2BetaClient"/> using the default credentials, endpoint /// and settings. To specify custom credentials or other settings, use /// <see cref="WorkflowsServiceV2BetaClientBuilder"/>. /// </summary> /// <returns>The created <see cref="WorkflowsServiceV2BetaClient"/>.</returns> public static WorkflowsServiceV2BetaClient Create() => new WorkflowsServiceV2BetaClientBuilder().Build(); /// <summary> /// Creates a <see cref="WorkflowsServiceV2BetaClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="WorkflowsServiceV2BetaSettings"/>.</param> /// <returns>The created <see cref="WorkflowsServiceV2BetaClient"/>.</returns> internal static WorkflowsServiceV2BetaClient Create(grpccore::CallInvoker callInvoker, WorkflowsServiceV2BetaSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient grpcClient = new WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient(callInvoker); return new WorkflowsServiceV2BetaClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC WorkflowsServiceV2Beta client</summary> public virtual WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Runs a pipeline. The returned Operation's [metadata] /// [google.longrunning.Operation.metadata] field will contain a /// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status /// of the pipeline execution. The /// [response][google.longrunning.Operation.response] field will contain a /// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the /// pipeline completes successfully. /// /// **Note:** Before you can use this method, the *Life Sciences Service Agent* /// must have access to your project. This is done automatically when the /// Cloud Life Sciences API is first enabled, but if you delete this permission /// you must disable and re-enable the API to grant the Life Sciences /// Service Agent the required permissions. /// Authorization requires the following [Google /// IAM](https://cloud.google.com/iam/) permission: /// /// * `lifesciences.workflows.run` /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual lro::Operation<RunPipelineResponse, Metadata> RunPipeline(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Runs a pipeline. The returned Operation's [metadata] /// [google.longrunning.Operation.metadata] field will contain a /// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status /// of the pipeline execution. The /// [response][google.longrunning.Operation.response] field will contain a /// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the /// pipeline completes successfully. /// /// **Note:** Before you can use this method, the *Life Sciences Service Agent* /// must have access to your project. This is done automatically when the /// Cloud Life Sciences API is first enabled, but if you delete this permission /// you must disable and re-enable the API to grant the Life Sciences /// Service Agent the required permissions. /// Authorization requires the following [Google /// IAM](https://cloud.google.com/iam/) permission: /// /// * `lifesciences.workflows.run` /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<RunPipelineResponse, Metadata>> RunPipelineAsync(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Runs a pipeline. The returned Operation's [metadata] /// [google.longrunning.Operation.metadata] field will contain a /// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status /// of the pipeline execution. The /// [response][google.longrunning.Operation.response] field will contain a /// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the /// pipeline completes successfully. /// /// **Note:** Before you can use this method, the *Life Sciences Service Agent* /// must have access to your project. This is done automatically when the /// Cloud Life Sciences API is first enabled, but if you delete this permission /// you must disable and re-enable the API to grant the Life Sciences /// Service Agent the required permissions. /// Authorization requires the following [Google /// IAM](https://cloud.google.com/iam/) permission: /// /// * `lifesciences.workflows.run` /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<lro::Operation<RunPipelineResponse, Metadata>> RunPipelineAsync(RunPipelineRequest request, st::CancellationToken cancellationToken) => RunPipelineAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary>The long-running operations client for <c>RunPipeline</c>.</summary> public virtual lro::OperationsClient RunPipelineOperationsClient => throw new sys::NotImplementedException(); /// <summary> /// Poll an operation once, using an <c>operationName</c> from a previous invocation of <c>RunPipeline</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The result of polling the operation.</returns> public virtual lro::Operation<RunPipelineResponse, Metadata> PollOnceRunPipeline(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<RunPipelineResponse, Metadata>.PollOnceFromName(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), RunPipelineOperationsClient, callSettings); /// <summary> /// Asynchronously poll an operation once, using an <c>operationName</c> from a previous invocation of /// <c>RunPipeline</c>. /// </summary> /// <param name="operationName"> /// The name of a previously invoked operation. Must not be <c>null</c> or empty. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A task representing the result of polling the operation.</returns> public virtual stt::Task<lro::Operation<RunPipelineResponse, Metadata>> PollOnceRunPipelineAsync(string operationName, gaxgrpc::CallSettings callSettings = null) => lro::Operation<RunPipelineResponse, Metadata>.PollOnceFromNameAsync(gax::GaxPreconditions.CheckNotNullOrEmpty(operationName, nameof(operationName)), RunPipelineOperationsClient, callSettings); } /// <summary>WorkflowsServiceV2Beta client wrapper implementation, for convenient use.</summary> /// <remarks> /// A service for running workflows, such as pipelines consisting of Docker /// containers. /// </remarks> public sealed partial class WorkflowsServiceV2BetaClientImpl : WorkflowsServiceV2BetaClient { private readonly gaxgrpc::ApiCall<RunPipelineRequest, lro::Operation> _callRunPipeline; /// <summary> /// Constructs a client wrapper for the WorkflowsServiceV2Beta service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="WorkflowsServiceV2BetaSettings"/> used within this client. /// </param> public WorkflowsServiceV2BetaClientImpl(WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient grpcClient, WorkflowsServiceV2BetaSettings settings) { GrpcClient = grpcClient; WorkflowsServiceV2BetaSettings effectiveSettings = settings ?? WorkflowsServiceV2BetaSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); RunPipelineOperationsClient = new lro::OperationsClientImpl(grpcClient.CreateOperationsClient(), effectiveSettings.RunPipelineOperationsSettings); _callRunPipeline = clientHelper.BuildApiCall<RunPipelineRequest, lro::Operation>(grpcClient.RunPipelineAsync, grpcClient.RunPipeline, effectiveSettings.RunPipelineSettings).WithGoogleRequestParam("parent", request => request.Parent); Modify_ApiCall(ref _callRunPipeline); Modify_RunPipelineApiCall(ref _callRunPipeline); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_RunPipelineApiCall(ref gaxgrpc::ApiCall<RunPipelineRequest, lro::Operation> call); partial void OnConstruction(WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient grpcClient, WorkflowsServiceV2BetaSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC WorkflowsServiceV2Beta client</summary> public override WorkflowsServiceV2Beta.WorkflowsServiceV2BetaClient GrpcClient { get; } partial void Modify_RunPipelineRequest(ref RunPipelineRequest request, ref gaxgrpc::CallSettings settings); /// <summary>The long-running operations client for <c>RunPipeline</c>.</summary> public override lro::OperationsClient RunPipelineOperationsClient { get; } /// <summary> /// Runs a pipeline. The returned Operation's [metadata] /// [google.longrunning.Operation.metadata] field will contain a /// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status /// of the pipeline execution. The /// [response][google.longrunning.Operation.response] field will contain a /// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the /// pipeline completes successfully. /// /// **Note:** Before you can use this method, the *Life Sciences Service Agent* /// must have access to your project. This is done automatically when the /// Cloud Life Sciences API is first enabled, but if you delete this permission /// you must disable and re-enable the API to grant the Life Sciences /// Service Agent the required permissions. /// Authorization requires the following [Google /// IAM](https://cloud.google.com/iam/) permission: /// /// * `lifesciences.workflows.run` /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override lro::Operation<RunPipelineResponse, Metadata> RunPipeline(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_RunPipelineRequest(ref request, ref callSettings); return new lro::Operation<RunPipelineResponse, Metadata>(_callRunPipeline.Sync(request, callSettings), RunPipelineOperationsClient); } /// <summary> /// Runs a pipeline. The returned Operation's [metadata] /// [google.longrunning.Operation.metadata] field will contain a /// [google.cloud.lifesciences.v2beta.Metadata][google.cloud.lifesciences.v2beta.Metadata] object describing the status /// of the pipeline execution. The /// [response][google.longrunning.Operation.response] field will contain a /// [google.cloud.lifesciences.v2beta.RunPipelineResponse][google.cloud.lifesciences.v2beta.RunPipelineResponse] object if the /// pipeline completes successfully. /// /// **Note:** Before you can use this method, the *Life Sciences Service Agent* /// must have access to your project. This is done automatically when the /// Cloud Life Sciences API is first enabled, but if you delete this permission /// you must disable and re-enable the API to grant the Life Sciences /// Service Agent the required permissions. /// Authorization requires the following [Google /// IAM](https://cloud.google.com/iam/) permission: /// /// * `lifesciences.workflows.run` /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override async stt::Task<lro::Operation<RunPipelineResponse, Metadata>> RunPipelineAsync(RunPipelineRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_RunPipelineRequest(ref request, ref callSettings); return new lro::Operation<RunPipelineResponse, Metadata>(await _callRunPipeline.Async(request, callSettings).ConfigureAwait(false), RunPipelineOperationsClient); } } public static partial class WorkflowsServiceV2Beta { public partial class WorkflowsServiceV2BetaClient { /// <summary> /// Creates a new instance of <see cref="lro::Operations.OperationsClient"/> using the same call invoker as /// this client. /// </summary> /// <returns>A new Operations client for the same target as this client.</returns> public virtual lro::Operations.OperationsClient CreateOperationsClient() => new lro::Operations.OperationsClient(CallInvoker); } } }
using Kitware.VTK; using System; // input file is C:\VTK\Rendering\Testing\Tcl\pickCells.tcl // output file is AVpickCells.cs /// <summary> /// The testing class derived from AVpickCells /// </summary> public class AVpickCellsClass { /// <summary> /// The main entry method called by the CSharp driver /// </summary> /// <param name="argv"></param> public static void AVpickCells(String [] argv) { //Prefix Content is: "" ren1 = vtkRenderer.New(); renWin = vtkRenderWindow.New(); renWin.AddRenderer((vtkRenderer)ren1); iren = new vtkRenderWindowInteractor(); iren.SetRenderWindow((vtkRenderWindow)renWin); // create a scene with one of each cell type[] // Voxel[] voxelPoints = new vtkPoints(); voxelPoints.SetNumberOfPoints((int)8); voxelPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); voxelPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); voxelPoints.InsertPoint((int)2,(double)0,(double)1,(double)0); voxelPoints.InsertPoint((int)3,(double)1,(double)1,(double)0); voxelPoints.InsertPoint((int)4,(double)0,(double)0,(double)1); voxelPoints.InsertPoint((int)5,(double)1,(double)0,(double)1); voxelPoints.InsertPoint((int)6,(double)0,(double)1,(double)1); voxelPoints.InsertPoint((int)7,(double)1,(double)1,(double)1); aVoxel = new vtkVoxel(); aVoxel.GetPointIds().SetId((int)0,(int)0); aVoxel.GetPointIds().SetId((int)1,(int)1); aVoxel.GetPointIds().SetId((int)2,(int)2); aVoxel.GetPointIds().SetId((int)3,(int)3); aVoxel.GetPointIds().SetId((int)4,(int)4); aVoxel.GetPointIds().SetId((int)5,(int)5); aVoxel.GetPointIds().SetId((int)6,(int)6); aVoxel.GetPointIds().SetId((int)7,(int)7); aVoxelGrid = new vtkUnstructuredGrid(); aVoxelGrid.Allocate((int)1,(int)1); aVoxelGrid.InsertNextCell((int)aVoxel.GetCellType(),(vtkIdList)aVoxel.GetPointIds()); aVoxelGrid.SetPoints((vtkPoints)voxelPoints); aVoxelMapper = new vtkDataSetMapper(); aVoxelMapper.SetInputData((vtkDataSet)aVoxelGrid); aVoxelActor = new vtkActor(); aVoxelActor.SetMapper((vtkMapper)aVoxelMapper); aVoxelActor.GetProperty().BackfaceCullingOn(); // Hexahedron[] hexahedronPoints = new vtkPoints(); hexahedronPoints.SetNumberOfPoints((int)8); hexahedronPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); hexahedronPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); hexahedronPoints.InsertPoint((int)2,(double)1,(double)1,(double)0); hexahedronPoints.InsertPoint((int)3,(double)0,(double)1,(double)0); hexahedronPoints.InsertPoint((int)4,(double)0,(double)0,(double)1); hexahedronPoints.InsertPoint((int)5,(double)1,(double)0,(double)1); hexahedronPoints.InsertPoint((int)6,(double)1,(double)1,(double)1); hexahedronPoints.InsertPoint((int)7,(double)0,(double)1,(double)1); aHexahedron = new vtkHexahedron(); aHexahedron.GetPointIds().SetId((int)0,(int)0); aHexahedron.GetPointIds().SetId((int)1,(int)1); aHexahedron.GetPointIds().SetId((int)2,(int)2); aHexahedron.GetPointIds().SetId((int)3,(int)3); aHexahedron.GetPointIds().SetId((int)4,(int)4); aHexahedron.GetPointIds().SetId((int)5,(int)5); aHexahedron.GetPointIds().SetId((int)6,(int)6); aHexahedron.GetPointIds().SetId((int)7,(int)7); aHexahedronGrid = new vtkUnstructuredGrid(); aHexahedronGrid.Allocate((int)1,(int)1); aHexahedronGrid.InsertNextCell((int)aHexahedron.GetCellType(),(vtkIdList)aHexahedron.GetPointIds()); aHexahedronGrid.SetPoints((vtkPoints)hexahedronPoints); aHexahedronMapper = new vtkDataSetMapper(); aHexahedronMapper.SetInputData((vtkDataSet)aHexahedronGrid); aHexahedronActor = new vtkActor(); aHexahedronActor.SetMapper((vtkMapper)aHexahedronMapper); aHexahedronActor.AddPosition((double)2,(double)0,(double)0); aHexahedronActor.GetProperty().BackfaceCullingOn(); // Tetra[] tetraPoints = new vtkPoints(); tetraPoints.SetNumberOfPoints((int)4); tetraPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); tetraPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); tetraPoints.InsertPoint((int)2,(double).5,(double)1,(double)0); tetraPoints.InsertPoint((int)3,(double).5,(double).5,(double)1); aTetra = new vtkTetra(); aTetra.GetPointIds().SetId((int)0,(int)0); aTetra.GetPointIds().SetId((int)1,(int)1); aTetra.GetPointIds().SetId((int)2,(int)2); aTetra.GetPointIds().SetId((int)3,(int)3); aTetraGrid = new vtkUnstructuredGrid(); aTetraGrid.Allocate((int)1,(int)1); aTetraGrid.InsertNextCell((int)aTetra.GetCellType(),(vtkIdList)aTetra.GetPointIds()); aTetraGrid.SetPoints((vtkPoints)tetraPoints); aTetraMapper = new vtkDataSetMapper(); aTetraMapper.SetInputData((vtkDataSet)aTetraGrid); aTetraActor = new vtkActor(); aTetraActor.SetMapper((vtkMapper)aTetraMapper); aTetraActor.AddPosition((double)4,(double)0,(double)0); aTetraActor.GetProperty().BackfaceCullingOn(); // Wedge[] wedgePoints = new vtkPoints(); wedgePoints.SetNumberOfPoints((int)6); wedgePoints.InsertPoint((int)0,(double)0,(double)1,(double)0); wedgePoints.InsertPoint((int)1,(double)0,(double)0,(double)0); wedgePoints.InsertPoint((int)2,(double)0,(double).5,(double).5); wedgePoints.InsertPoint((int)3,(double)1,(double)1,(double)0); wedgePoints.InsertPoint((int)4,(double)1,(double)0,(double)0); wedgePoints.InsertPoint((int)5,(double)1,(double).5,(double).5); aWedge = new vtkWedge(); aWedge.GetPointIds().SetId((int)0,(int)0); aWedge.GetPointIds().SetId((int)1,(int)1); aWedge.GetPointIds().SetId((int)2,(int)2); aWedge.GetPointIds().SetId((int)3,(int)3); aWedge.GetPointIds().SetId((int)4,(int)4); aWedge.GetPointIds().SetId((int)5,(int)5); aWedgeGrid = new vtkUnstructuredGrid(); aWedgeGrid.Allocate((int)1,(int)1); aWedgeGrid.InsertNextCell((int)aWedge.GetCellType(),(vtkIdList)aWedge.GetPointIds()); aWedgeGrid.SetPoints((vtkPoints)wedgePoints); aWedgeMapper = new vtkDataSetMapper(); aWedgeMapper.SetInputData((vtkDataSet)aWedgeGrid); aWedgeActor = new vtkActor(); aWedgeActor.SetMapper((vtkMapper)aWedgeMapper); aWedgeActor.AddPosition((double)6,(double)0,(double)0); aWedgeActor.GetProperty().BackfaceCullingOn(); // Pyramid[] pyramidPoints = new vtkPoints(); pyramidPoints.SetNumberOfPoints((int)5); pyramidPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); pyramidPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); pyramidPoints.InsertPoint((int)2,(double)1,(double)1,(double)0); pyramidPoints.InsertPoint((int)3,(double)0,(double)1,(double)0); pyramidPoints.InsertPoint((int)4,(double).5,(double).5,(double)1); aPyramid = new vtkPyramid(); aPyramid.GetPointIds().SetId((int)0,(int)0); aPyramid.GetPointIds().SetId((int)1,(int)1); aPyramid.GetPointIds().SetId((int)2,(int)2); aPyramid.GetPointIds().SetId((int)3,(int)3); aPyramid.GetPointIds().SetId((int)4,(int)4); aPyramidGrid = new vtkUnstructuredGrid(); aPyramidGrid.Allocate((int)1,(int)1); aPyramidGrid.InsertNextCell((int)aPyramid.GetCellType(),(vtkIdList)aPyramid.GetPointIds()); aPyramidGrid.SetPoints((vtkPoints)pyramidPoints); aPyramidMapper = new vtkDataSetMapper(); aPyramidMapper.SetInputData((vtkDataSet)aPyramidGrid); aPyramidActor = new vtkActor(); aPyramidActor.SetMapper((vtkMapper)aPyramidMapper); aPyramidActor.AddPosition((double)8,(double)0,(double)0); aPyramidActor.GetProperty().BackfaceCullingOn(); // Pixel[] pixelPoints = new vtkPoints(); pixelPoints.SetNumberOfPoints((int)4); pixelPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); pixelPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); pixelPoints.InsertPoint((int)2,(double)0,(double)1,(double)0); pixelPoints.InsertPoint((int)3,(double)1,(double)1,(double)0); aPixel = new vtkPixel(); aPixel.GetPointIds().SetId((int)0,(int)0); aPixel.GetPointIds().SetId((int)1,(int)1); aPixel.GetPointIds().SetId((int)2,(int)2); aPixel.GetPointIds().SetId((int)3,(int)3); aPixelGrid = new vtkUnstructuredGrid(); aPixelGrid.Allocate((int)1,(int)1); aPixelGrid.InsertNextCell((int)aPixel.GetCellType(),(vtkIdList)aPixel.GetPointIds()); aPixelGrid.SetPoints((vtkPoints)pixelPoints); aPixelMapper = new vtkDataSetMapper(); aPixelMapper.SetInputData((vtkDataSet)aPixelGrid); aPixelActor = new vtkActor(); aPixelActor.SetMapper((vtkMapper)aPixelMapper); aPixelActor.AddPosition((double)0,(double)0,(double)2); aPixelActor.GetProperty().BackfaceCullingOn(); // Quad[] quadPoints = new vtkPoints(); quadPoints.SetNumberOfPoints((int)4); quadPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); quadPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); quadPoints.InsertPoint((int)2,(double)1,(double)1,(double)0); quadPoints.InsertPoint((int)3,(double)0,(double)1,(double)0); aQuad = new vtkQuad(); aQuad.GetPointIds().SetId((int)0,(int)0); aQuad.GetPointIds().SetId((int)1,(int)1); aQuad.GetPointIds().SetId((int)2,(int)2); aQuad.GetPointIds().SetId((int)3,(int)3); aQuadGrid = new vtkUnstructuredGrid(); aQuadGrid.Allocate((int)1,(int)1); aQuadGrid.InsertNextCell((int)aQuad.GetCellType(),(vtkIdList)aQuad.GetPointIds()); aQuadGrid.SetPoints((vtkPoints)quadPoints); aQuadMapper = new vtkDataSetMapper(); aQuadMapper.SetInputData((vtkDataSet)aQuadGrid); aQuadActor = new vtkActor(); aQuadActor.SetMapper((vtkMapper)aQuadMapper); aQuadActor.AddPosition((double)2,(double)0,(double)2); aQuadActor.GetProperty().BackfaceCullingOn(); // Triangle[] trianglePoints = new vtkPoints(); trianglePoints.SetNumberOfPoints((int)3); trianglePoints.InsertPoint((int)0,(double)0,(double)0,(double)0); trianglePoints.InsertPoint((int)1,(double)1,(double)0,(double)0); trianglePoints.InsertPoint((int)2,(double).5,(double).5,(double)0); aTriangle = new vtkTriangle(); aTriangle.GetPointIds().SetId((int)0,(int)0); aTriangle.GetPointIds().SetId((int)1,(int)1); aTriangle.GetPointIds().SetId((int)2,(int)2); aTriangleGrid = new vtkUnstructuredGrid(); aTriangleGrid.Allocate((int)1,(int)1); aTriangleGrid.InsertNextCell((int)aTriangle.GetCellType(),(vtkIdList)aTriangle.GetPointIds()); aTriangleGrid.SetPoints((vtkPoints)trianglePoints); aTriangleMapper = new vtkDataSetMapper(); aTriangleMapper.SetInputData((vtkDataSet)aTriangleGrid); aTriangleActor = new vtkActor(); aTriangleActor.SetMapper((vtkMapper)aTriangleMapper); aTriangleActor.AddPosition((double)4,(double)0,(double)2); aTriangleActor.GetProperty().BackfaceCullingOn(); // Polygon[] polygonPoints = new vtkPoints(); polygonPoints.SetNumberOfPoints((int)4); polygonPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); polygonPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); polygonPoints.InsertPoint((int)2,(double)1,(double)1,(double)0); polygonPoints.InsertPoint((int)3,(double)0,(double)1,(double)0); aPolygon = new vtkPolygon(); aPolygon.GetPointIds().SetNumberOfIds((int)4); aPolygon.GetPointIds().SetId((int)0,(int)0); aPolygon.GetPointIds().SetId((int)1,(int)1); aPolygon.GetPointIds().SetId((int)2,(int)2); aPolygon.GetPointIds().SetId((int)3,(int)3); aPolygonGrid = new vtkUnstructuredGrid(); aPolygonGrid.Allocate((int)1,(int)1); aPolygonGrid.InsertNextCell((int)aPolygon.GetCellType(),(vtkIdList)aPolygon.GetPointIds()); aPolygonGrid.SetPoints((vtkPoints)polygonPoints); aPolygonMapper = new vtkDataSetMapper(); aPolygonMapper.SetInputData((vtkDataSet)aPolygonGrid); aPolygonActor = new vtkActor(); aPolygonActor.SetMapper((vtkMapper)aPolygonMapper); aPolygonActor.AddPosition((double)6,(double)0,(double)2); aPolygonActor.GetProperty().BackfaceCullingOn(); // Triangle Strip[] triangleStripPoints = new vtkPoints(); triangleStripPoints.SetNumberOfPoints((int)5); triangleStripPoints.InsertPoint((int)0,(double)0,(double)1,(double)0); triangleStripPoints.InsertPoint((int)1,(double)0,(double)0,(double)0); triangleStripPoints.InsertPoint((int)2,(double)1,(double)1,(double)0); triangleStripPoints.InsertPoint((int)3,(double)1,(double)0,(double)0); triangleStripPoints.InsertPoint((int)4,(double)2,(double)1,(double)0); aTriangleStrip = new vtkTriangleStrip(); aTriangleStrip.GetPointIds().SetNumberOfIds((int)5); aTriangleStrip.GetPointIds().SetId((int)0,(int)0); aTriangleStrip.GetPointIds().SetId((int)1,(int)1); aTriangleStrip.GetPointIds().SetId((int)2,(int)2); aTriangleStrip.GetPointIds().SetId((int)3,(int)3); aTriangleStrip.GetPointIds().SetId((int)4,(int)4); aTriangleStripGrid = new vtkUnstructuredGrid(); aTriangleStripGrid.Allocate((int)1,(int)1); aTriangleStripGrid.InsertNextCell((int)aTriangleStrip.GetCellType(),(vtkIdList)aTriangleStrip.GetPointIds()); aTriangleStripGrid.SetPoints((vtkPoints)triangleStripPoints); aTriangleStripMapper = new vtkDataSetMapper(); aTriangleStripMapper.SetInputData((vtkDataSet)aTriangleStripGrid); aTriangleStripActor = new vtkActor(); aTriangleStripActor.SetMapper((vtkMapper)aTriangleStripMapper); aTriangleStripActor.AddPosition((double)8,(double)0,(double)2); aTriangleStripActor.GetProperty().BackfaceCullingOn(); // Line[] linePoints = new vtkPoints(); linePoints.SetNumberOfPoints((int)2); linePoints.InsertPoint((int)0,(double)0,(double)0,(double)0); linePoints.InsertPoint((int)1,(double)1,(double)1,(double)0); aLine = new vtkLine(); aLine.GetPointIds().SetId((int)0,(int)0); aLine.GetPointIds().SetId((int)1,(int)1); aLineGrid = new vtkUnstructuredGrid(); aLineGrid.Allocate((int)1,(int)1); aLineGrid.InsertNextCell((int)aLine.GetCellType(),(vtkIdList)aLine.GetPointIds()); aLineGrid.SetPoints((vtkPoints)linePoints); aLineMapper = new vtkDataSetMapper(); aLineMapper.SetInputData((vtkDataSet)aLineGrid); aLineActor = new vtkActor(); aLineActor.SetMapper((vtkMapper)aLineMapper); aLineActor.AddPosition((double)0,(double)0,(double)4); aLineActor.GetProperty().BackfaceCullingOn(); // Poly line[] polyLinePoints = new vtkPoints(); polyLinePoints.SetNumberOfPoints((int)3); polyLinePoints.InsertPoint((int)0,(double)0,(double)0,(double)0); polyLinePoints.InsertPoint((int)1,(double)1,(double)1,(double)0); polyLinePoints.InsertPoint((int)2,(double)1,(double)0,(double)0); aPolyLine = new vtkPolyLine(); aPolyLine.GetPointIds().SetNumberOfIds((int)3); aPolyLine.GetPointIds().SetId((int)0,(int)0); aPolyLine.GetPointIds().SetId((int)1,(int)1); aPolyLine.GetPointIds().SetId((int)2,(int)2); aPolyLineGrid = new vtkUnstructuredGrid(); aPolyLineGrid.Allocate((int)1,(int)1); aPolyLineGrid.InsertNextCell((int)aPolyLine.GetCellType(),(vtkIdList)aPolyLine.GetPointIds()); aPolyLineGrid.SetPoints((vtkPoints)polyLinePoints); aPolyLineMapper = new vtkDataSetMapper(); aPolyLineMapper.SetInputData((vtkDataSet)aPolyLineGrid); aPolyLineActor = new vtkActor(); aPolyLineActor.SetMapper((vtkMapper)aPolyLineMapper); aPolyLineActor.AddPosition((double)2,(double)0,(double)4); aPolyLineActor.GetProperty().BackfaceCullingOn(); // Vertex[] vertexPoints = new vtkPoints(); vertexPoints.SetNumberOfPoints((int)1); vertexPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); aVertex = new vtkVertex(); aVertex.GetPointIds().SetId((int)0,(int)0); aVertexGrid = new vtkUnstructuredGrid(); aVertexGrid.Allocate((int)1,(int)1); aVertexGrid.InsertNextCell((int)aVertex.GetCellType(),(vtkIdList)aVertex.GetPointIds()); aVertexGrid.SetPoints((vtkPoints)vertexPoints); aVertexMapper = new vtkDataSetMapper(); aVertexMapper.SetInputData((vtkDataSet)aVertexGrid); aVertexActor = new vtkActor(); aVertexActor.SetMapper((vtkMapper)aVertexMapper); aVertexActor.AddPosition((double)0,(double)0,(double)6); aVertexActor.GetProperty().BackfaceCullingOn(); // Poly Vertex[] polyVertexPoints = new vtkPoints(); polyVertexPoints.SetNumberOfPoints((int)3); polyVertexPoints.InsertPoint((int)0,(double)0,(double)0,(double)0); polyVertexPoints.InsertPoint((int)1,(double)1,(double)0,(double)0); polyVertexPoints.InsertPoint((int)2,(double)1,(double)1,(double)0); aPolyVertex = new vtkPolyVertex(); aPolyVertex.GetPointIds().SetNumberOfIds((int)3); aPolyVertex.GetPointIds().SetId((int)0,(int)0); aPolyVertex.GetPointIds().SetId((int)1,(int)1); aPolyVertex.GetPointIds().SetId((int)2,(int)2); aPolyVertexGrid = new vtkUnstructuredGrid(); aPolyVertexGrid.Allocate((int)1,(int)1); aPolyVertexGrid.InsertNextCell((int)aPolyVertex.GetCellType(),(vtkIdList)aPolyVertex.GetPointIds()); aPolyVertexGrid.SetPoints((vtkPoints)polyVertexPoints); aPolyVertexMapper = new vtkDataSetMapper(); aPolyVertexMapper.SetInputData((vtkDataSet)aPolyVertexGrid); aPolyVertexActor = new vtkActor(); aPolyVertexActor.SetMapper((vtkMapper)aPolyVertexMapper); aPolyVertexActor.AddPosition((double)2,(double)0,(double)6); aPolyVertexActor.GetProperty().BackfaceCullingOn(); // Pentagonal prism[] pentaPoints = new vtkPoints(); pentaPoints.SetNumberOfPoints((int)10); pentaPoints.InsertPoint((int)0,(double)0.25,(double)0.0,(double)0.0); pentaPoints.InsertPoint((int)1,(double)0.75,(double)0.0,(double)0.0); pentaPoints.InsertPoint((int)2,(double)1.0,(double)0.5,(double)0.0); pentaPoints.InsertPoint((int)3,(double)0.5,(double)1.0,(double)0.0); pentaPoints.InsertPoint((int)4,(double)0.0,(double)0.5,(double)0.0); pentaPoints.InsertPoint((int)5,(double)0.25,(double)0.0,(double)1.0); pentaPoints.InsertPoint((int)6,(double)0.75,(double)0.0,(double)1.0); pentaPoints.InsertPoint((int)7,(double)1.0,(double)0.5,(double)1.0); pentaPoints.InsertPoint((int)8,(double)0.5,(double)1.0,(double)1.0); pentaPoints.InsertPoint((int)9,(double)0.0,(double)0.5,(double)1.0); aPenta = new vtkPentagonalPrism(); aPenta.GetPointIds().SetId((int)0,(int)0); aPenta.GetPointIds().SetId((int)1,(int)1); aPenta.GetPointIds().SetId((int)2,(int)2); aPenta.GetPointIds().SetId((int)3,(int)3); aPenta.GetPointIds().SetId((int)4,(int)4); aPenta.GetPointIds().SetId((int)5,(int)5); aPenta.GetPointIds().SetId((int)6,(int)6); aPenta.GetPointIds().SetId((int)7,(int)7); aPenta.GetPointIds().SetId((int)8,(int)8); aPenta.GetPointIds().SetId((int)9,(int)9); aPentaGrid = new vtkUnstructuredGrid(); aPentaGrid.Allocate((int)1,(int)1); aPentaGrid.InsertNextCell((int)aPenta.GetCellType(),(vtkIdList)aPenta.GetPointIds()); aPentaGrid.SetPoints((vtkPoints)pentaPoints); aPentaMapper = new vtkDataSetMapper(); aPentaMapper.SetInputData((vtkDataSet)aPentaGrid); aPentaActor = new vtkActor(); aPentaActor.SetMapper((vtkMapper)aPentaMapper); aPentaActor.AddPosition((double)10,(double)0,(double)0); aPentaActor.GetProperty().BackfaceCullingOn(); // Hexagonal prism[] hexaPoints = new vtkPoints(); hexaPoints.SetNumberOfPoints((int)12); hexaPoints.InsertPoint((int)0,(double)0.0,(double)0.0,(double)0.0); hexaPoints.InsertPoint((int)1,(double)0.5,(double)0.0,(double)0.0); hexaPoints.InsertPoint((int)2,(double)1.0,(double)0.5,(double)0.0); hexaPoints.InsertPoint((int)3,(double)1.0,(double)1.0,(double)0.0); hexaPoints.InsertPoint((int)4,(double)0.5,(double)1.0,(double)0.0); hexaPoints.InsertPoint((int)5,(double)0.0,(double)0.5,(double)0.0); hexaPoints.InsertPoint((int)6,(double)0.0,(double)0.0,(double)1.0); hexaPoints.InsertPoint((int)7,(double)0.5,(double)0.0,(double)1.0); hexaPoints.InsertPoint((int)8,(double)1.0,(double)0.5,(double)1.0); hexaPoints.InsertPoint((int)9,(double)1.0,(double)1.0,(double)1.0); hexaPoints.InsertPoint((int)10,(double)0.5,(double)1.0,(double)1.0); hexaPoints.InsertPoint((int)11,(double)0.0,(double)0.5,(double)1.0); aHexa = new vtkHexagonalPrism(); aHexa.GetPointIds().SetId((int)0,(int)0); aHexa.GetPointIds().SetId((int)1,(int)1); aHexa.GetPointIds().SetId((int)2,(int)2); aHexa.GetPointIds().SetId((int)3,(int)3); aHexa.GetPointIds().SetId((int)4,(int)4); aHexa.GetPointIds().SetId((int)5,(int)5); aHexa.GetPointIds().SetId((int)6,(int)6); aHexa.GetPointIds().SetId((int)7,(int)7); aHexa.GetPointIds().SetId((int)8,(int)8); aHexa.GetPointIds().SetId((int)9,(int)9); aHexa.GetPointIds().SetId((int)10,(int)10); aHexa.GetPointIds().SetId((int)11,(int)11); aHexaGrid = new vtkUnstructuredGrid(); aHexaGrid.Allocate((int)1,(int)1); aHexaGrid.InsertNextCell((int)aHexa.GetCellType(),(vtkIdList)aHexa.GetPointIds()); aHexaGrid.SetPoints((vtkPoints)hexaPoints); aHexaMapper = new vtkDataSetMapper(); aHexaMapper.SetInputData((vtkDataSet)aHexaGrid); aHexaActor = new vtkActor(); aHexaActor.SetMapper((vtkMapper)aHexaMapper); aHexaActor.AddPosition((double)12,(double)0,(double)0); aHexaActor.GetProperty().BackfaceCullingOn(); ren1.SetBackground((double).1,(double).2,(double).4); ren1.AddActor((vtkProp)aVoxelActor); aVoxelActor.GetProperty().SetDiffuseColor((double)1,(double)0,(double)0); ren1.AddActor((vtkProp)aHexahedronActor); aHexahedronActor.GetProperty().SetDiffuseColor((double)1,(double)1,(double)0); ren1.AddActor((vtkProp)aTetraActor); aTetraActor.GetProperty().SetDiffuseColor((double)0,(double)1,(double)0); ren1.AddActor((vtkProp)aWedgeActor); aWedgeActor.GetProperty().SetDiffuseColor((double)0,(double)1,(double)1); ren1.AddActor((vtkProp)aPyramidActor); aPyramidActor.GetProperty().SetDiffuseColor((double)1,(double)0,(double)1); ren1.AddActor((vtkProp)aPixelActor); aPixelActor.GetProperty().SetDiffuseColor((double)0,(double)1,(double)1); ren1.AddActor((vtkProp)aQuadActor); aQuadActor.GetProperty().SetDiffuseColor((double)1,(double)0,(double)1); ren1.AddActor((vtkProp)aTriangleActor); aTriangleActor.GetProperty().SetDiffuseColor((double).3,(double)1,(double).5); ren1.AddActor((vtkProp)aPolygonActor); aPolygonActor.GetProperty().SetDiffuseColor((double)1,(double).4,(double).5); ren1.AddActor((vtkProp)aTriangleStripActor); aTriangleStripActor.GetProperty().SetDiffuseColor((double).3,(double).7,(double)1); ren1.AddActor((vtkProp)aLineActor); aLineActor.GetProperty().SetDiffuseColor((double).2,(double)1,(double)1); ren1.AddActor((vtkProp)aPolyLineActor); aPolyLineActor.GetProperty().SetDiffuseColor((double)1,(double)1,(double)1); ren1.AddActor((vtkProp)aVertexActor); aVertexActor.GetProperty().SetDiffuseColor((double)1,(double)1,(double)1); ren1.AddActor((vtkProp)aPolyVertexActor); aPolyVertexActor.GetProperty().SetDiffuseColor((double)1,(double)1,(double)1); ren1.AddActor((vtkProp)aPentaActor); aPentaActor.GetProperty().SetDiffuseColor((double).2,(double).4,(double).7); ren1.AddActor((vtkProp)aHexaActor); aHexaActor.GetProperty().SetDiffuseColor((double).7,(double).5,(double)1); ren1.ResetCamera(); ren1.GetActiveCamera().Azimuth((double)30); ren1.GetActiveCamera().Elevation((double)20); ren1.GetActiveCamera().Dolly((double)1.25); ren1.ResetCameraClippingRange(); renWin.Render(); cellPicker = new vtkCellPicker(); pointPicker = new vtkPointPicker(); worldPicker = new vtkWorldPointPicker(); cellCount = 0; pointCount = 0; ren1.IsInViewport((int)0,(int)0); x = 0; while((x) <= 265) { y = 100; while((y) <= 200) { cellPicker.Pick((double)x,(double)y,(double)0,(vtkRenderer)ren1); pointPicker.Pick((double)x,(double)y,(double)0,(vtkRenderer)ren1); worldPicker.Pick((double)x,(double)y,(double)0,(vtkRenderer)ren1); if ((cellPicker.GetCellId()) != -1) { cellCount = cellCount + 1; } if ((pointPicker.GetPointId()) != -1) { pointCount = pointCount + 1; } y = y + 6; } x = x + 6; } // render the image[] //[] iren.Initialize(); //deleteAllVTKObjects(); } static string VTK_DATA_ROOT; static int threshold; static vtkRenderer ren1; static vtkRenderWindow renWin; static vtkRenderWindowInteractor iren; static vtkPoints voxelPoints; static vtkVoxel aVoxel; static vtkUnstructuredGrid aVoxelGrid; static vtkDataSetMapper aVoxelMapper; static vtkActor aVoxelActor; static vtkPoints hexahedronPoints; static vtkHexahedron aHexahedron; static vtkUnstructuredGrid aHexahedronGrid; static vtkDataSetMapper aHexahedronMapper; static vtkActor aHexahedronActor; static vtkPoints tetraPoints; static vtkTetra aTetra; static vtkUnstructuredGrid aTetraGrid; static vtkDataSetMapper aTetraMapper; static vtkActor aTetraActor; static vtkPoints wedgePoints; static vtkWedge aWedge; static vtkUnstructuredGrid aWedgeGrid; static vtkDataSetMapper aWedgeMapper; static vtkActor aWedgeActor; static vtkPoints pyramidPoints; static vtkPyramid aPyramid; static vtkUnstructuredGrid aPyramidGrid; static vtkDataSetMapper aPyramidMapper; static vtkActor aPyramidActor; static vtkPoints pixelPoints; static vtkPixel aPixel; static vtkUnstructuredGrid aPixelGrid; static vtkDataSetMapper aPixelMapper; static vtkActor aPixelActor; static vtkPoints quadPoints; static vtkQuad aQuad; static vtkUnstructuredGrid aQuadGrid; static vtkDataSetMapper aQuadMapper; static vtkActor aQuadActor; static vtkPoints trianglePoints; static vtkTriangle aTriangle; static vtkUnstructuredGrid aTriangleGrid; static vtkDataSetMapper aTriangleMapper; static vtkActor aTriangleActor; static vtkPoints polygonPoints; static vtkPolygon aPolygon; static vtkUnstructuredGrid aPolygonGrid; static vtkDataSetMapper aPolygonMapper; static vtkActor aPolygonActor; static vtkPoints triangleStripPoints; static vtkTriangleStrip aTriangleStrip; static vtkUnstructuredGrid aTriangleStripGrid; static vtkDataSetMapper aTriangleStripMapper; static vtkActor aTriangleStripActor; static vtkPoints linePoints; static vtkLine aLine; static vtkUnstructuredGrid aLineGrid; static vtkDataSetMapper aLineMapper; static vtkActor aLineActor; static vtkPoints polyLinePoints; static vtkPolyLine aPolyLine; static vtkUnstructuredGrid aPolyLineGrid; static vtkDataSetMapper aPolyLineMapper; static vtkActor aPolyLineActor; static vtkPoints vertexPoints; static vtkVertex aVertex; static vtkUnstructuredGrid aVertexGrid; static vtkDataSetMapper aVertexMapper; static vtkActor aVertexActor; static vtkPoints polyVertexPoints; static vtkPolyVertex aPolyVertex; static vtkUnstructuredGrid aPolyVertexGrid; static vtkDataSetMapper aPolyVertexMapper; static vtkActor aPolyVertexActor; static vtkPoints pentaPoints; static vtkPentagonalPrism aPenta; static vtkUnstructuredGrid aPentaGrid; static vtkDataSetMapper aPentaMapper; static vtkActor aPentaActor; static vtkPoints hexaPoints; static vtkHexagonalPrism aHexa; static vtkUnstructuredGrid aHexaGrid; static vtkDataSetMapper aHexaMapper; static vtkActor aHexaActor; static vtkCellPicker cellPicker; static vtkPointPicker pointPicker; static vtkWorldPointPicker worldPicker; static int cellCount; static int pointCount; static int x; static int y; ///<summary> A Get Method for Static Variables </summary> public static string GetVTK_DATA_ROOT() { return VTK_DATA_ROOT; } ///<summary> A Set Method for Static Variables </summary> public static void SetVTK_DATA_ROOT(string toSet) { VTK_DATA_ROOT = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getthreshold() { return threshold; } ///<summary> A Set Method for Static Variables </summary> public static void Setthreshold(int toSet) { threshold = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderer Getren1() { return ren1; } ///<summary> A Set Method for Static Variables </summary> public static void Setren1(vtkRenderer toSet) { ren1 = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindow GetrenWin() { return renWin; } ///<summary> A Set Method for Static Variables </summary> public static void SetrenWin(vtkRenderWindow toSet) { renWin = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkRenderWindowInteractor Getiren() { return iren; } ///<summary> A Set Method for Static Variables </summary> public static void Setiren(vtkRenderWindowInteractor toSet) { iren = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetvoxelPoints() { return voxelPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetvoxelPoints(vtkPoints toSet) { voxelPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkVoxel GetaVoxel() { return aVoxel; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVoxel(vtkVoxel toSet) { aVoxel = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaVoxelGrid() { return aVoxelGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVoxelGrid(vtkUnstructuredGrid toSet) { aVoxelGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaVoxelMapper() { return aVoxelMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVoxelMapper(vtkDataSetMapper toSet) { aVoxelMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaVoxelActor() { return aVoxelActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVoxelActor(vtkActor toSet) { aVoxelActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GethexahedronPoints() { return hexahedronPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SethexahedronPoints(vtkPoints toSet) { hexahedronPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkHexahedron GetaHexahedron() { return aHexahedron; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexahedron(vtkHexahedron toSet) { aHexahedron = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaHexahedronGrid() { return aHexahedronGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexahedronGrid(vtkUnstructuredGrid toSet) { aHexahedronGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaHexahedronMapper() { return aHexahedronMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexahedronMapper(vtkDataSetMapper toSet) { aHexahedronMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaHexahedronActor() { return aHexahedronActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexahedronActor(vtkActor toSet) { aHexahedronActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GettetraPoints() { return tetraPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SettetraPoints(vtkPoints toSet) { tetraPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTetra GetaTetra() { return aTetra; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTetra(vtkTetra toSet) { aTetra = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaTetraGrid() { return aTetraGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTetraGrid(vtkUnstructuredGrid toSet) { aTetraGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaTetraMapper() { return aTetraMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTetraMapper(vtkDataSetMapper toSet) { aTetraMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaTetraActor() { return aTetraActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTetraActor(vtkActor toSet) { aTetraActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetwedgePoints() { return wedgePoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetwedgePoints(vtkPoints toSet) { wedgePoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkWedge GetaWedge() { return aWedge; } ///<summary> A Set Method for Static Variables </summary> public static void SetaWedge(vtkWedge toSet) { aWedge = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaWedgeGrid() { return aWedgeGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaWedgeGrid(vtkUnstructuredGrid toSet) { aWedgeGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaWedgeMapper() { return aWedgeMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaWedgeMapper(vtkDataSetMapper toSet) { aWedgeMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaWedgeActor() { return aWedgeActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaWedgeActor(vtkActor toSet) { aWedgeActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetpyramidPoints() { return pyramidPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetpyramidPoints(vtkPoints toSet) { pyramidPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPyramid GetaPyramid() { return aPyramid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPyramid(vtkPyramid toSet) { aPyramid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaPyramidGrid() { return aPyramidGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPyramidGrid(vtkUnstructuredGrid toSet) { aPyramidGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaPyramidMapper() { return aPyramidMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPyramidMapper(vtkDataSetMapper toSet) { aPyramidMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaPyramidActor() { return aPyramidActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPyramidActor(vtkActor toSet) { aPyramidActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetpixelPoints() { return pixelPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetpixelPoints(vtkPoints toSet) { pixelPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPixel GetaPixel() { return aPixel; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPixel(vtkPixel toSet) { aPixel = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaPixelGrid() { return aPixelGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPixelGrid(vtkUnstructuredGrid toSet) { aPixelGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaPixelMapper() { return aPixelMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPixelMapper(vtkDataSetMapper toSet) { aPixelMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaPixelActor() { return aPixelActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPixelActor(vtkActor toSet) { aPixelActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetquadPoints() { return quadPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetquadPoints(vtkPoints toSet) { quadPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkQuad GetaQuad() { return aQuad; } ///<summary> A Set Method for Static Variables </summary> public static void SetaQuad(vtkQuad toSet) { aQuad = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaQuadGrid() { return aQuadGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaQuadGrid(vtkUnstructuredGrid toSet) { aQuadGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaQuadMapper() { return aQuadMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaQuadMapper(vtkDataSetMapper toSet) { aQuadMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaQuadActor() { return aQuadActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaQuadActor(vtkActor toSet) { aQuadActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GettrianglePoints() { return trianglePoints; } ///<summary> A Set Method for Static Variables </summary> public static void SettrianglePoints(vtkPoints toSet) { trianglePoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTriangle GetaTriangle() { return aTriangle; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangle(vtkTriangle toSet) { aTriangle = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaTriangleGrid() { return aTriangleGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleGrid(vtkUnstructuredGrid toSet) { aTriangleGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaTriangleMapper() { return aTriangleMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleMapper(vtkDataSetMapper toSet) { aTriangleMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaTriangleActor() { return aTriangleActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleActor(vtkActor toSet) { aTriangleActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetpolygonPoints() { return polygonPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetpolygonPoints(vtkPoints toSet) { polygonPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolygon GetaPolygon() { return aPolygon; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolygon(vtkPolygon toSet) { aPolygon = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaPolygonGrid() { return aPolygonGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolygonGrid(vtkUnstructuredGrid toSet) { aPolygonGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaPolygonMapper() { return aPolygonMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolygonMapper(vtkDataSetMapper toSet) { aPolygonMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaPolygonActor() { return aPolygonActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolygonActor(vtkActor toSet) { aPolygonActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GettriangleStripPoints() { return triangleStripPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SettriangleStripPoints(vtkPoints toSet) { triangleStripPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkTriangleStrip GetaTriangleStrip() { return aTriangleStrip; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleStrip(vtkTriangleStrip toSet) { aTriangleStrip = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaTriangleStripGrid() { return aTriangleStripGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleStripGrid(vtkUnstructuredGrid toSet) { aTriangleStripGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaTriangleStripMapper() { return aTriangleStripMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleStripMapper(vtkDataSetMapper toSet) { aTriangleStripMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaTriangleStripActor() { return aTriangleStripActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaTriangleStripActor(vtkActor toSet) { aTriangleStripActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetlinePoints() { return linePoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetlinePoints(vtkPoints toSet) { linePoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkLine GetaLine() { return aLine; } ///<summary> A Set Method for Static Variables </summary> public static void SetaLine(vtkLine toSet) { aLine = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaLineGrid() { return aLineGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaLineGrid(vtkUnstructuredGrid toSet) { aLineGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaLineMapper() { return aLineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaLineMapper(vtkDataSetMapper toSet) { aLineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaLineActor() { return aLineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaLineActor(vtkActor toSet) { aLineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetpolyLinePoints() { return polyLinePoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetpolyLinePoints(vtkPoints toSet) { polyLinePoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyLine GetaPolyLine() { return aPolyLine; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyLine(vtkPolyLine toSet) { aPolyLine = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaPolyLineGrid() { return aPolyLineGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyLineGrid(vtkUnstructuredGrid toSet) { aPolyLineGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaPolyLineMapper() { return aPolyLineMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyLineMapper(vtkDataSetMapper toSet) { aPolyLineMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaPolyLineActor() { return aPolyLineActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyLineActor(vtkActor toSet) { aPolyLineActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetvertexPoints() { return vertexPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetvertexPoints(vtkPoints toSet) { vertexPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkVertex GetaVertex() { return aVertex; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVertex(vtkVertex toSet) { aVertex = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaVertexGrid() { return aVertexGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVertexGrid(vtkUnstructuredGrid toSet) { aVertexGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaVertexMapper() { return aVertexMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVertexMapper(vtkDataSetMapper toSet) { aVertexMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaVertexActor() { return aVertexActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaVertexActor(vtkActor toSet) { aVertexActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetpolyVertexPoints() { return polyVertexPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetpolyVertexPoints(vtkPoints toSet) { polyVertexPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPolyVertex GetaPolyVertex() { return aPolyVertex; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyVertex(vtkPolyVertex toSet) { aPolyVertex = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaPolyVertexGrid() { return aPolyVertexGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyVertexGrid(vtkUnstructuredGrid toSet) { aPolyVertexGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaPolyVertexMapper() { return aPolyVertexMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyVertexMapper(vtkDataSetMapper toSet) { aPolyVertexMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaPolyVertexActor() { return aPolyVertexActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPolyVertexActor(vtkActor toSet) { aPolyVertexActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GetpentaPoints() { return pentaPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SetpentaPoints(vtkPoints toSet) { pentaPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPentagonalPrism GetaPenta() { return aPenta; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPenta(vtkPentagonalPrism toSet) { aPenta = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaPentaGrid() { return aPentaGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPentaGrid(vtkUnstructuredGrid toSet) { aPentaGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaPentaMapper() { return aPentaMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPentaMapper(vtkDataSetMapper toSet) { aPentaMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaPentaActor() { return aPentaActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaPentaActor(vtkActor toSet) { aPentaActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPoints GethexaPoints() { return hexaPoints; } ///<summary> A Set Method for Static Variables </summary> public static void SethexaPoints(vtkPoints toSet) { hexaPoints = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkHexagonalPrism GetaHexa() { return aHexa; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexa(vtkHexagonalPrism toSet) { aHexa = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkUnstructuredGrid GetaHexaGrid() { return aHexaGrid; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexaGrid(vtkUnstructuredGrid toSet) { aHexaGrid = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkDataSetMapper GetaHexaMapper() { return aHexaMapper; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexaMapper(vtkDataSetMapper toSet) { aHexaMapper = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkActor GetaHexaActor() { return aHexaActor; } ///<summary> A Set Method for Static Variables </summary> public static void SetaHexaActor(vtkActor toSet) { aHexaActor = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkCellPicker GetcellPicker() { return cellPicker; } ///<summary> A Set Method for Static Variables </summary> public static void SetcellPicker(vtkCellPicker toSet) { cellPicker = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkPointPicker GetpointPicker() { return pointPicker; } ///<summary> A Set Method for Static Variables </summary> public static void SetpointPicker(vtkPointPicker toSet) { pointPicker = toSet; } ///<summary> A Get Method for Static Variables </summary> public static vtkWorldPointPicker GetworldPicker() { return worldPicker; } ///<summary> A Set Method for Static Variables </summary> public static void SetworldPicker(vtkWorldPointPicker toSet) { worldPicker = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int GetcellCount() { return cellCount; } ///<summary> A Set Method for Static Variables </summary> public static void SetcellCount(int toSet) { cellCount = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int GetpointCount() { return pointCount; } ///<summary> A Set Method for Static Variables </summary> public static void SetpointCount(int toSet) { pointCount = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Getx() { return x; } ///<summary> A Set Method for Static Variables </summary> public static void Setx(int toSet) { x = toSet; } ///<summary> A Get Method for Static Variables </summary> public static int Gety() { return y; } ///<summary> A Set Method for Static Variables </summary> public static void Sety(int toSet) { y = toSet; } ///<summary>Deletes all static objects created</summary> public static void deleteAllVTKObjects() { //clean up vtk objects if(ren1!= null){ren1.Dispose();} if(renWin!= null){renWin.Dispose();} if(iren!= null){iren.Dispose();} if(voxelPoints!= null){voxelPoints.Dispose();} if(aVoxel!= null){aVoxel.Dispose();} if(aVoxelGrid!= null){aVoxelGrid.Dispose();} if(aVoxelMapper!= null){aVoxelMapper.Dispose();} if(aVoxelActor!= null){aVoxelActor.Dispose();} if(hexahedronPoints!= null){hexahedronPoints.Dispose();} if(aHexahedron!= null){aHexahedron.Dispose();} if(aHexahedronGrid!= null){aHexahedronGrid.Dispose();} if(aHexahedronMapper!= null){aHexahedronMapper.Dispose();} if(aHexahedronActor!= null){aHexahedronActor.Dispose();} if(tetraPoints!= null){tetraPoints.Dispose();} if(aTetra!= null){aTetra.Dispose();} if(aTetraGrid!= null){aTetraGrid.Dispose();} if(aTetraMapper!= null){aTetraMapper.Dispose();} if(aTetraActor!= null){aTetraActor.Dispose();} if(wedgePoints!= null){wedgePoints.Dispose();} if(aWedge!= null){aWedge.Dispose();} if(aWedgeGrid!= null){aWedgeGrid.Dispose();} if(aWedgeMapper!= null){aWedgeMapper.Dispose();} if(aWedgeActor!= null){aWedgeActor.Dispose();} if(pyramidPoints!= null){pyramidPoints.Dispose();} if(aPyramid!= null){aPyramid.Dispose();} if(aPyramidGrid!= null){aPyramidGrid.Dispose();} if(aPyramidMapper!= null){aPyramidMapper.Dispose();} if(aPyramidActor!= null){aPyramidActor.Dispose();} if(pixelPoints!= null){pixelPoints.Dispose();} if(aPixel!= null){aPixel.Dispose();} if(aPixelGrid!= null){aPixelGrid.Dispose();} if(aPixelMapper!= null){aPixelMapper.Dispose();} if(aPixelActor!= null){aPixelActor.Dispose();} if(quadPoints!= null){quadPoints.Dispose();} if(aQuad!= null){aQuad.Dispose();} if(aQuadGrid!= null){aQuadGrid.Dispose();} if(aQuadMapper!= null){aQuadMapper.Dispose();} if(aQuadActor!= null){aQuadActor.Dispose();} if(trianglePoints!= null){trianglePoints.Dispose();} if(aTriangle!= null){aTriangle.Dispose();} if(aTriangleGrid!= null){aTriangleGrid.Dispose();} if(aTriangleMapper!= null){aTriangleMapper.Dispose();} if(aTriangleActor!= null){aTriangleActor.Dispose();} if(polygonPoints!= null){polygonPoints.Dispose();} if(aPolygon!= null){aPolygon.Dispose();} if(aPolygonGrid!= null){aPolygonGrid.Dispose();} if(aPolygonMapper!= null){aPolygonMapper.Dispose();} if(aPolygonActor!= null){aPolygonActor.Dispose();} if(triangleStripPoints!= null){triangleStripPoints.Dispose();} if(aTriangleStrip!= null){aTriangleStrip.Dispose();} if(aTriangleStripGrid!= null){aTriangleStripGrid.Dispose();} if(aTriangleStripMapper!= null){aTriangleStripMapper.Dispose();} if(aTriangleStripActor!= null){aTriangleStripActor.Dispose();} if(linePoints!= null){linePoints.Dispose();} if(aLine!= null){aLine.Dispose();} if(aLineGrid!= null){aLineGrid.Dispose();} if(aLineMapper!= null){aLineMapper.Dispose();} if(aLineActor!= null){aLineActor.Dispose();} if(polyLinePoints!= null){polyLinePoints.Dispose();} if(aPolyLine!= null){aPolyLine.Dispose();} if(aPolyLineGrid!= null){aPolyLineGrid.Dispose();} if(aPolyLineMapper!= null){aPolyLineMapper.Dispose();} if(aPolyLineActor!= null){aPolyLineActor.Dispose();} if(vertexPoints!= null){vertexPoints.Dispose();} if(aVertex!= null){aVertex.Dispose();} if(aVertexGrid!= null){aVertexGrid.Dispose();} if(aVertexMapper!= null){aVertexMapper.Dispose();} if(aVertexActor!= null){aVertexActor.Dispose();} if(polyVertexPoints!= null){polyVertexPoints.Dispose();} if(aPolyVertex!= null){aPolyVertex.Dispose();} if(aPolyVertexGrid!= null){aPolyVertexGrid.Dispose();} if(aPolyVertexMapper!= null){aPolyVertexMapper.Dispose();} if(aPolyVertexActor!= null){aPolyVertexActor.Dispose();} if(pentaPoints!= null){pentaPoints.Dispose();} if(aPenta!= null){aPenta.Dispose();} if(aPentaGrid!= null){aPentaGrid.Dispose();} if(aPentaMapper!= null){aPentaMapper.Dispose();} if(aPentaActor!= null){aPentaActor.Dispose();} if(hexaPoints!= null){hexaPoints.Dispose();} if(aHexa!= null){aHexa.Dispose();} if(aHexaGrid!= null){aHexaGrid.Dispose();} if(aHexaMapper!= null){aHexaMapper.Dispose();} if(aHexaActor!= null){aHexaActor.Dispose();} if(cellPicker!= null){cellPicker.Dispose();} if(pointPicker!= null){pointPicker.Dispose();} if(worldPicker!= null){worldPicker.Dispose();} } } //--- end of script --//
using System; using System.Collections.Generic; using System.Composition.Hosting; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Endpoint; using OmniSharp.Mef; using OmniSharp.Models.UpdateBuffer; using OmniSharp.Plugins; using OmniSharp.Services; using OmniSharp.Protocol; using OmniSharp.Utilities; using System.Globalization; namespace OmniSharp.Stdio { internal class Host : IDisposable { private readonly TextReader _input; private readonly ISharedTextWriter _writer; private readonly IServiceProvider _serviceProvider; private readonly IDictionary<string, Lazy<EndpointHandler>> _endpointHandlers; private readonly CompositionHost _compositionHost; private readonly ILogger _logger; private readonly IOmniSharpEnvironment _environment; private readonly CancellationTokenSource _cancellationTokenSource; private readonly CachedStringBuilder _cachedStringBuilder; private static readonly double TimestampToTicks = TimeSpan.TicksPerSecond / (double)Stopwatch.Frequency; public Host( TextReader input, ISharedTextWriter writer, IOmniSharpEnvironment environment, IServiceProvider serviceProvider, CompositionHostBuilder compositionHostBuilder, ILoggerFactory loggerFactory, CancellationTokenSource cancellationTokenSource) { _cancellationTokenSource = cancellationTokenSource; _input = input; _writer = writer; _environment = environment; _serviceProvider = serviceProvider; _logger = loggerFactory.CreateLogger<Host>(); _logger.LogInformation($"Starting OmniSharp on {Platform.Current}"); _compositionHost = compositionHostBuilder.Build(_environment.TargetDirectory); _cachedStringBuilder = new CachedStringBuilder(); var handlers = Initialize(); _endpointHandlers = handlers; } private IDictionary<string, Lazy<EndpointHandler>> Initialize() { var workspace = _compositionHost.GetExport<OmniSharpWorkspace>(); var projectSystems = _compositionHost.GetExports<IProjectSystem>(); var endpointMetadatas = _compositionHost.GetExports<Lazy<IRequest, OmniSharpEndpointMetadata>>() .Select(x => x.Metadata) .ToArray(); var handlers = _compositionHost.GetExports<Lazy<IRequestHandler, OmniSharpRequestHandlerMetadata>>(); var updateBufferEndpointHandler = new Lazy<EndpointHandler<UpdateBufferRequest, object>>( () => (EndpointHandler<UpdateBufferRequest, object>)_endpointHandlers[OmniSharpEndpoints.UpdateBuffer].Value); var languagePredicateHandler = new LanguagePredicateHandler(projectSystems); var projectSystemPredicateHandler = new StaticLanguagePredicateHandler("Projects"); var nugetPredicateHandler = new StaticLanguagePredicateHandler("NuGet"); var endpointHandlers = endpointMetadatas.ToDictionary( x => x.EndpointName, endpoint => new Lazy<EndpointHandler>(() => { IPredicateHandler handler; // Projects are a special case, this allows us to select the correct "Projects" language for them if (endpoint.EndpointName == OmniSharpEndpoints.ProjectInformation || endpoint.EndpointName == OmniSharpEndpoints.WorkspaceInformation) handler = projectSystemPredicateHandler; else if (endpoint.EndpointName == OmniSharpEndpoints.PackageSearch || endpoint.EndpointName == OmniSharpEndpoints.PackageSource || endpoint.EndpointName == OmniSharpEndpoints.PackageVersion) handler = nugetPredicateHandler; else handler = languagePredicateHandler; // This lets any endpoint, that contains a Request object, invoke update buffer. // The language will be same language as the caller, this means any language service // must implement update buffer. var updateEndpointHandler = updateBufferEndpointHandler; if (endpoint.EndpointName == OmniSharpEndpoints.UpdateBuffer) { // We don't want to call update buffer on update buffer. updateEndpointHandler = new Lazy<EndpointHandler<UpdateBufferRequest, object>>(() => null); } return EndpointHandler.Factory(handler, _compositionHost, _logger, endpoint, handlers, updateEndpointHandler, Enumerable.Empty<Plugin>()); }), StringComparer.OrdinalIgnoreCase ); // Handled as alternative middleware in http endpointHandlers.Add( OmniSharpEndpoints.CheckAliveStatus, new Lazy<EndpointHandler>( () => new GenericEndpointHandler(x => Task.FromResult<object>(true))) ); endpointHandlers.Add( OmniSharpEndpoints.CheckReadyStatus, new Lazy<EndpointHandler>( () => new GenericEndpointHandler(x => Task.FromResult<object>(workspace.Initialized))) ); endpointHandlers.Add( OmniSharpEndpoints.StopServer, new Lazy<EndpointHandler>( () => new GenericEndpointHandler(x => { _cancellationTokenSource.Cancel(); return Task.FromResult<object>(null); })) ); return endpointHandlers; } public void Dispose() { _compositionHost?.Dispose(); _cancellationTokenSource?.Dispose(); } public void Start() { WorkspaceInitializer.Initialize(_serviceProvider, _compositionHost); Task.Factory.StartNew(async () => { _writer.WriteLine(new EventPacket() { Event = "started" }); while (!_cancellationTokenSource.IsCancellationRequested) { var line = await _input.ReadLineAsync(); if (line == null) { break; } var ignored = Task.Factory.StartNew(async () => { try { await HandleRequest(line, _logger); } catch (Exception e) { if (e is AggregateException aggregateEx) { e = aggregateEx.Flatten().InnerException; } _writer.WriteLine(new EventPacket() { Event = "error", Body = JsonConvert.ToString(e.ToString(), '"', StringEscapeHandling.Default) }); } }); } }); _logger.LogInformation($"Omnisharp server running using {nameof(TransportType.Stdio)} at location '{_environment.TargetDirectory}' on host {_environment.HostProcessId}."); Console.CancelKeyPress += (sender, e) => { _cancellationTokenSource.Cancel(); e.Cancel = true; }; if (_environment.HostProcessId != -1) { try { var hostProcess = Process.GetProcessById(_environment.HostProcessId); hostProcess.EnableRaisingEvents = true; hostProcess.OnExit(() => _cancellationTokenSource.Cancel()); } catch { // If the process dies before we get here then request shutdown // immediately _cancellationTokenSource.Cancel(); } } } private async Task HandleRequest(string json, ILogger logger) { var startTimestamp = Stopwatch.GetTimestamp(); var request = RequestPacket.Parse(json); if (logger.IsEnabled(LogLevel.Debug)) { LogRequest(json, logger, LogLevel.Debug); } var response = request.Reply(); try { if (!request.Command.StartsWith("/")) { request.Command = $"/{request.Command}"; } // hand off request to next layer if (_endpointHandlers.TryGetValue(request.Command, out var handler)) { var result = await handler.Value.Handle(request); response.Body = result; return; } throw new NotSupportedException($"Command '{request.Command}' is not supported."); } catch (Exception e) { if (e is AggregateException aggregateEx) { e = aggregateEx.Flatten().InnerException; } // updating the response object here so that the ResponseStream // prints the latest state when being closed response.Success = false; response.Message = JsonConvert.ToString(e.ToString(), '"', StringEscapeHandling.Default); } finally { // response gets logged when Debug or more detailed log level is enabled // or when we have unsuccessful response (exception) if (logger.IsEnabled(LogLevel.Debug) || !response.Success) { // if logging is at Debug level, request would have already been logged // however not for higher log levels, so we want to explicitly log the request too if (!logger.IsEnabled(LogLevel.Debug)) { LogRequest(json, logger, LogLevel.Warning); } var currentTimestamp = Stopwatch.GetTimestamp(); var elapsed = new TimeSpan((long)(TimestampToTicks * (currentTimestamp - startTimestamp))); LogResponse(response.ToString(), logger, response.Success, elapsed); } // actually write it _writer.WriteLine(response); } } void LogRequest(string json, ILogger logger, LogLevel logLevel) { var builder = _cachedStringBuilder.Acquire(); try { builder.AppendLine("************ Request ************"); builder.Append(JToken.Parse(json).ToString(Formatting.Indented)); logger.Log(logLevel, builder.ToString()); } finally { _cachedStringBuilder.Release(builder); } } void LogResponse(string json, ILogger logger, bool isSuccess, TimeSpan elapsed) { var builder = _cachedStringBuilder.Acquire(); try { builder.AppendLine($"************ Response ({elapsed.TotalMilliseconds.ToString("0.0000", CultureInfo.InvariantCulture)}ms) ************ "); builder.Append(JToken.Parse(json).ToString(Formatting.Indented)); if (isSuccess) { logger.LogDebug(builder.ToString()); } else { logger.LogError(builder.ToString()); } } finally { _cachedStringBuilder.Release(builder); } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Concurrent; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Runspaces; using Microsoft.PowerShell.MarkdownRender; namespace Microsoft.PowerShell.Commands { /// <summary> /// Class for implementing Set-MarkdownOption cmdlet. /// </summary> [Cmdlet( VerbsCommon.Set, "MarkdownOption", DefaultParameterSetName = IndividualSetting, HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006265")] [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo))] public class SetMarkdownOptionCommand : PSCmdlet { /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 1. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header1Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 2. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header2Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 3. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header3Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 4. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header4Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 5. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header5Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for Header Level 6. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Header6Color { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for code block background. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string Code { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for image alt text foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string ImageAltTextForegroundColor { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for link foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string LinkForegroundColor { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for italics text foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string ItalicsForegroundColor { get; set; } /// <summary> /// Gets or sets the VT100 escape sequence for bold text foreground. /// </summary> [ValidatePattern(@"^\[*[0-9;]*?m{1}")] [Parameter(ParameterSetName = IndividualSetting)] public string BoldForegroundColor { get; set; } /// <summary> /// Gets or sets the switch to PassThru the values set. /// </summary> [Parameter] public SwitchParameter PassThru { get; set; } /// <summary> /// Gets or sets the Theme. /// </summary> [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = ThemeParamSet, Mandatory = true)] [ValidateSet(DarkThemeName, LightThemeName)] public string Theme { get; set; } /// <summary> /// Gets or sets InputObject. /// </summary> [ValidateNotNullOrEmpty] [Parameter(ParameterSetName = InputObjectParamSet, Mandatory = true, ValueFromPipeline = true, Position = 0)] public PSObject InputObject { get; set; } private const string IndividualSetting = "IndividualSetting"; private const string InputObjectParamSet = "InputObject"; private const string ThemeParamSet = "Theme"; private const string LightThemeName = "Light"; private const string DarkThemeName = "Dark"; /// <summary> /// Override EndProcessing. /// </summary> protected override void EndProcessing() { PSMarkdownOptionInfo mdOptionInfo = null; switch (ParameterSetName) { case ThemeParamSet: mdOptionInfo = new PSMarkdownOptionInfo(); if (string.Equals(Theme, LightThemeName, StringComparison.OrdinalIgnoreCase)) { mdOptionInfo.SetLightTheme(); } else if (string.Equals(Theme, DarkThemeName, StringComparison.OrdinalIgnoreCase)) { mdOptionInfo.SetDarkTheme(); } break; case InputObjectParamSet: object baseObj = InputObject.BaseObject; mdOptionInfo = baseObj as PSMarkdownOptionInfo; if (mdOptionInfo == null) { var errorMessage = StringUtil.Format(ConvertMarkdownStrings.InvalidInputObjectType, baseObj.GetType()); ErrorRecord errorRecord = new( new ArgumentException(errorMessage), "InvalidObject", ErrorCategory.InvalidArgument, InputObject); } break; case IndividualSetting: mdOptionInfo = new PSMarkdownOptionInfo(); SetOptions(mdOptionInfo); break; } var setOption = PSMarkdownOptionInfoCache.Set(this.CommandInfo, mdOptionInfo); if (PassThru.IsPresent) { WriteObject(setOption); } } private void SetOptions(PSMarkdownOptionInfo mdOptionInfo) { if (!string.IsNullOrEmpty(Header1Color)) { mdOptionInfo.Header1 = Header1Color; } if (!string.IsNullOrEmpty(Header2Color)) { mdOptionInfo.Header2 = Header2Color; } if (!string.IsNullOrEmpty(Header3Color)) { mdOptionInfo.Header3 = Header3Color; } if (!string.IsNullOrEmpty(Header4Color)) { mdOptionInfo.Header4 = Header4Color; } if (!string.IsNullOrEmpty(Header5Color)) { mdOptionInfo.Header5 = Header5Color; } if (!string.IsNullOrEmpty(Header6Color)) { mdOptionInfo.Header6 = Header6Color; } if (!string.IsNullOrEmpty(Code)) { mdOptionInfo.Code = Code; } if (!string.IsNullOrEmpty(ImageAltTextForegroundColor)) { mdOptionInfo.Image = ImageAltTextForegroundColor; } if (!string.IsNullOrEmpty(LinkForegroundColor)) { mdOptionInfo.Link = LinkForegroundColor; } if (!string.IsNullOrEmpty(ItalicsForegroundColor)) { mdOptionInfo.EmphasisItalics = ItalicsForegroundColor; } if (!string.IsNullOrEmpty(BoldForegroundColor)) { mdOptionInfo.EmphasisBold = BoldForegroundColor; } } } /// <summary> /// Implements the cmdlet for getting the Markdown options that are set. /// </summary> [Cmdlet( VerbsCommon.Get, "MarkdownOption", HelpUri = "https://go.microsoft.com/fwlink/?linkid=2006371")] [OutputType(typeof(Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo))] public class GetMarkdownOptionCommand : PSCmdlet { private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; /// <summary> /// Override EndProcessing. /// </summary> protected override void EndProcessing() { WriteObject(PSMarkdownOptionInfoCache.Get(this.CommandInfo)); } } /// <summary> /// The class manages whether we should use a module scope variable or concurrent dictionary for storing the set PSMarkdownOptions. /// When we have a moduleInfo available we use the module scope variable. /// In case of built-in modules, they are loaded as snapins when we are hosting PowerShell. /// We use runspace Id as the key for the concurrent dictionary to have the functionality of separate settings per runspace. /// Force loading the module does not unload the nested modules and hence we cannot use IModuleAssemblyCleanup to remove items from the dictionary. /// Because of these reason, we continue using module scope variable when moduleInfo is available. /// </summary> internal static class PSMarkdownOptionInfoCache { private static readonly ConcurrentDictionary<Guid, PSMarkdownOptionInfo> markdownOptionInfoCache; private const string MarkdownOptionInfoVariableName = "PSMarkdownOptionInfo"; static PSMarkdownOptionInfoCache() { markdownOptionInfoCache = new ConcurrentDictionary<Guid, PSMarkdownOptionInfo>(); } internal static PSMarkdownOptionInfo Get(CommandInfo command) { // If we have the moduleInfo then store are module scope variable if (command.Module != null) { return command.Module.SessionState.PSVariable.GetValue(MarkdownOptionInfoVariableName, new PSMarkdownOptionInfo()) as PSMarkdownOptionInfo; } // If we don't have a moduleInfo, like in PowerShell hosting scenarios, use a concurrent dictionary. if (markdownOptionInfoCache.TryGetValue(Runspace.DefaultRunspace.InstanceId, out PSMarkdownOptionInfo cachedOption)) { // return the cached options for the runspaceId return cachedOption; } else { // no option cache so cache and return the default PSMarkdownOptionInfo var newOptionInfo = new PSMarkdownOptionInfo(); return markdownOptionInfoCache.GetOrAdd(Runspace.DefaultRunspace.InstanceId, newOptionInfo); } } internal static PSMarkdownOptionInfo Set(CommandInfo command, PSMarkdownOptionInfo optionInfo) { // If we have the moduleInfo then store are module scope variable if (command.Module != null) { command.Module.SessionState.PSVariable.Set(MarkdownOptionInfoVariableName, optionInfo); return optionInfo; } // If we don't have a moduleInfo, like in PowerShell hosting scenarios with modules loaded as snapins, use a concurrent dictionary. return markdownOptionInfoCache.AddOrUpdate(Runspace.DefaultRunspace.InstanceId, optionInfo, (key, oldvalue) => optionInfo); } } }
// 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; namespace System.Xml { internal partial class ReadContentAsBinaryHelper { // Private enums private enum State { None, InReadContent, InReadElementContent, } // Fields private XmlReader _reader; private State _state; private int _valueOffset; private bool _isEnd; private bool _canReadValueChunk; private char[] _valueChunk; private int _valueChunkLength; private IncrementalReadDecoder _decoder; private Base64Decoder _base64Decoder; private BinHexDecoder _binHexDecoder; // Constants private const int ChunkSize = 256; // Constructor internal ReadContentAsBinaryHelper(XmlReader reader) { _reader = reader; _canReadValueChunk = reader.CanReadValueChunk; if (_canReadValueChunk) { _valueChunk = new char[ChunkSize]; } } // Static methods internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader) { if (helper == null) { return new ReadContentAsBinaryHelper(reader); } else { helper.Reset(); return helper; } } // Internal methods internal int ReadContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBase64"); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (!_reader.CanReadContentAs()) { throw _reader.CreateReadContentAsException("ReadContentAsBinHex"); } if (!Init()) { return 0; } break; case State.InReadContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadContentAsBinary(buffer, index, count); } break; case State.InReadElementContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBase64(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBase64"); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _base64Decoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup base64 decoder InitBase64Decoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { // check arguments if (buffer == null) { throw new ArgumentNullException("buffer"); } if (count < 0) { throw new ArgumentOutOfRangeException("count"); } if (index < 0) { throw new ArgumentOutOfRangeException("index"); } if (buffer.Length - index < count) { throw new ArgumentOutOfRangeException("count"); } switch (_state) { case State.None: if (_reader.NodeType != XmlNodeType.Element) { throw _reader.CreateReadElementContentAsException("ReadElementContentAsBinHex"); } if (!InitOnElement()) { return 0; } break; case State.InReadContent: throw new InvalidOperationException(SR.Xml_MixingBinaryContentMethods); case State.InReadElementContent: // if we have a correct decoder, go read if (_decoder == _binHexDecoder) { // read more binary data return ReadElementContentAsBinary(buffer, index, count); } break; default: Debug.Assert(false); return 0; } Debug.Assert(_state == State.InReadElementContent); // setup binhex decoder InitBinHexDecoder(); // read more binary data return ReadElementContentAsBinary(buffer, index, count); } internal void Finish() { if (_state != State.None) { while (MoveToNextContentNode(true)) { } if (_state == State.InReadElementContent) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); } } Reset(); } internal void Reset() { _state = State.None; _isEnd = false; _valueOffset = 0; } // Private methods private bool Init() { // make sure we are on a content node if (!MoveToNextContentNode(false)) { return false; } _state = State.InReadContent; _isEnd = false; return true; } private bool InitOnElement() { Debug.Assert(_reader.NodeType == XmlNodeType.Element); bool isEmpty = _reader.IsEmptyElement; // move to content or off the empty element _reader.Read(); if (isEmpty) { return false; } // make sure we are on a content node if (!MoveToNextContentNode(false)) { if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off end element _reader.Read(); return false; } _state = State.InReadElementContent; _isEnd = false; return true; } private void InitBase64Decoder() { if (_base64Decoder == null) { _base64Decoder = new Base64Decoder(); } else { _base64Decoder.Reset(); } _decoder = _base64Decoder; } private void InitBinHexDecoder() { if (_binHexDecoder == null) { _binHexDecoder = new BinHexDecoder(); } else { _binHexDecoder.Reset(); } _decoder = _binHexDecoder; } private int ReadContentAsBinary(byte[] buffer, int index, int count) { Debug.Assert(_decoder != null); if (_isEnd) { Reset(); return 0; } _decoder.SetNextOutputBuffer(buffer, index, count); for (; ;) { // use streaming ReadValueChunk if the reader supports it if (_canReadValueChunk) { for (; ;) { if (_valueOffset < _valueChunkLength) { int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) { return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk, 0, ChunkSize)) == 0) { break; } _valueOffset = 0; } } else { // read what is reader.Value string value = _reader.Value; int decodedCharsCount = _decoder.Decode(value, _valueOffset, value.Length - _valueOffset); _valueOffset += decodedCharsCount; if (_decoder.IsFull) { return _decoder.DecodedCount; } } _valueOffset = 0; // move to next textual node in the element content; throw on sub elements if (!MoveToNextContentNode(true)) { _isEnd = true; return _decoder.DecodedCount; } } } private int ReadElementContentAsBinary(byte[] buffer, int index, int count) { if (count == 0) { return 0; } // read binary int decoded = ReadContentAsBinary(buffer, index, count); if (decoded > 0) { return decoded; } // if 0 bytes returned check if we are on a closing EndElement, throw exception if not if (_reader.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_InvalidNodeType, _reader.NodeType.ToString(), _reader as IXmlLineInfo); } // move off the EndElement _reader.Read(); _state = State.None; return 0; } private bool MoveToNextContentNode(bool moveIfOnContentNode) { do { switch (_reader.NodeType) { case XmlNodeType.Attribute: return !moveIfOnContentNode; case XmlNodeType.Text: case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: case XmlNodeType.CDATA: if (!moveIfOnContentNode) { return true; } break; case XmlNodeType.ProcessingInstruction: case XmlNodeType.Comment: case XmlNodeType.EndEntity: // skip comments, pis and end entity nodes break; case XmlNodeType.EntityReference: if (_reader.CanResolveEntity) { _reader.ResolveEntity(); break; } goto default; default: return false; } moveIfOnContentNode = false; } while (_reader.Read()); return false; } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedGlobalForwardingRulesClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient> mockGrpcClient = new moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlobalForwardingRuleRequest request = new GetGlobalForwardingRuleRequest { Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = ForwardingRule.Types.PscConnectionStatus.UndefinedPscConnectionStatus, Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = ForwardingRule.Types.IpVersion.UndefinedIpVersion, BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = ForwardingRule.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme, ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = ForwardingRule.Types.IPProtocol.Udp, AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = ForwardingRule.Types.NetworkTier.Standard, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GlobalForwardingRulesClient client = new GlobalForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient> mockGrpcClient = new moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlobalForwardingRuleRequest request = new GetGlobalForwardingRuleRequest { Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = ForwardingRule.Types.PscConnectionStatus.UndefinedPscConnectionStatus, Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = ForwardingRule.Types.IpVersion.UndefinedIpVersion, BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = ForwardingRule.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme, ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = ForwardingRule.Types.IPProtocol.Udp, AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = ForwardingRule.Types.NetworkTier.Standard, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ForwardingRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GlobalForwardingRulesClient client = new GlobalForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ForwardingRule responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient> mockGrpcClient = new moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlobalForwardingRuleRequest request = new GetGlobalForwardingRuleRequest { Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = ForwardingRule.Types.PscConnectionStatus.UndefinedPscConnectionStatus, Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = ForwardingRule.Types.IpVersion.UndefinedIpVersion, BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = ForwardingRule.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme, ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = ForwardingRule.Types.IPProtocol.Udp, AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = ForwardingRule.Types.NetworkTier.Standard, }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); GlobalForwardingRulesClient client = new GlobalForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule response = client.Get(request.Project, request.ForwardingRule); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient> mockGrpcClient = new moq::Mock<GlobalForwardingRules.GlobalForwardingRulesClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForGlobalOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetGlobalForwardingRuleRequest request = new GetGlobalForwardingRuleRequest { Project = "projectaa6ff846", ForwardingRule = "forwarding_rule51d5478e", }; ForwardingRule expectedResponse = new ForwardingRule { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", CreationTimestamp = "creation_timestamp235e59a1", IPAddress = "I_p_addressf1537179", Ports = { "ports9860f047", }, IsMirroringCollector = false, Region = "regionedb20d96", LabelFingerprint = "label_fingerprint06ccff3a", PscConnectionStatus = ForwardingRule.Types.PscConnectionStatus.UndefinedPscConnectionStatus, Target = "targetaefbae42", PortRange = "port_ranged4420f7d", ServiceDirectoryRegistrations = { new ForwardingRuleServiceDirectoryRegistration(), }, Network = "networkd22ce091", Fingerprint = "fingerprint009e6052", PscConnectionId = 1768355415909345202UL, IpVersion = ForwardingRule.Types.IpVersion.UndefinedIpVersion, BackendService = "backend_serviceed490d45", Subnetwork = "subnetworkf55bf572", ServiceName = "service_named5df05d5", LoadBalancingScheme = ForwardingRule.Types.LoadBalancingScheme.UndefinedLoadBalancingScheme, ServiceLabel = "service_label5f95d0c0", Description = "description2cf9da67", AllPorts = false, SelfLink = "self_link7e87f12d", MetadataFilters = { new MetadataFilter(), }, IPProtocol = ForwardingRule.Types.IPProtocol.Udp, AllowGlobalAccess = false, Labels = { { "key8a0b6e3c", "value60c16320" }, }, NetworkTier = ForwardingRule.Types.NetworkTier.Standard, }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<ForwardingRule>(stt::Task.FromResult(expectedResponse), null, null, null, null)); GlobalForwardingRulesClient client = new GlobalForwardingRulesClientImpl(mockGrpcClient.Object, null); ForwardingRule responseCallSettings = await client.GetAsync(request.Project, request.ForwardingRule, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); ForwardingRule responseCancellationToken = await client.GetAsync(request.Project, request.ForwardingRule, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Client.Services { using System; using System.Collections.Generic; using System.Collections; using System.Diagnostics; using System.Reflection; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Client.Services; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Services; using Apache.Ignite.Core.Platform; using Apache.Ignite.Core.Services; /// <summary> /// Services client. /// </summary> internal class ServicesClient : IServicesClient { /** */ [Flags] private enum ServiceFlags : byte { KeepBinary = 1, // ReSharper disable once UnusedMember.Local HasParameterTypes = 2 } /** */ private readonly IgniteClient _ignite; /** */ private readonly IClientClusterGroup _clusterGroup; /** */ private readonly bool _keepBinary; /** */ private readonly bool _serverKeepBinary; /** */ private readonly TimeSpan _timeout; /// <summary> /// Initializes a new instance of <see cref="ServicesClient"/> class. /// </summary> public ServicesClient( IgniteClient ignite, IClientClusterGroup clusterGroup = null, bool keepBinary = false, bool serverKeepBinary = false, TimeSpan timeout = default(TimeSpan)) { Debug.Assert(ignite != null); _ignite = ignite; _clusterGroup = clusterGroup; _keepBinary = keepBinary; _serverKeepBinary = serverKeepBinary; _timeout = timeout; } /** <inheritdoc /> */ public IClientClusterGroup ClusterGroup { get { return _clusterGroup ?? _ignite.GetCluster(); } } /** <inheritdoc /> */ public T GetServiceProxy<T>(string serviceName) where T : class { return GetServiceProxy<T>(serviceName, null); } /** <inheritdoc /> */ public T GetServiceProxy<T>(string serviceName, IServiceCallContext callCtx) where T : class { IgniteArgumentCheck.NotNullOrEmpty(serviceName, "name"); IgniteArgumentCheck.Ensure(callCtx == null || callCtx is ServiceCallContext, "callCtx", "custom implementation of " + typeof(ServiceCallContext).Name + " is not supported." + " Please use " + typeof(ServiceCallContextBuilder).Name + " to create it."); var platformType = GetServiceDescriptor(serviceName).PlatformType; IDictionary callAttrs = callCtx == null ? null : ((ServiceCallContext) callCtx).Values(); return ServiceProxyFactory<T>.CreateProxy( (method, args) => InvokeProxyMethod(serviceName, method, args, platformType, callAttrs) ); } /** <inheritdoc /> */ public ICollection<IClientServiceDescriptor> GetServiceDescriptors() { return _ignite.Socket.DoOutInOp( ClientOp.ServiceGetDescriptors, ctx => { }, ctx => { var cnt = ctx.Reader.ReadInt(); var res = new List<IClientServiceDescriptor>(cnt); for (var i = 0; i < cnt; i++) res.Add(new ClientServiceDescriptor(ctx.Reader)); return res; }); } /** <inheritdoc /> */ public IClientServiceDescriptor GetServiceDescriptor(string serviceName) { return _ignite.Socket.DoOutInOp( ClientOp.ServiceGetDescriptor, ctx => ctx.Writer.WriteString(serviceName), ctx => new ClientServiceDescriptor(ctx.Reader)); } /** <inheritdoc /> */ public IServicesClient WithKeepBinary() { return new ServicesClient(_ignite, _clusterGroup, true, _serverKeepBinary, _timeout); } /** <inheritdoc /> */ public IServicesClient WithServerKeepBinary() { return new ServicesClient(_ignite, _clusterGroup, _keepBinary, true, _timeout); } /// <summary> /// Invokes the proxy method. /// </summary> private object InvokeProxyMethod(string serviceName, MethodBase method, object[] args, PlatformType platformType, IDictionary callAttrs) { return _ignite.Socket.DoOutInOp(ClientOp.ServiceInvoke, ctx => { var w = ctx.Writer; w.WriteString(serviceName); w.WriteByte(_serverKeepBinary ? (byte) ServiceFlags.KeepBinary : (byte) 0); w.WriteLong((long) _timeout.TotalMilliseconds); if (_clusterGroup != null) { var nodes = _clusterGroup.GetNodes(); if (nodes.Count == 0) { throw new IgniteClientException("Cluster group is empty"); } w.WriteInt(nodes.Count); foreach (var node in nodes) { BinaryUtils.WriteGuid(node.Id, ctx.Stream); } } else { w.WriteInt(0); } w.WriteString(method.Name); ServiceProxySerializer.WriteMethodArguments(w, null, args, platformType); if (ctx.Features.HasFeature(ClientBitmaskFeature.ServiceInvokeCtx)) { w.WriteDictionary(callAttrs); } else if (callAttrs != null) { throw new IgniteClientException( "Passing caller context to the service is not supported by the server"); } }, ctx => { var reader = _keepBinary ? ctx.Marshaller.StartUnmarshal(ctx.Stream, BinaryMode.ForceBinary) : ctx.Reader; return reader.ReadObject<object>(); }); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using ME; using UnityEditor; using UnityEngine; using UnityEngine.UI.Windows.Plugins.Flow; using System.Text.RegularExpressions; using FD = UnityEngine.UI.Windows.Plugins.Flow.Data; namespace UnityEngine.UI.Windows.Plugins.FlowCompiler { public class Tpl { public class Info { public string baseNamespace; public string classname; public string baseClassname; public string screenName; public string classnameFile { get { return this.classname + ".cs"; } } public string baseClassnameFile { get { return this.baseClassname + ".cs"; } } public string classnameWithNamespace { get { return this.baseNamespace + "." + this.screenName; } } public Info(FD.FlowWindow window) { this.baseNamespace = window.compiledNamespace; this.classname = window.compiledDerivedClassName; this.baseClassname = window.compiledBaseClassName; this.screenName = window.directory; } public Info(string baseNamespace, string classname, string baseClassname, string screenName) { this.baseNamespace = baseNamespace; this.classname = classname; this.baseClassname = baseClassname; this.screenName = screenName; } public string Replace(string replace, System.Func<string, string> predicate = null) { replace = replace.Replace("{CLASS_NAME}", this.classname); replace = replace.Replace("{BASE_CLASS_NAME}", this.baseClassname); replace = replace.Replace("{NAMESPACE_NAME}", this.baseNamespace); replace = replace.Replace("{CLASS_NAME_WITH_NAMESPACE}", this.classnameWithNamespace); if (predicate != null) replace = predicate(replace); return replace; } } public static string ReplaceText(string text, Info oldInfo, Info newInfo) { return FlowTemplateGenerator.ReplaceText(text, oldInfo, newInfo); } public static string GetNamespace() { return FlowCompilerSystem.currentNamespace; } public static string GetBaseClassName(FD.FlowWindow flowWindow) { return flowWindow.directory.UppercaseFirst() + "ScreenBase"; } public static string GetDerivedClassName(FD.FlowWindow flowWindow) { return flowWindow.directory.UppercaseFirst() + "Screen"; } public static string GetNamespace(FD.FlowWindow window) { return Tpl.GetNamespace() + IO.GetRelativePath(window, "."); } public static string GenerateTransitionMethods(FD.FlowWindow window) { var flowData = FlowSystem.GetData(); var transitions = flowData.windowAssets.Where(w => window.attachItems.Any((item) => item.targetId == w.id) && w.CanCompiled() && !w.IsContainer()); var result = string.Empty; foreach (var each in transitions) { var className = each.directory; var classNameWithNamespace = Tpl.GetNamespace(each) + "." + Tpl.GetDerivedClassName(each); result += FlowTemplateGenerator.GenerateWindowLayoutTransitionMethod(window, each, className, classNameWithNamespace); WindowSystem.CollectCallVariations(each.GetScreen(), (listTypes, listNames) => { result += FlowTemplateGenerator.GenerateWindowLayoutTransitionTypedMethod(window, each, className, classNameWithNamespace, listTypes, listNames); }); } // Make FlowDefault() method if exists var c = 0; var everyPlatformHasUniqueName = false; foreach (var attachItem in window.attachItems) { var attachId = attachItem.targetId; var attachedWindow = FlowSystem.GetWindow(attachId); var tmp = UnityEditor.UI.Windows.Plugins.Flow.Flow.IsCompilerTransitionAttachedGeneration(window, attachedWindow); if (tmp == true) ++c; } everyPlatformHasUniqueName = c > 1; foreach (var attachItem in window.attachItems) { var attachId = attachItem.targetId; var attachedWindow = FlowSystem.GetWindow(attachId); if (attachedWindow.IsShowDefault() == true) { result += FlowTemplateGenerator.GenerateWindowLayoutTransitionMethodDefault(); } result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionAttachedGeneration(window, attachedWindow, everyPlatformHasUniqueName); WindowSystem.CollectCallVariations(attachedWindow.GetScreen(), (listTypes, listNames) => { result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionTypedAttachedGeneration(window, attachedWindow, everyPlatformHasUniqueName, listTypes, listNames); }); } // Run addons transition logic result += UnityEditor.UI.Windows.Plugins.Flow.Flow.OnCompilerTransitionGeneration(window); return result; } } public static class IO { public static void RenameDirectory(string oldPath, string newPath) { oldPath = oldPath.Replace("//", "/"); newPath = newPath.Replace("//", "/"); oldPath = oldPath.Trim('/'); newPath = newPath.Trim('/'); //Debug.Log("MoveAsset: " + oldPath + " => " + newPath); AssetDatabase.MoveAsset(oldPath, newPath); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); } public static void RenameFile(string oldFile, string newFile) { oldFile = oldFile.Replace("//", "/"); newFile = newFile.Replace("//", "/"); //Debug.Log("RenameAsset: " + oldFile + " => " + newFile); //Debug.Log(AssetDatabase.RenameAsset(oldFile, newFile)); System.IO.File.Move(oldFile, newFile); AssetDatabase.ImportAsset(newFile); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); } public static void ReplaceInFiles(string path, System.Func<MonoScript, bool> predicate, System.Func<string, string> replace) { #if !UNITY_WEBPLAYER try { path = path.Trim('/'); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); var scripts = AssetDatabase.FindAssets("t:MonoScript", new string[] { path }) .Select(file => AssetDatabase.GUIDToAssetPath(file)) .Select(file => AssetDatabase.LoadAssetAtPath(file, typeof(MonoScript))) .OfType<MonoScript>() .Where(predicate); foreach (var each in scripts) { var filepath = AssetDatabase.GetAssetPath(each); /*var lines = File.ReadAllLines(filepath); var writer = new StreamWriter(filepath); foreach (var line in lines) { writer.WriteLine(replace(line)); } writer.Dispose();*/ File.WriteAllText(filepath, replace(File.ReadAllText(filepath))); } } catch (Exception e) { Debug.LogException(e); } #endif } public static void CreateFile(string path, string filename, string content, bool rewrite = true) { #if !UNITY_WEBPLAYER IO.CreateDirectory(path, string.Empty); path = path.Trim('/'); filename = filename.Trim('/'); var filepath = Path.Combine(path, filename); filepath = filepath.Replace("//", "/"); if (File.Exists(filepath) == false || rewrite == true) { File.WriteAllText(filepath, content); AssetDatabase.ImportAsset(filepath); } #endif } public static void CreateDirectory(string root, string folder) { #if !UNITY_WEBPLAYER folder = folder.Trim('/'); root = root.Trim('/'); var path = Path.Combine(root, folder); path = path.Replace("//", "/"); if (Directory.Exists(path) == false) { Directory.CreateDirectory(path); AssetDatabase.Refresh(); } #endif } private static IEnumerable<FD.FlowWindow> GetParentContainers(FD.FlowWindow window, IEnumerable<FD.FlowWindow> containers) { var parent = containers.FirstOrDefault(where => where.attachItems.Any((item) => item.targetId == window.id)); while (parent != null) { yield return parent; parent = containers.FirstOrDefault(where => where.attachItems.Any((item) => item.targetId == parent.id)); } } public static string GetRelativePath(FD.FlowWindow window, string token) { var result = GetParentContainers(window, FlowSystem.GetContainers()) .Reverse() .Select(w => w.directory) .Aggregate(string.Empty, (total, path) => total + token + path); if (string.IsNullOrEmpty(result) == true) { result = token + FlowDatabase.OTHER_NAME; } result += token + window.directory; return result; } } } namespace UnityEngine.UI.Windows.Plugins.FlowCompiler { public static class FlowCompilerSystem { public static string currentNamespace; private static string currentProject; private static string currentProjectDirectory; #if UNITY_EDITOR #region OLD /* private static bool CompiledInfoIsInvalid( FD.FlowWindow flowWindow ) { return GetBaseClassName( flowWindow ) != flowWindow.compiledBaseClassName || GetNamespace( flowWindow ) != flowWindow.compiledNamespace; } private static void UpdateInheritedClasses( string oldBaseClassName, string newBaseClassName, string oldDerivedClassName, string newDerivedClassName, string oldNamespace, string newNamespace ) { if ( string.IsNullOrEmpty( oldBaseClassName ) || string.IsNullOrEmpty( newBaseClassName ) ) { return; } var oldFullClassPath = oldNamespace + oldBaseClassName; var newFullClassPath = newNamespace + newBaseClassName; AssetDatabase.StartAssetEditing(); try { var scripts = AssetDatabase.FindAssets( "t:MonoScript" ) .Select( _ => AssetDatabase.GUIDToAssetPath( _ ) ) .Select( _ => AssetDatabase.LoadAssetAtPath( _, typeof( MonoScript ) ) ) .OfType<MonoScript>() .Where( _ => _.text.Contains( oldBaseClassName ) || _.text.Contains( oldDerivedClassName ) || _.text.Contains( oldNamespace ) ) .Where( _ => _.name != newBaseClassName ); foreach ( var each in scripts ) { var path = AssetDatabase.GetAssetPath( each ); var lines = File.ReadAllLines( path ); var writer = new StreamWriter( path ); foreach ( var line in lines ) { writer.WriteLine( line.Replace( oldFullClassPath, newFullClassPath ) .Replace( oldNamespace, newNamespace ) .Replace( oldBaseClassName, newBaseClassName ) .Replace( oldDerivedClassName, newDerivedClassName ) ); } writer.Dispose(); } } catch ( Exception e ) { Debug.LogException( e ); } AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh( ImportAssetOptions.ForceUpdate ); } private static void GenerateUIWindow( string fullpath, FD.FlowWindow window, bool recompile = false ) { var isCompiledInfoInvalid = window.compiled && CompiledInfoIsInvalid( window ); if ( window.compiled == false || recompile == true || isCompiledInfoInvalid ) { var baseClassName = GetBaseClassName( window ); var derivedClassName = GetDerivedClassName( window ); var classNamespace = GetNamespace( window ); var baseClassTemplate = FlowTemplateGenerator.GenerateWindowLayoutBaseClass( baseClassName, classNamespace, GenerateTransitionMethods( window ) ); var derivedClassTemplate = FlowTemplateGenerator.GenerateWindowLayoutDerivedClass( derivedClassName, baseClassName, classNamespace ); #if !UNITY_WEBPLAYER var baseClassPath = ( fullpath + "/" + baseClassName + ".cs" ).Replace( "//", "/" ); var derivedClassPath = ( fullpath + "/" + derivedClassName + ".cs" ).Replace( "//", "/" ); #endif if ( baseClassTemplate != null && derivedClassTemplate != null ) { IO.CreateDirectory( fullpath, string.Empty ); IO.CreateDirectory( fullpath, FlowDatabase.COMPONENTS_FOLDER ); IO.CreateDirectory( fullpath, FlowDatabase.LAYOUT_FOLDER ); IO.CreateDirectory( fullpath, FlowDatabase.SCREENS_FOLDER ); #if !UNITY_WEBPLAYER Directory.CreateDirectory( fullpath ); File.WriteAllText( baseClassPath, baseClassTemplate ); if ( !File.Exists( derivedClassPath ) ) { File.WriteAllText( derivedClassPath, derivedClassTemplate ); AssetDatabase.ImportAsset( derivedClassName ); } AssetDatabase.ImportAsset( baseClassPath ); #endif } else { return; } var oldBaseClassName = window.compiledBaseClassName; var newBaseClassName = baseClassName; var oldDerivedClassName = window.compiledDerivedClassName; var newDerivedClassName = derivedClassName; var oldNamespace = window.compiledNamespace; window.compiledBaseClassName = baseClassName; window.compiledDerivedClassName = derivedClassName; window.compiledNamespace = classNamespace; var newNamespace = window.compiledNamespace; window.compiledDirectory = fullpath; window.compiled = true; AssetDatabase.Refresh( ImportAssetOptions.ForceUpdate ); if ( isCompiledInfoInvalid ) { EditorApplication.delayCall += () => UpdateInheritedClasses( oldBaseClassName, newBaseClassName, oldDerivedClassName, newDerivedClassName, oldNamespace, newNamespace ); } } } public static void GenerateUI( string pathToData, bool recompile = false, Func<FD.FlowWindow, bool> predicate = null ) { var filename = Path.GetFileName( pathToData ); var directory = pathToData.Replace( filename, "" ); currentProject = Path.GetFileNameWithoutExtension( pathToData ); var basePath = directory + currentProject; CreateDirectory( basePath, string.Empty ); CreateDirectory( basePath, FlowDatabase.OTHER_NAME ); AssetDatabase.StartAssetEditing(); predicate = predicate ?? delegate { return true; }; try { foreach ( var each in FlowSystem.GetWindows().Where( _ => !_.isDefaultLink && predicate( _ ) ) ) { var relativePath = GetRelativePath( each, "/" ); if ( !string.IsNullOrEmpty( each.directory ) ) { CreateDirectory( basePath, relativePath ); } GenerateUIWindow( basePath + relativePath + "/", each, recompile ); } } catch ( Exception e ) { Debug.LogException( e ); } AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh( ImportAssetOptions.ForceUpdate ); }*/ #endregion private static void GenerateWindow(string newPath, FD.FlowWindow window, bool recompile, bool minimalScriptsSize) { if (window.compiled == true && recompile == false) return; var oldPath = window.compiledDirectory; var newInfo = new Tpl.Info(Tpl.GetNamespace(window), Tpl.GetDerivedClassName(window), Tpl.GetBaseClassName(window), window.directory); var oldInfo = new Tpl.Info(window); if (string.IsNullOrEmpty(oldPath) == true) { oldPath = newPath; } var path = oldPath; if (window.compiled == true && (oldPath != newPath)) { // If window is moving and compiled - just rename // Replace in files IO.ReplaceInFiles(FlowCompilerSystem.currentProjectDirectory, (file) => { var text = file.text; return text.Contains(oldInfo.baseNamespace); }, (text) => { return Tpl.ReplaceText(text, oldInfo, newInfo); }); // Rename base class name IO.RenameFile(oldPath + oldInfo.baseClassnameFile, oldPath + newInfo.baseClassnameFile); // Rename derived class name IO.RenameFile(oldPath + oldInfo.classnameFile, oldPath + newInfo.classnameFile); // Rename main folder IO.RenameDirectory(oldPath, newPath); path = newPath; } // Rebuild without rename //Debug.Log(window.title + " :: REBUILD BASE :: " + path); IO.CreateDirectory(path, string.Empty); IO.CreateDirectory(path, FlowDatabase.COMPONENTS_FOLDER); IO.CreateDirectory(path, FlowDatabase.LAYOUT_FOLDER); IO.CreateDirectory(path, FlowDatabase.SCREENS_FOLDER); var baseClassTemplate = FlowTemplateGenerator.GenerateWindowLayoutBaseClass(newInfo.baseClassname, newInfo.baseNamespace, Tpl.GenerateTransitionMethods(window)); var derivedClassTemplate = FlowTemplateGenerator.GenerateWindowLayoutDerivedClass(newInfo.classname, newInfo.baseClassname, newInfo.baseNamespace); if (minimalScriptsSize == true) { baseClassTemplate = FlowCompilerSystem.Compress(baseClassTemplate); } if (baseClassTemplate != null && derivedClassTemplate != null) { IO.CreateFile(path, newInfo.baseClassnameFile, baseClassTemplate, rewrite: true); IO.CreateFile(path, newInfo.classnameFile, derivedClassTemplate, rewrite: false); } window.compiledNamespace = newInfo.baseNamespace; window.compiledScreenName = newInfo.screenName; window.compiledBaseClassName = newInfo.baseClassname; window.compiledDerivedClassName = newInfo.classname; window.compiledDirectory = path; window.compiled = true; } private static string Compress(string data) { var symbols = new string[] { ",", "{", "}", @"\(", @"\)", "==", ">=", "<=", "=>", "-", @"\+", "--", @"\+\+", ">", "<", "=", ":", @"\?" }; data = data.Replace("\t", string.Empty); var blockComments = @"/\*(.*?)\*/"; var lineComments = @"//(.*?)\r?\n"; var strings = @"""((\\[^\n]|[^""\n])*)"""; var verbatimStrings = @"@(""[^""]*"")+"; data = Regex.Replace(data, blockComments + "|" + lineComments + "|" + strings + "|" + verbatimStrings, me => { if (me.Value.StartsWith("/*") || me.Value.StartsWith("//")) return me.Value.StartsWith("//") ? Environment.NewLine : ""; // Keep the literal strings return me.Value; }, RegexOptions.Singleline); data = data.Replace("\t", string.Empty); data = data.Replace("\r\n", string.Empty); data = data.Replace("\r", string.Empty); data = data.Replace("\n", string.Empty); foreach (var symbol in symbols) { data = Regex.Replace(data, @"(\s?" + symbol + @"\s?)", symbol.Replace(@"\", string.Empty)); } return data; } private static void Generate(string pathToData, bool recompile, bool minimalScriptsSize, System.Func<FD.FlowWindow, bool> predicate) { var filename = Path.GetFileName(pathToData); if (string.IsNullOrEmpty(pathToData) == true) { throw new Exception("`pathToData` is wrong: " + pathToData + ". Filename: " + filename); } var directory = pathToData.Replace(filename, string.Empty); FlowCompilerSystem.currentProject = Path.GetFileNameWithoutExtension(pathToData); FlowCompilerSystem.currentProjectDirectory = directory; var basePath = directory + FlowCompilerSystem.currentProject; IO.CreateDirectory(basePath, string.Empty); IO.CreateDirectory(basePath, FlowDatabase.OTHER_NAME); predicate = predicate ?? delegate { return true; }; AssetDatabase.StartAssetEditing(); { try { var windows = FlowSystem.GetWindows().Where(w => w.CanCompiled() && predicate(w)); foreach (var each in windows) { var relativePath = IO.GetRelativePath(each, "/"); FlowCompilerSystem.GenerateWindow(basePath + relativePath + "/", each, recompile, minimalScriptsSize); } } catch (Exception e) { Debug.LogException(e); } } AssetDatabase.StopAssetEditing(); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); FlowSystem.SetDirty(); FlowSystem.Save(); } #region VARIANTS public static void GenerateByTag(string pathToData, int tag, bool recompile = false, bool minimalScriptsSize = false) { FlowCompilerSystem.Generate(pathToData, recompile, minimalScriptsSize, flowWindow => flowWindow.tags.Contains(tag)); } public static void GenerateByTags(string pathToData, int[] tags, bool recompile = false, bool minimalScriptsSize = false) { FlowCompilerSystem.Generate(pathToData, recompile, minimalScriptsSize, flowWindow => { foreach (var tag in flowWindow.tags) { if (tags.Contains(tag) == true) return true; } return false; }); } public static void GenerateByWindow(string pathToData, bool recompile = false, bool minimalScriptsSize = false, FD.FlowWindow window = null) { FlowCompilerSystem.Generate(pathToData, recompile, minimalScriptsSize, flowWindow => flowWindow == window); } public static void Generate(string pathToData, bool recompile = false, bool minimalScriptsSize = false) { FlowCompilerSystem.Generate(pathToData, recompile, minimalScriptsSize, null); } #endregion #endif } }
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Allocation; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Framework.Graphics; using osu.Framework.IO.Stores; using osuTK; using osuTK.Graphics; using osu.Framework.Caching; namespace osu.Game.Graphics { public class SpriteIcon : CompositeDrawable { private Sprite spriteShadow; private Sprite spriteMain; private Cached layout = new Cached(); private Container shadowVisibility; private FontStore store; [BackgroundDependencyLoader] private void load(FontStore store) { this.store = store; InternalChildren = new Drawable[] { shadowVisibility = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, Child = spriteShadow = new Sprite { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit, Y = 2, Colour = new Color4(0f, 0f, 0f, 0.2f), }, Alpha = shadow ? 1 : 0, }, spriteMain = new Sprite { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Both, FillMode = FillMode.Fit }, }; updateTexture(); } protected override void LoadComplete() { base.LoadComplete(); updateTexture(); } private FontAwesome loadedIcon; private void updateTexture() { var loadableIcon = icon; if (loadableIcon == loadedIcon) return; var texture = store.Get(((char)loadableIcon).ToString()); spriteMain.Texture = texture; spriteShadow.Texture = texture; if (Size == Vector2.Zero) Size = new Vector2(texture?.DisplayWidth ?? 0, texture?.DisplayHeight ?? 0); loadedIcon = loadableIcon; } public override bool Invalidate(Invalidation invalidation = Invalidation.All, Drawable source = null, bool shallPropagate = true) { if ((invalidation & Invalidation.Colour) > 0 && Shadow) layout.Invalidate(); return base.Invalidate(invalidation, source, shallPropagate); } protected override void Update() { if (!layout.IsValid) { //adjust shadow alpha based on highest component intensity to avoid muddy display of darker text. //squared result for quadratic fall-off seems to give the best result. var avgColour = (Color4)DrawColourInfo.Colour.AverageColour; spriteShadow.Alpha = (float)Math.Pow(Math.Max(Math.Max(avgColour.R, avgColour.G), avgColour.B), 2); layout.Validate(); } } private bool shadow; public bool Shadow { get => shadow; set { shadow = value; if (shadowVisibility != null) shadowVisibility.Alpha = value ? 1 : 0; } } private FontAwesome icon; public FontAwesome Icon { get => icon; set { if (icon == value) return; icon = value; if (LoadState == LoadState.Loaded) updateTexture(); } } } public enum FontAwesome { fa_500px = 0xf26e, fa_address_book = 0xf2b9, fa_address_book_o = 0xf2ba, fa_address_card = 0xf2bb, fa_address_card_o = 0xf2bc, fa_adjust = 0xf042, fa_adn = 0xf170, fa_align_center = 0xf037, fa_align_justify = 0xf039, fa_align_left = 0xf036, fa_align_right = 0xf038, fa_amazon = 0xf270, fa_ambulance = 0xf0f9, fa_american_sign_language_interpreting = 0xf2a3, fa_anchor = 0xf13d, fa_android = 0xf17b, fa_angellist = 0xf209, fa_angle_double_down = 0xf103, fa_angle_double_left = 0xf100, fa_angle_double_right = 0xf101, fa_angle_double_up = 0xf102, fa_angle_down = 0xf107, fa_angle_left = 0xf104, fa_angle_right = 0xf105, fa_angle_up = 0xf106, fa_apple = 0xf179, fa_archive = 0xf187, fa_area_chart = 0xf1fe, fa_arrow_circle_down = 0xf0ab, fa_arrow_circle_left = 0xf0a8, fa_arrow_circle_o_down = 0xf01a, fa_arrow_circle_o_left = 0xf190, fa_arrow_circle_o_right = 0xf18e, fa_arrow_circle_o_up = 0xf01b, fa_arrow_circle_right = 0xf0a9, fa_arrow_circle_up = 0xf0aa, fa_arrow_down = 0xf063, fa_arrow_left = 0xf060, fa_arrow_right = 0xf061, fa_arrow_up = 0xf062, fa_arrows = 0xf047, fa_arrows_alt = 0xf0b2, fa_arrows_h = 0xf07e, fa_arrows_v = 0xf07d, fa_asl_interpreting = 0xf2a3, fa_assistive_listening_systems = 0xf2a2, fa_asterisk = 0xf069, fa_at = 0xf1fa, fa_audio_description = 0xf29e, fa_automobile = 0xf1b9, fa_backward = 0xf04a, fa_balance_scale = 0xf24e, fa_ban = 0xf05e, fa_bandcamp = 0xf2d5, fa_bank = 0xf19c, fa_bar_chart = 0xf080, fa_bar_chart_o = 0xf080, fa_barcode = 0xf02a, fa_bars = 0xf0c9, fa_bath = 0xf2cd, fa_bathtub = 0xf2cd, fa_battery = 0xf240, fa_battery_0 = 0xf244, fa_battery_1 = 0xf243, fa_battery_2 = 0xf242, fa_battery_3 = 0xf241, fa_battery_4 = 0xf240, fa_battery_empty = 0xf244, fa_battery_full = 0xf240, fa_battery_half = 0xf242, fa_battery_quarter = 0xf243, fa_battery_three_quarters = 0xf241, fa_bed = 0xf236, fa_beer = 0xf0fc, fa_behance = 0xf1b4, fa_behance_square = 0xf1b5, fa_bell = 0xf0f3, fa_bell_o = 0xf0a2, fa_bell_slash = 0xf1f6, fa_bell_slash_o = 0xf1f7, fa_bicycle = 0xf206, fa_binoculars = 0xf1e5, fa_birthday_cake = 0xf1fd, fa_bitbucket = 0xf171, fa_bitbucket_square = 0xf172, fa_bitcoin = 0xf15a, fa_black_tie = 0xf27e, fa_blind = 0xf29d, fa_bluetooth = 0xf293, fa_bluetooth_b = 0xf294, fa_bold = 0xf032, fa_bolt = 0xf0e7, fa_bomb = 0xf1e2, fa_book = 0xf02d, fa_bookmark = 0xf02e, fa_bookmark_o = 0xf097, fa_braille = 0xf2a1, fa_briefcase = 0xf0b1, fa_btc = 0xf15a, fa_bug = 0xf188, fa_building = 0xf1ad, fa_building_o = 0xf0f7, fa_bullhorn = 0xf0a1, fa_bullseye = 0xf140, fa_bus = 0xf207, fa_buysellads = 0xf20d, fa_cab = 0xf1ba, fa_calculator = 0xf1ec, fa_calendar = 0xf073, fa_calendar_check_o = 0xf274, fa_calendar_minus_o = 0xf272, fa_calendar_o = 0xf133, fa_calendar_plus_o = 0xf271, fa_calendar_times_o = 0xf273, fa_camera = 0xf030, fa_camera_retro = 0xf083, fa_car = 0xf1b9, fa_caret_down = 0xf0d7, fa_caret_left = 0xf0d9, fa_caret_right = 0xf0da, fa_caret_square_o_down = 0xf150, fa_caret_square_o_left = 0xf191, fa_caret_square_o_right = 0xf152, fa_caret_square_o_up = 0xf151, fa_caret_up = 0xf0d8, fa_cart_arrow_down = 0xf218, fa_cart_plus = 0xf217, fa_cc = 0xf20a, fa_cc_amex = 0xf1f3, fa_cc_diners_club = 0xf24c, fa_cc_discover = 0xf1f2, fa_cc_jcb = 0xf24b, fa_cc_mastercard = 0xf1f1, fa_cc_paypal = 0xf1f4, fa_cc_stripe = 0xf1f5, fa_cc_visa = 0xf1f0, fa_certificate = 0xf0a3, fa_chain = 0xf0c1, fa_chain_broken = 0xf127, fa_check = 0xf00c, fa_check_circle = 0xf058, fa_check_circle_o = 0xf05d, fa_check_square = 0xf14a, fa_check_square_o = 0xf046, fa_chevron_circle_down = 0xf13a, fa_chevron_circle_left = 0xf137, fa_chevron_circle_right = 0xf138, fa_chevron_circle_up = 0xf139, fa_chevron_down = 0xf078, fa_chevron_left = 0xf053, fa_chevron_right = 0xf054, fa_chevron_up = 0xf077, fa_child = 0xf1ae, fa_chrome = 0xf268, fa_circle = 0xf111, fa_circle_o = 0xf10c, fa_circle_o_notch = 0xf1ce, fa_circle_thin = 0xf1db, fa_clipboard = 0xf0ea, fa_clock_o = 0xf017, fa_clone = 0xf24d, fa_close = 0xf00d, fa_cloud = 0xf0c2, fa_cloud_download = 0xf0ed, fa_cloud_upload = 0xf0ee, fa_cny = 0xf157, fa_code = 0xf121, fa_code_fork = 0xf126, fa_codepen = 0xf1cb, fa_codiepie = 0xf284, fa_coffee = 0xf0f4, fa_cog = 0xf013, fa_cogs = 0xf085, fa_columns = 0xf0db, fa_comment = 0xf075, fa_comment_o = 0xf0e5, fa_commenting = 0xf27a, fa_commenting_o = 0xf27b, fa_comments = 0xf086, fa_comments_o = 0xf0e6, fa_compass = 0xf14e, fa_compress = 0xf066, fa_connectdevelop = 0xf20e, fa_contao = 0xf26d, fa_copy = 0xf0c5, fa_copyright = 0xf1f9, fa_creative_commons = 0xf25e, fa_credit_card = 0xf09d, fa_credit_card_alt = 0xf283, fa_crop = 0xf125, fa_crosshairs = 0xf05b, fa_css3 = 0xf13c, fa_cube = 0xf1b2, fa_cubes = 0xf1b3, fa_cut = 0xf0c4, fa_cutlery = 0xf0f5, fa_dashboard = 0xf0e4, fa_dashcube = 0xf210, fa_database = 0xf1c0, fa_deaf = 0xf2a4, fa_deafness = 0xf2a4, fa_dedent = 0xf03b, fa_delicious = 0xf1a5, fa_desktop = 0xf108, fa_deviantart = 0xf1bd, fa_diamond = 0xf219, fa_digg = 0xf1a6, fa_dollar = 0xf155, fa_dot_circle_o = 0xf192, fa_download = 0xf019, fa_dribbble = 0xf17d, fa_drivers_license = 0xf2c2, fa_drivers_license_o = 0xf2c3, fa_dropbox = 0xf16b, fa_drupal = 0xf1a9, fa_edge = 0xf282, fa_edit = 0xf044, fa_eercast = 0xf2da, fa_eject = 0xf052, fa_ellipsis_h = 0xf141, fa_ellipsis_v = 0xf142, fa_empire = 0xf1d1, fa_envelope = 0xf0e0, fa_envelope_o = 0xf003, fa_envelope_open = 0xf2b6, fa_envelope_open_o = 0xf2b7, fa_envelope_square = 0xf199, fa_envira = 0xf299, fa_eraser = 0xf12d, fa_etsy = 0xf2d7, fa_eur = 0xf153, fa_euro = 0xf153, fa_exchange = 0xf0ec, fa_exclamation = 0xf12a, fa_exclamation_circle = 0xf06a, fa_exclamation_triangle = 0xf071, fa_expand = 0xf065, fa_expeditedssl = 0xf23e, fa_external_link = 0xf08e, fa_external_link_square = 0xf14c, fa_eye = 0xf06e, fa_eye_slash = 0xf070, fa_eyedropper = 0xf1fb, fa_fa = 0xf2b4, fa_facebook = 0xf09a, fa_facebook_f = 0xf09a, fa_facebook_official = 0xf230, fa_facebook_square = 0xf082, fa_fast_backward = 0xf049, fa_fast_forward = 0xf050, fa_fax = 0xf1ac, fa_feed = 0xf09e, fa_female = 0xf182, fa_fighter_jet = 0xf0fb, fa_file = 0xf15b, fa_file_archive_o = 0xf1c6, fa_file_audio_o = 0xf1c7, fa_file_code_o = 0xf1c9, fa_file_excel_o = 0xf1c3, fa_file_image_o = 0xf1c5, fa_file_movie_o = 0xf1c8, fa_file_o = 0xf016, fa_file_pdf_o = 0xf1c1, fa_file_photo_o = 0xf1c5, fa_file_picture_o = 0xf1c5, fa_file_powerpoint_o = 0xf1c4, fa_file_sound_o = 0xf1c7, fa_file_text = 0xf15c, fa_file_text_o = 0xf0f6, fa_file_video_o = 0xf1c8, fa_file_word_o = 0xf1c2, fa_file_zip_o = 0xf1c6, fa_files_o = 0xf0c5, fa_film = 0xf008, fa_filter = 0xf0b0, fa_fire = 0xf06d, fa_fire_extinguisher = 0xf134, fa_firefox = 0xf269, fa_first_order = 0xf2b0, fa_flag = 0xf024, fa_flag_checkered = 0xf11e, fa_flag_o = 0xf11d, fa_flash = 0xf0e7, fa_flask = 0xf0c3, fa_flickr = 0xf16e, fa_floppy_o = 0xf0c7, fa_folder = 0xf07b, fa_folder_o = 0xf114, fa_folder_open = 0xf07c, fa_folder_open_o = 0xf115, fa_font = 0xf031, fa_font_awesome = 0xf2b4, fa_fonticons = 0xf280, fa_fort_awesome = 0xf286, fa_forumbee = 0xf211, fa_forward = 0xf04e, fa_foursquare = 0xf180, fa_free_code_camp = 0xf2c5, fa_frown_o = 0xf119, fa_futbol_o = 0xf1e3, fa_gamepad = 0xf11b, fa_gavel = 0xf0e3, fa_gbp = 0xf154, fa_ge = 0xf1d1, fa_gear = 0xf013, fa_gears = 0xf085, fa_genderless = 0xf22d, fa_get_pocket = 0xf265, fa_gg = 0xf260, fa_gg_circle = 0xf261, fa_gift = 0xf06b, fa_git = 0xf1d3, fa_git_square = 0xf1d2, fa_github = 0xf09b, fa_github_alt = 0xf113, fa_github_square = 0xf092, fa_gitlab = 0xf296, fa_gittip = 0xf184, fa_glass = 0xf000, fa_glide = 0xf2a5, fa_glide_g = 0xf2a6, fa_globe = 0xf0ac, fa_google = 0xf1a0, fa_google_plus = 0xf0d5, fa_google_plus_circle = 0xf2b3, fa_google_plus_official = 0xf2b3, fa_google_plus_square = 0xf0d4, fa_google_wallet = 0xf1ee, fa_graduation_cap = 0xf19d, fa_gratipay = 0xf184, fa_grav = 0xf2d6, fa_group = 0xf0c0, fa_h_square = 0xf0fd, fa_hacker_news = 0xf1d4, fa_hand_grab_o = 0xf255, fa_hand_lizard_o = 0xf258, fa_hand_o_down = 0xf0a7, fa_hand_o_left = 0xf0a5, fa_hand_o_right = 0xf0a4, fa_hand_o_up = 0xf0a6, fa_hand_paper_o = 0xf256, fa_hand_peace_o = 0xf25b, fa_hand_pointer_o = 0xf25a, fa_hand_rock_o = 0xf255, fa_hand_scissors_o = 0xf257, fa_hand_spock_o = 0xf259, fa_hand_stop_o = 0xf256, fa_handshake_o = 0xf2b5, fa_hard_of_hearing = 0xf2a4, fa_hashtag = 0xf292, fa_hdd_o = 0xf0a0, fa_header = 0xf1dc, fa_headphones = 0xf025, fa_heart = 0xf004, fa_heart_o = 0xf08a, fa_heartbeat = 0xf21e, fa_history = 0xf1da, fa_home = 0xf015, fa_hospital_o = 0xf0f8, fa_hotel = 0xf236, fa_hourglass = 0xf254, fa_hourglass_1 = 0xf251, fa_hourglass_2 = 0xf252, fa_hourglass_3 = 0xf253, fa_hourglass_end = 0xf253, fa_hourglass_half = 0xf252, fa_hourglass_o = 0xf250, fa_hourglass_start = 0xf251, fa_houzz = 0xf27c, fa_html5 = 0xf13b, fa_i_cursor = 0xf246, fa_id_badge = 0xf2c1, fa_id_card = 0xf2c2, fa_id_card_o = 0xf2c3, fa_ils = 0xf20b, fa_image = 0xf03e, fa_imdb = 0xf2d8, fa_inbox = 0xf01c, fa_indent = 0xf03c, fa_industry = 0xf275, fa_info = 0xf129, fa_info_circle = 0xf05a, fa_inr = 0xf156, fa_instagram = 0xf16d, fa_institution = 0xf19c, fa_internet_explorer = 0xf26b, fa_intersex = 0xf224, fa_ioxhost = 0xf208, fa_italic = 0xf033, fa_joomla = 0xf1aa, fa_jpy = 0xf157, fa_jsfiddle = 0xf1cc, fa_key = 0xf084, fa_keyboard_o = 0xf11c, fa_krw = 0xf159, fa_language = 0xf1ab, fa_laptop = 0xf109, fa_lastfm = 0xf202, fa_lastfm_square = 0xf203, fa_leaf = 0xf06c, fa_leanpub = 0xf212, fa_legal = 0xf0e3, fa_lemon_o = 0xf094, fa_level_down = 0xf149, fa_level_up = 0xf148, fa_life_bouy = 0xf1cd, fa_life_buoy = 0xf1cd, fa_life_ring = 0xf1cd, fa_life_saver = 0xf1cd, fa_lightbulb_o = 0xf0eb, fa_line_chart = 0xf201, fa_link = 0xf0c1, fa_linkedin = 0xf0e1, fa_linkedin_square = 0xf08c, fa_linode = 0xf2b8, fa_linux = 0xf17c, fa_list = 0xf03a, fa_list_alt = 0xf022, fa_list_ol = 0xf0cb, fa_list_ul = 0xf0ca, fa_location_arrow = 0xf124, fa_lock = 0xf023, fa_long_arrow_down = 0xf175, fa_long_arrow_left = 0xf177, fa_long_arrow_right = 0xf178, fa_long_arrow_up = 0xf176, fa_low_vision = 0xf2a8, fa_magic = 0xf0d0, fa_magnet = 0xf076, fa_mail_forward = 0xf064, fa_mail_reply = 0xf112, fa_mail_reply_all = 0xf122, fa_male = 0xf183, fa_map = 0xf279, fa_map_marker = 0xf041, fa_map_o = 0xf278, fa_map_pin = 0xf276, fa_map_signs = 0xf277, fa_mars = 0xf222, fa_mars_double = 0xf227, fa_mars_stroke = 0xf229, fa_mars_stroke_h = 0xf22b, fa_mars_stroke_v = 0xf22a, fa_maxcdn = 0xf136, fa_meanpath = 0xf20c, fa_medium = 0xf23a, fa_medkit = 0xf0fa, fa_meetup = 0xf2e0, fa_meh_o = 0xf11a, fa_mercury = 0xf223, fa_microchip = 0xf2db, fa_microphone = 0xf130, fa_microphone_slash = 0xf131, fa_minus = 0xf068, fa_minus_circle = 0xf056, fa_minus_square = 0xf146, fa_minus_square_o = 0xf147, fa_mixcloud = 0xf289, fa_mobile = 0xf10b, fa_mobile_phone = 0xf10b, fa_modx = 0xf285, fa_money = 0xf0d6, fa_moon_o = 0xf186, fa_mortar_board = 0xf19d, fa_motorcycle = 0xf21c, fa_mouse_pointer = 0xf245, fa_music = 0xf001, fa_navicon = 0xf0c9, fa_neuter = 0xf22c, fa_newspaper_o = 0xf1ea, fa_object_group = 0xf247, fa_object_ungroup = 0xf248, fa_odnoklassniki = 0xf263, fa_odnoklassniki_square = 0xf264, fa_opencart = 0xf23d, fa_openid = 0xf19b, fa_opera = 0xf26a, fa_optin_monster = 0xf23c, fa_outdent = 0xf03b, fa_pagelines = 0xf18c, fa_paint_brush = 0xf1fc, fa_paper_plane = 0xf1d8, fa_paper_plane_o = 0xf1d9, fa_paperclip = 0xf0c6, fa_paragraph = 0xf1dd, fa_paste = 0xf0ea, fa_pause = 0xf04c, fa_pause_circle = 0xf28b, fa_pause_circle_o = 0xf28c, fa_paw = 0xf1b0, fa_paypal = 0xf1ed, fa_pencil = 0xf040, fa_pencil_square = 0xf14b, fa_pencil_square_o = 0xf044, fa_percent = 0xf295, fa_phone = 0xf095, fa_phone_square = 0xf098, fa_photo = 0xf03e, fa_picture_o = 0xf03e, fa_pie_chart = 0xf200, fa_pied_piper = 0xf2ae, fa_pied_piper_alt = 0xf1a8, fa_pied_piper_pp = 0xf1a7, fa_pinterest = 0xf0d2, fa_pinterest_p = 0xf231, fa_pinterest_square = 0xf0d3, fa_plane = 0xf072, fa_play = 0xf04b, fa_play_circle = 0xf144, fa_play_circle_o = 0xf01d, fa_plug = 0xf1e6, fa_plus = 0xf067, fa_plus_circle = 0xf055, fa_plus_square = 0xf0fe, fa_plus_square_o = 0xf196, fa_podcast = 0xf2ce, fa_power_off = 0xf011, fa_print = 0xf02f, fa_product_hunt = 0xf288, fa_puzzle_piece = 0xf12e, fa_qq = 0xf1d6, fa_qrcode = 0xf029, fa_question = 0xf128, fa_question_circle = 0xf059, fa_question_circle_o = 0xf29c, fa_quora = 0xf2c4, fa_quote_left = 0xf10d, fa_quote_right = 0xf10e, fa_ra = 0xf1d0, fa_random = 0xf074, fa_ravelry = 0xf2d9, fa_rebel = 0xf1d0, fa_recycle = 0xf1b8, fa_reddit = 0xf1a1, fa_reddit_alien = 0xf281, fa_reddit_square = 0xf1a2, fa_refresh = 0xf021, fa_registered = 0xf25d, fa_remove = 0xf00d, fa_renren = 0xf18b, fa_reorder = 0xf0c9, fa_repeat = 0xf01e, fa_reply = 0xf112, fa_reply_all = 0xf122, fa_resistance = 0xf1d0, fa_retweet = 0xf079, fa_rmb = 0xf157, fa_road = 0xf018, fa_rocket = 0xf135, fa_rotate_left = 0xf0e2, fa_rotate_right = 0xf01e, fa_rouble = 0xf158, fa_rss = 0xf09e, fa_rss_square = 0xf143, fa_rub = 0xf158, fa_ruble = 0xf158, fa_rupee = 0xf156, fa_s15 = 0xf2cd, fa_safari = 0xf267, fa_save = 0xf0c7, fa_scissors = 0xf0c4, fa_scribd = 0xf28a, fa_search = 0xf002, fa_search_minus = 0xf010, fa_search_plus = 0xf00e, fa_sellsy = 0xf213, fa_send = 0xf1d8, fa_send_o = 0xf1d9, fa_server = 0xf233, fa_share = 0xf064, fa_share_alt = 0xf1e0, fa_share_alt_square = 0xf1e1, fa_share_square = 0xf14d, fa_share_square_o = 0xf045, fa_shekel = 0xf20b, fa_sheqel = 0xf20b, fa_shield = 0xf132, fa_ship = 0xf21a, fa_shirtsinbulk = 0xf214, fa_shopping_bag = 0xf290, fa_shopping_basket = 0xf291, fa_shopping_cart = 0xf07a, fa_shower = 0xf2cc, fa_sign_in = 0xf090, fa_sign_language = 0xf2a7, fa_sign_out = 0xf08b, fa_signal = 0xf012, fa_signing = 0xf2a7, fa_simplybuilt = 0xf215, fa_sitemap = 0xf0e8, fa_skyatlas = 0xf216, fa_skype = 0xf17e, fa_slack = 0xf198, fa_sliders = 0xf1de, fa_slideshare = 0xf1e7, fa_smile_o = 0xf118, fa_snapchat = 0xf2ab, fa_snapchat_ghost = 0xf2ac, fa_snapchat_square = 0xf2ad, fa_snowflake_o = 0xf2dc, fa_soccer_ball_o = 0xf1e3, fa_sort = 0xf0dc, fa_sort_alpha_asc = 0xf15d, fa_sort_alpha_desc = 0xf15e, fa_sort_amount_asc = 0xf160, fa_sort_amount_desc = 0xf161, fa_sort_asc = 0xf0de, fa_sort_desc = 0xf0dd, fa_sort_down = 0xf0dd, fa_sort_numeric_asc = 0xf162, fa_sort_numeric_desc = 0xf163, fa_sort_up = 0xf0de, fa_soundcloud = 0xf1be, fa_space_shuttle = 0xf197, fa_spinner = 0xf110, fa_spoon = 0xf1b1, fa_spotify = 0xf1bc, fa_square = 0xf0c8, fa_square_o = 0xf096, fa_stack_exchange = 0xf18d, fa_stack_overflow = 0xf16c, fa_star = 0xf005, fa_star_half = 0xf089, fa_star_half_empty = 0xf123, fa_star_half_full = 0xf123, fa_star_half_o = 0xf123, fa_star_o = 0xf006, fa_steam = 0xf1b6, fa_steam_square = 0xf1b7, fa_step_backward = 0xf048, fa_step_forward = 0xf051, fa_stethoscope = 0xf0f1, fa_sticky_note = 0xf249, fa_sticky_note_o = 0xf24a, fa_stop = 0xf04d, fa_stop_circle = 0xf28d, fa_stop_circle_o = 0xf28e, fa_street_view = 0xf21d, fa_strikethrough = 0xf0cc, fa_stumbleupon = 0xf1a4, fa_stumbleupon_circle = 0xf1a3, fa_subscript = 0xf12c, fa_subway = 0xf239, fa_suitcase = 0xf0f2, fa_sun_o = 0xf185, fa_superpowers = 0xf2dd, fa_superscript = 0xf12b, fa_support = 0xf1cd, fa_table = 0xf0ce, fa_tablet = 0xf10a, fa_tachometer = 0xf0e4, fa_tag = 0xf02b, fa_tags = 0xf02c, fa_tasks = 0xf0ae, fa_taxi = 0xf1ba, fa_telegram = 0xf2c6, fa_television = 0xf26c, fa_tencent_weibo = 0xf1d5, fa_terminal = 0xf120, fa_text_height = 0xf034, fa_text_width = 0xf035, fa_th = 0xf00a, fa_th_large = 0xf009, fa_th_list = 0xf00b, fa_themeisle = 0xf2b2, fa_thermometer = 0xf2c7, fa_thermometer_0 = 0xf2cb, fa_thermometer_1 = 0xf2ca, fa_thermometer_2 = 0xf2c9, fa_thermometer_3 = 0xf2c8, fa_thermometer_4 = 0xf2c7, fa_thermometer_empty = 0xf2cb, fa_thermometer_full = 0xf2c7, fa_thermometer_half = 0xf2c9, fa_thermometer_quarter = 0xf2ca, fa_thermometer_three_quarters = 0xf2c8, fa_thumb_tack = 0xf08d, fa_thumbs_down = 0xf165, fa_thumbs_o_down = 0xf088, fa_thumbs_o_up = 0xf087, fa_thumbs_up = 0xf164, fa_ticket = 0xf145, fa_times = 0xf00d, fa_times_circle = 0xf057, fa_times_circle_o = 0xf05c, fa_times_rectangle = 0xf2d3, fa_times_rectangle_o = 0xf2d4, fa_tint = 0xf043, fa_toggle_down = 0xf150, fa_toggle_left = 0xf191, fa_toggle_off = 0xf204, fa_toggle_on = 0xf205, fa_toggle_right = 0xf152, fa_toggle_up = 0xf151, fa_trademark = 0xf25c, fa_train = 0xf238, fa_transgender = 0xf224, fa_transgender_alt = 0xf225, fa_trash = 0xf1f8, fa_trash_o = 0xf014, fa_tree = 0xf1bb, fa_trello = 0xf181, fa_tripadvisor = 0xf262, fa_trophy = 0xf091, fa_truck = 0xf0d1, fa_try = 0xf195, fa_tty = 0xf1e4, fa_tumblr = 0xf173, fa_tumblr_square = 0xf174, fa_turkish_lira = 0xf195, fa_tv = 0xf26c, fa_twitch = 0xf1e8, fa_twitter = 0xf099, fa_twitter_square = 0xf081, fa_umbrella = 0xf0e9, fa_underline = 0xf0cd, fa_undo = 0xf0e2, fa_universal_access = 0xf29a, fa_university = 0xf19c, fa_unlink = 0xf127, fa_unlock = 0xf09c, fa_unlock_alt = 0xf13e, fa_unsorted = 0xf0dc, fa_upload = 0xf093, fa_usb = 0xf287, fa_usd = 0xf155, fa_user = 0xf007, fa_user_circle = 0xf2bd, fa_user_circle_o = 0xf2be, fa_user_md = 0xf0f0, fa_user_o = 0xf2c0, fa_user_plus = 0xf234, fa_user_secret = 0xf21b, fa_user_times = 0xf235, fa_users = 0xf0c0, fa_vcard = 0xf2bb, fa_vcard_o = 0xf2bc, fa_venus = 0xf221, fa_venus_double = 0xf226, fa_venus_mars = 0xf228, fa_viacoin = 0xf237, fa_viadeo = 0xf2a9, fa_viadeo_square = 0xf2aa, fa_video_camera = 0xf03d, fa_vimeo = 0xf27d, fa_vimeo_square = 0xf194, fa_vine = 0xf1ca, fa_vk = 0xf189, fa_volume_control_phone = 0xf2a0, fa_volume_down = 0xf027, fa_volume_off = 0xf026, fa_volume_up = 0xf028, fa_warning = 0xf071, fa_wechat = 0xf1d7, fa_weibo = 0xf18a, fa_weixin = 0xf1d7, fa_whatsapp = 0xf232, fa_wheelchair = 0xf193, fa_wheelchair_alt = 0xf29b, fa_wifi = 0xf1eb, fa_wikipedia_w = 0xf266, fa_window_close = 0xf2d3, fa_window_close_o = 0xf2d4, fa_window_maximize = 0xf2d0, fa_window_minimize = 0xf2d1, fa_window_restore = 0xf2d2, fa_windows = 0xf17a, fa_won = 0xf159, fa_wordpress = 0xf19a, fa_wpbeginner = 0xf297, fa_wpexplorer = 0xf2de, fa_wpforms = 0xf298, fa_wrench = 0xf0ad, fa_xing = 0xf168, fa_xing_square = 0xf169, fa_y_combinator = 0xf23b, fa_y_combinator_square = 0xf1d4, fa_yahoo = 0xf19e, fa_yc = 0xf23b, fa_yc_square = 0xf1d4, fa_yelp = 0xf1e9, fa_yen = 0xf157, fa_yoast = 0xf2b1, fa_youtube = 0xf167, fa_youtube_play = 0xf16a, fa_youtube_square = 0xf166, // ruleset icons in circles fa_osu_osu_o = 0xe000, fa_osu_mania_o = 0xe001, fa_osu_fruits_o = 0xe002, fa_osu_taiko_o = 0xe003, // ruleset icons without circles fa_osu_filled_circle = 0xe004, fa_osu_cross_o = 0xe005, fa_osu_logo = 0xe006, fa_osu_chevron_down_o = 0xe007, fa_osu_edit_o = 0xe033, fa_osu_left_o = 0xe034, fa_osu_right_o = 0xe035, fa_osu_charts = 0xe036, fa_osu_solo = 0xe037, fa_osu_multi = 0xe038, fa_osu_gear = 0xe039, // misc icons fa_osu_bat = 0xe008, fa_osu_bubble = 0xe009, fa_osu_bubble_pop = 0xe02e, fa_osu_dice = 0xe011, fa_osu_heart1 = 0xe02f, fa_osu_heart1_break = 0xe030, fa_osu_hot = 0xe031, fa_osu_list_search = 0xe032, //osu! playstyles fa_osu_playstyle_tablet = 0xe02a, fa_osu_playstyle_mouse = 0xe029, fa_osu_playstyle_keyboard = 0xe02b, fa_osu_playstyle_touch = 0xe02c, // osu! difficulties fa_osu_easy_osu = 0xe015, fa_osu_normal_osu = 0xe016, fa_osu_hard_osu = 0xe017, fa_osu_insane_osu = 0xe018, fa_osu_expert_osu = 0xe019, // taiko difficulties fa_osu_easy_taiko = 0xe01a, fa_osu_normal_taiko = 0xe01b, fa_osu_hard_taiko = 0xe01c, fa_osu_insane_taiko = 0xe01d, fa_osu_expert_taiko = 0xe01e, // fruits difficulties fa_osu_easy_fruits = 0xe01f, fa_osu_normal_fruits = 0xe020, fa_osu_hard_fruits = 0xe021, fa_osu_insane_fruits = 0xe022, fa_osu_expert_fruits = 0xe023, // mania difficulties fa_osu_easy_mania = 0xe024, fa_osu_normal_mania = 0xe025, fa_osu_hard_mania = 0xe026, fa_osu_insane_mania = 0xe027, fa_osu_expert_mania = 0xe028, // mod icons fa_osu_mod_perfect = 0xe049, fa_osu_mod_autopilot = 0xe03a, fa_osu_mod_auto = 0xe03b, fa_osu_mod_cinema = 0xe03c, fa_osu_mod_doubletime = 0xe03d, fa_osu_mod_easy = 0xe03e, fa_osu_mod_flashlight = 0xe03f, fa_osu_mod_halftime = 0xe040, fa_osu_mod_hardrock = 0xe041, fa_osu_mod_hidden = 0xe042, fa_osu_mod_nightcore = 0xe043, fa_osu_mod_nofail = 0xe044, fa_osu_mod_relax = 0xe045, fa_osu_mod_spunout = 0xe046, fa_osu_mod_suddendeath = 0xe047, fa_osu_mod_target = 0xe048, fa_osu_mod_bg = 0xe04a, } }
// This file was contributed to the RDL Project under the MIT License. It was // modified as part of merging into the RDL Project. /* The MIT License Copyright (c) 2006 Christian Cunlif and Lionel Cuir of Aulofee Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections; using System.IO; using System.Reflection; using System.Text; using System.Text.RegularExpressions; namespace fyiReporting.RDL { /// <summary> /// This class builds the following from a URL: /// /// .mht file (Web Archive, single file) /// .htm file with dereferenced (absolute) references (Web Page, HTML Only) /// .htm file plus all referenced files in a local subfolder (Web Page, complete) /// .txt file (non-HTML contents of Web Page) /// /// The .mht format is based on RFC2557 /// "compliant Multipart MIME Message (mhtml web archive)" /// http://www.ietf.org/rfc/rfc2557.txt /// </summary> /// <remarks> /// Jeff Atwood /// http://www.codinghorror.com/ /// </remarks> public class MhtBuilder { #region Fields and enum StringBuilder _MhtBuilder; bool _StripScriptFromHtml = false; bool _StripIframeFromHtml = false; bool _AllowRecursion = true; bool _AddWebMark = true; Encoding _ForcedEncoding = null; MhtWebFile _HtmlFile; internal MhtWebClientLocal WebClient = new MhtWebClientLocal(); internal SortedList WebFiles = new SortedList(); const string _MimeFinalBoundaryTag = "----=_NextPart_000_00"; // note that chunk size is equal to maximum line width (expanded = 75 chars) const int _ChunkSize = 57; public enum FileStorage { Memory, DiskPermanent, DiskTemporary } #endregion Fields and enum #region Constructor public MhtBuilder() { _HtmlFile = new MhtWebFile(this); } #endregion Constructor #region Properties /// <summary> /// Add the "Mark of the web" to retrieved HTML content so it can run /// locally on Windows XP SP2 /// </summary> /// <remarks> /// http://www.microsoft.com/technet/prodtechnol/winxppro/maintain/sp2brows.mspx#XSLTsection133121120120 /// </remarks> public bool AddWebMark { get { return this._AddWebMark; } set { this._AddWebMark = value; } } /// <summary> /// allow recursive retrieval of any embedded HTML (typically IFRAME or FRAME) /// turn off to prevent infinite recursion in the case of pages that reference themselves.. /// </summary> public bool AllowRecursiveFileRetrieval { get { return _AllowRecursion; } set { _AllowRecursion = value; } } /// <summary> /// returns the Mime content-type string designation of a mht file /// </summary> public string MhtContentType { get { return "message/rfc822"; } } /// <summary> /// Strip all &lt;IFRAME&gt; blocks from any retrieved HTML /// </summary> public bool StripIframes { get { return this._StripIframeFromHtml; } set { this._StripIframeFromHtml = value; } } /// <summary> /// Strip all &lt;SCRIPT&gt; blocks from any retrieved HTML /// </summary> public bool StripScripts { get { return this._StripScriptFromHtml; } set { this._StripScriptFromHtml = value; } } /// <summary> /// *only* set this if you want to FORCE a specific text encoding for all the HTML pages you're downloading; /// otherwise the text encoding is autodetected, which is generally what you want /// </summary> public Encoding TextEncoding { get { return this._ForcedEncoding; } set { this._ForcedEncoding = value; } } /// <summary> /// Specifies the target Url we want to save /// </summary> public string Url { get { return _HtmlFile.Url; } set { WebFiles.Clear(); _HtmlFile.Url = value; } } #endregion Properties #region Private methods /// <summary> /// Appends a downloaded external binary file to our MhtBuilder using Base64 encoding /// </summary> void AppendMhtBinaryFile(MhtWebFile ef) { AppendMhtBoundary(); AppendMhtLine("Content-Type: " + ef.ContentType); AppendMhtLine("Content-Transfer-Encoding: base64"); AppendMhtLine("Content-Location: " + ef.Url); AppendMhtLine(); // note that chunk size is equal to maximum line width (expanded = 75 chars) int len = ef.DownloadedBytes.Length; if (len <= _ChunkSize) AppendMhtLine(Convert.ToBase64String(ef.DownloadedBytes, 0, len)); else { int i = 0; while ((i + _ChunkSize) < len) { AppendMhtLine(Convert.ToBase64String(ef.DownloadedBytes, i, _ChunkSize)); i += _ChunkSize; } if (i != len) AppendMhtLine(Convert.ToBase64String(ef.DownloadedBytes, i, len - i)); } } /// <summary> /// appends a boundary marker to our MhtBuilder /// </summary> void AppendMhtBoundary() { AppendMhtLine(); AppendMhtLine("--"+ _MimeFinalBoundaryTag); } /// <summary> /// appends a boundary marker to our MhtBuilder /// </summary> void AppendMhtFinalBoundary() { AppendMhtLine(); AppendMhtLine("--" + _MimeFinalBoundaryTag + "--"); } /// <summary> /// Appends a downloaded external file to our MhtBuilder /// </summary> void AppendMhtFile(MhtWebFile ef) { if (ef.WasDownloaded && !ef.WasAppended) { if (ef.IsBinary) AppendMhtBinaryFile(ef); else AppendMhtTextFile(ef); } ef.WasAppended = true; } /// <summary> /// appends all downloaded files (from _ExternalFiles) to our MhtBuilder /// </summary> /// <param name="st">type of storage to use when downloading external files</param> /// <param name="storagePath">path to use for downloaded external files</param> void AppendMhtFiles() { foreach (MhtWebFile ef in WebFiles.Values) AppendMhtFile(ef); AppendMhtFinalBoundary(); } /// <summary> /// appends the Mht header, which includes the root HTML /// </summary> void AppendMhtHeader(MhtWebFile ef) { // clear the stringbuilder contents _MhtBuilder = new StringBuilder(); //AppendMhtLine("From: <Saved by " + Environment.UserName + " on " + Environment.MachineName + ">"); //AppendMhtLine("Subject: " + ef.HtmlTitle); // For the title, reduces its size if too long and removes line breaks if any. string title = ef.HtmlTitle; if (title != null) { if (title.Length > 260) title = title.Substring(0, 260); if (title.IndexOf('\n') != -1) title = title.Replace('\n', ' '); if (title.IndexOf(Environment.NewLine) != -1) title = title.Replace(Environment.NewLine, " "); } AppendMhtLine("From: <Saved by " + Environment.UserName + " on " + Environment.MachineName + ">"); AppendMhtLine("Subject: " + title); AppendMhtLine("Date: " + DateTime.Now.ToString("ddd, dd MMM yyyy HH:mm:ss zzz")); AppendMhtLine("MIME-Version: 1.0"); AppendMhtLine("Content-Type: multipart/related;"); AppendMhtLine(Convert.ToChar(9).ToString() + "type=\"text/html\";"); AppendMhtLine(Convert.ToChar(9).ToString() + "boundary=\"----=_NextPart_000_00\""); AppendMhtLine("X-MimeOLE: Produced by " + this.GetType().ToString() + " " + Assembly.GetExecutingAssembly().GetName().Version.ToString()); AppendMhtLine(""); AppendMhtLine("This is a multi-part message in MIME format."); AppendMhtFile(ef); } /// <summary> /// append a single line, with trailing CRLF, to our MhtBuilder /// </summary> void AppendMhtLine() { _MhtBuilder.Append(Environment.NewLine); } /// <summary> /// append a single line, with trailing CRLF, to our MhtBuilder /// </summary> void AppendMhtLine(string s) { if (s != null) _MhtBuilder.Append(s); _MhtBuilder.Append(Environment.NewLine); } /// <summary> /// Appends a downloaded external text file to our MhtBuilder using Quoted-Printable encoding /// </summary> void AppendMhtTextFile(MhtWebFile ef) { AppendMhtBoundary(); AppendMhtLine("Content-Type: " + ef.ContentType + ";"); AppendMhtLine(Convert.ToChar(9).ToString() + @"charset="" + ef.TextEncoding.WebName + @"""); AppendMhtLine("Content-Transfer-Encoding: quoted-printable"); AppendMhtLine("Content-Location: " + ef.Url); AppendMhtLine(); AppendMhtLine(QuotedPrintableEncode(ef.ToString(), ef.TextEncoding)); } /// <summary> /// returns the root HTML we'll use to generate everything else; /// this is tracked in the _HtmlFile object, which is always FileStorage.Memory /// </summary> void DownloadHtmlFile(string url) { if (url != "") this.Url = url; _HtmlFile.WasAppended = false; _HtmlFile.Download(); if (!_HtmlFile.WasDownloaded) throw new Exception("unable to download '" + this.Url + "': " + _HtmlFile.DownloadException.Message, _HtmlFile.DownloadException); } /// <summary> /// dumps our MhtBuilder as a string and clears it /// </summary> string FinalizeMht() { string s = _MhtBuilder.ToString(); _MhtBuilder = null; return s; } /// <summary> /// dumps our MhtBuilder to disk and clears it /// </summary> void FinalizeMht(string outputFilePath) { StreamWriter writer = new StreamWriter(outputFilePath, false, _HtmlFile.TextEncoding); writer.Write(_MhtBuilder.ToString()); writer.Close(); _MhtBuilder = null; } /// <summary> /// returns true if this path refers to a directory (vs. a filename) /// </summary> bool IsDirectory(string FilePath) { return FilePath.EndsWith(@"\"); } /// <summary> /// ensures that the path, if it contains a filename, matches one of the semicolon delimited /// filetypes provided in fileExtension /// </summary> void ValidateFilename(string FilePath, string fileExtensions) { if (this.IsDirectory(FilePath)) return; string ext = Path.GetExtension(FilePath); if (ext == "") { throw new Exception("The filename provided, '" + Path.GetFileName(FilePath) + "', has no extension. If are specifying a folder, make sure it ends in a trailing slash. The expected file extension(s) are '" + fileExtensions + "'"); } if (!Regex.IsMatch(fileExtensions, ext + "(;|$)", RegexOptions.IgnoreCase)) { throw new Exception("The extension of the filename provided + '" + Path.GetFileName(FilePath) + "', does not have the expected extension(s) '" + fileExtensions + "'"); } } #endregion Private methods #region Public methods /// <summary> /// Generates a string representation of the current URL as a Mht archive file /// using exclusively in-memory storage /// </summary> /// <returns>string representation of MHT file</returns> public string GetPageArchive() { return GetPageArchive(string.Empty); } /// <summary> /// Generates a string representation of the URL as a Mht archive file /// using exclusively in-memory storage /// </summary> /// <param name="url">fully qualified URL you wish to render to Mht</param> /// <returns>string representation of MHT file</returns> public string GetPageArchive(string url) { DownloadHtmlFile(url); // download all references _HtmlFile.DownloadExternalFiles(_AllowRecursion); // build the Mht AppendMhtHeader(_HtmlFile); AppendMhtFiles(); return this.FinalizeMht(); } /// <summary> /// Saves the current URL to disk as a single file Mht archive /// if a folder is provided instead of a filename, the TITLE tag is used to name the file /// </summary> /// <param name="outputFilePath">path to generate to, or filename to generate</param> /// <param name="st">type of storage to use when generating the Mht archive</param> /// <returns>the complete path of the Mht archive file that was generated</returns> public string SavePageArchive(string outputFilePath) { return SavePageArchive(outputFilePath, string.Empty); } /// <summary> /// Saves URL to disk as a single file Mht archive /// if a folder is provided instead of a filename, the TITLE tag is used to name the file /// </summary> /// <param name="outputFilePath">path to generate to, or filename to generate</param> /// <param name="st">type of storage to use when generating the Mht archive</param> /// <param name="url">fully qualified URL you wish to save as Mht</param> /// <returns>the complete path of the Mht archive file that was generated</returns> public string SavePageArchive(string outputFilePath, string url) { ValidateFilename(outputFilePath, ".mht"); DownloadHtmlFile(url); _HtmlFile.DownloadPath = outputFilePath; _HtmlFile.UseHtmlTitleAsFilename = true; // download all references _HtmlFile.DownloadExternalFiles(_AllowRecursion); // build the Mht AppendMhtHeader(_HtmlFile); AppendMhtFiles(); FinalizeMht(Path.ChangeExtension(_HtmlFile.DownloadPath, ".mht")); WebFiles.Clear(); return Path.ChangeExtension(_HtmlFile.DownloadPath, ".mht"); } #endregion Public methods #region Quoted-Printable encoding /// <summary> /// converts a string into Quoted-Printable encoding /// http://www.freesoft.org/CIE/RFC/1521/6.htm /// </summary> string QuotedPrintableEncode(string s, Encoding e) { int lastSpace = 0; int lineLength = 0; int lineBreaks = 0; StringBuilder sb = new StringBuilder(); if (s == null || s.Length == 0) return ""; foreach (char c in s) { int ascii = Convert.ToInt32(c); if (ascii == 61 || ascii > 126) { if (ascii <= 255) { sb.Append("="); sb.Append(Convert.ToString(ascii, 16).ToUpper()); lineLength += 3; } else { // double-byte land.. foreach (byte b in e.GetBytes(c.ToString())) { sb.Append("="); sb.Append(Convert.ToString(b, 16).ToUpper()); lineLength += 3; } } } else { sb.Append(c); lineLength++; if (ascii == 32) lastSpace = sb.Length; } if (lineLength >= 73) { if (lastSpace == 0) { sb.Insert(sb.Length, "=" + Environment.NewLine); lineLength = 0; } else { sb.Insert(lastSpace, "=" + Environment.NewLine); lineLength = sb.Length - lastSpace - 1; } lineBreaks++; lastSpace = 0; } } // if we split the line, have to indicate trailing spaces if (lineBreaks > 0 && sb[sb.Length - 1] == ' ') { sb.Remove(sb.Length - 1, 1); sb.Append("=20"); } return sb.ToString(); } #endregion Quoted-Printable encoding } }
// **************************************************************** // This is free software licensed under the NUnit license. You // may obtain a copy of the license as well as information regarding // copyright ownership at http://nunit.org. // **************************************************************** using System; using System.Collections; using System.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; using NUnit.Core; using NUnit.Util; namespace NUnit.UiKit { /// <summary> /// ColorProgressBar provides a custom progress bar with the /// ability to control the color of the bar and to render itself /// in either solid or segmented style. The bar can be updated /// on the fly and has code to avoid repainting the entire bar /// when that occurs. /// </summary> public class ColorProgressBar : System.Windows.Forms.Control { #region Instance Variables /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// The current progress value /// </summary> private int val = 0; /// <summary> /// The minimum value allowed /// </summary> private int min = 0; /// <summary> /// The maximum value allowed /// </summary> private int max = 100; /// <summary> /// Amount to advance for each step /// </summary> private int step = 1; /// <summary> /// Last segment displayed when displaying asynchronously rather /// than through OnPaint calls. /// </summary> private int lastSegmentCount=0; /// <summary> /// The brush to use in painting the progress bar /// </summary> private Brush foreBrush = null; /// <summary> /// The brush to use in painting the background of the bar /// </summary> private Brush backBrush = null; /// <summary> /// Indicates whether to draw the bar in segments or not /// </summary> private bool segmented = false; #endregion #region Constructors & Disposer public ColorProgressBar() { // This call is required by the Windows.Forms Form Designer. InitializeComponent(); SetStyle(ControlStyles.ResizeRedraw, true); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } this.ReleaseBrushes(); } base.Dispose( disposing ); } #endregion #region Properties [Category("Behavior")] public int Minimum { get { return this.min; } set { if (value <= Maximum) { if (this.min != value) { this.min = value; this.Invalidate(); } } else { throw new ArgumentOutOfRangeException("Minimum", value ,"Minimum must be <= Maximum."); } } } [Category("Behavior")] public int Maximum { get { return this.max; } set { if (value >= Minimum) { if (this.max != value) { this.max = value; this.Invalidate(); } } else { throw new ArgumentOutOfRangeException("Maximum", value ,"Maximum must be >= Minimum."); } } } [Category("Behavior")] public int Step { get { return this.step; } set { if (value <= Maximum && value >= Minimum) { this.step = value; } else { throw new ArgumentOutOfRangeException("Step", value ,"Must fall between Minimum and Maximum inclusive."); } } } [Browsable(false)] private float PercentValue { get { if (0 != Maximum - Minimum) // NRG 05/28/03: Prevent divide by zero return((float)this.val / ((float)Maximum - (float)Minimum)); else return(0); } } [Category("Behavior")] public int Value { get { return this.val; } set { if(value == this.val) return; else if(value <= Maximum && value >= Minimum) { this.val = value; this.Invalidate(); } else { throw new ArgumentOutOfRangeException("Value", value ,"Must fall between Minimum and Maximum inclusive."); } } } [Category("Appearance")] public bool Segmented { get { return segmented; } set { segmented = value; } } #endregion #region Methods protected override void OnCreateControl() { } public void PerformStep() { int newValue = Value + Step; if( newValue > Maximum ) newValue = Maximum; Value = newValue; } protected override void OnBackColorChanged(System.EventArgs e) { base.OnBackColorChanged(e); this.Refresh(); } protected override void OnForeColorChanged(System.EventArgs e) { base.OnForeColorChanged(e); this.Refresh(); } protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); this.lastSegmentCount=0; this.ReleaseBrushes(); PaintBar(e.Graphics); ControlPaint.DrawBorder3D( e.Graphics ,this.ClientRectangle ,Border3DStyle.SunkenOuter); //e.Graphics.Flush(); } private void ReleaseBrushes() { if(foreBrush != null) { foreBrush.Dispose(); backBrush.Dispose(); foreBrush=null; backBrush=null; } } private void AcquireBrushes() { if(foreBrush == null) { foreBrush = new SolidBrush(this.ForeColor); backBrush = new SolidBrush(this.BackColor); } } private void PaintBar(Graphics g) { Rectangle theBar = Rectangle.Inflate(ClientRectangle, -2, -2); int maxRight = theBar.Right-1; this.AcquireBrushes(); if ( segmented ) { int segmentWidth = (int)((float)ClientRectangle.Height * 0.66f); int maxSegmentCount = ( theBar.Width + segmentWidth ) / segmentWidth; //int maxRight = Bar.Right; int newSegmentCount = (int)System.Math.Ceiling(PercentValue*maxSegmentCount); if(newSegmentCount > lastSegmentCount) { theBar.X += lastSegmentCount*segmentWidth; while (lastSegmentCount < newSegmentCount ) { theBar.Width = System.Math.Min( maxRight - theBar.X, segmentWidth - 2 ); g.FillRectangle( foreBrush, theBar ); theBar.X += segmentWidth; lastSegmentCount++; } } else if(newSegmentCount < lastSegmentCount) { theBar.X += newSegmentCount * segmentWidth; theBar.Width = maxRight - theBar.X; g.FillRectangle(backBrush, theBar); lastSegmentCount = newSegmentCount; } } else { //g.FillRectangle( backBrush, theBar ); theBar.Width = theBar.Width * val / max; g.FillRectangle( foreBrush, theBar ); } if(Value == Minimum || Value == Maximum) this.ReleaseBrushes(); } #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() { // // ProgressBar // this.CausesValidation = false; this.Enabled = false; this.ForeColor = System.Drawing.SystemColors.Highlight; this.Name = "ProgressBar"; this.Size = new System.Drawing.Size(432, 24); } #endregion } public class TestProgressBar : ColorProgressBar, TestObserver { private readonly static Color SuccessColor = Color.Lime; private readonly static Color FailureColor = Color.Red; private readonly static Color IgnoredColor = Color.Yellow; public TestProgressBar() { Initialize( 100 ); } private void Initialize( int testCount ) { Value = 0; Maximum = testCount; ForeColor = SuccessColor; } private void OnRunStarting( object Sender, TestEventArgs e ) { Initialize( e.TestCount ); } private void OnTestLoaded(object sender, TestEventArgs e) { Initialize(e.TestCount); } private void OnTestReloaded(object sender, TestEventArgs e) { if (Services.UserSettings.GetSetting("Options.TestLoader.ClearResultsOnReload", false)) Initialize(e.TestCount); else Value = Maximum = e.TestCount; } private void OnTestUnloaded(object sender, TestEventArgs e) { Initialize( 100 ); } private void OnTestFinished( object sender, TestEventArgs e ) { PerformStep(); switch (e.Result.ResultState) { case ResultState.NotRunnable: case ResultState.Failure: case ResultState.Error: case ResultState.Cancelled: ForeColor = FailureColor; break; case ResultState.Ignored: if (ForeColor == SuccessColor) ForeColor = IgnoredColor; break; default: break; } } private void OnSuiteFinished( object sender, TestEventArgs e ) { TestResult result = e.Result; if ( result.FailureSite == FailureSite.TearDown ) switch (result.ResultState) { case ResultState.Error: case ResultState.Failure: case ResultState.Cancelled: ForeColor = FailureColor; break; } } private void OnTestException(object sender, TestEventArgs e) { ForeColor = FailureColor; } #region TestObserver Members public void Subscribe(ITestEvents events) { events.TestLoaded += new TestEventHandler( OnTestLoaded ); events.TestReloaded += new TestEventHandler(OnTestReloaded); events.TestUnloaded += new TestEventHandler( OnTestUnloaded ); events.RunStarting += new TestEventHandler( OnRunStarting ); events.TestFinished += new TestEventHandler( OnTestFinished ); events.SuiteFinished += new TestEventHandler( OnSuiteFinished ); events.TestException += new TestEventHandler(OnTestException); } #endregion } }
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 RestClient.TestAPI.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; } } }
/* Copyright 2014 Google Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using DriveProxy.Utils; namespace DriveProxy.API { partial class DriveService { public class Settings { public static readonly string GUID_MyComputer = "20d04fe0-3aea-1069-a2d8-08002b30309d"; public static readonly string GUID_GDriveShlExt = "30323693-0E1E-4365-99FB-5074A5C6F273"; public static readonly int KB = 0x400; public static readonly int DownloadFileChunkSize = 256 * KB; public static readonly int UploadFileChunkSize = 256 * KB; public static int AuthenticationTimeout = 120; public static readonly int CleanupFileTimeout = 5; public static readonly int FileOnDiskTimeout = 5; private static string _googleDriveFolder = ""; private static readonly string _FileDataStoreFolder = String.Format("{0}.MyLibrary", Title); private static readonly string _ImageFolder = "Images"; private static readonly string _RootIdFileName = "root.key"; private static readonly string _LastChangeIdFileName = "history.key"; private static readonly string _JournalFileName = "journal.dat"; private static readonly string _DesktopIniFileName = "Desktop.ini"; private static readonly string _RefreshTokenFileName = "refreshtoken.dat"; private static readonly string _FileTitlesFileName = "filetitles.dat"; private static readonly string _FileName = "settings.dat"; private static readonly string _LogFileName = "log.dat"; private static readonly string _ShellLogFileName = "log.shell.dat"; private static readonly string _PathRegistryStartup = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run"; protected static string _LocalApplicationData = null; protected static string _LocalGoogleDriveData = null; protected static string _LocalGoogleDriveDataUser = null; protected static string _GoogleDriveDataUser = null; protected static string _ApplicationData = null; protected static string _GoogleDriveData = null; private static string _imageFolderPath = ""; private static string _desktopOldIniFilePath; private static string _desktopNewIniFilePath; private static string _tokenOldFilePath; private static string _tokenNewFilePath; private static string _rootIdFilePath; private static string _lastChangeIdPath; private static string _journalFolderPath; private static string _fileTitlesFilePath; private static string _filePath; private static string _logFilePath; private static string _shellLogFilePath; protected static string _UserName = ""; protected static string _userLogged = ""; protected static string _Location = ""; protected static string _LocationFileName = ""; protected static FileReturnType _FileReturnType = FileReturnType.FilterGoogleFiles; public static int _UseCaching = 1; public static string GoogleDriveFolder { get { if (String.IsNullOrEmpty(_googleDriveFolder)) { _googleDriveFolder = CompanyPath + "\\" + Product; } return _googleDriveFolder; } set { if (!String.IsNullOrEmpty(value) && value.IndexOf(CompanyPath + "\\") != 0) { _googleDriveFolder = CompanyPath + "\\" + value; } else { _googleDriveFolder = ""; } } } public static string Version { get { FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location); return fvi.FileVersion; } } public static string Title { get { AssemblyTitleAttribute titleAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (AssemblyTitleAttribute), false) .OfType<AssemblyTitleAttribute>() .FirstOrDefault(); return titleAttribute == null ? Path.GetFileNameWithoutExtension(Assembly.GetEntryAssembly().CodeBase) : titleAttribute.Title; } } public static string Description { get { AssemblyDescriptionAttribute descriptionAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (AssemblyDescriptionAttribute), false) .OfType<AssemblyDescriptionAttribute>() .FirstOrDefault(); if (descriptionAttribute != null) { return descriptionAttribute.Description; } Log.Error("Couldn't resolve description"); return "Unknown"; } } public static string Company { get { AssemblyCompanyAttribute companyAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (AssemblyCompanyAttribute), false) .OfType<AssemblyCompanyAttribute>() .FirstOrDefault(); if (companyAttribute != null) { return companyAttribute.Company; } Log.Error("Couldn't resolve company"); return "Unknown"; } } public static string Product { get { AssemblyProductAttribute productAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (AssemblyProductAttribute), false) .OfType<AssemblyProductAttribute>() .FirstOrDefault(); if (productAttribute != null) { return productAttribute.Product; } Log.Error("Couldn't resolve product"); return "Unknown"; } } public static string Copyright { get { AssemblyCopyrightAttribute copyrightAttribute = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (AssemblyCopyrightAttribute), false) .OfType<AssemblyCopyrightAttribute>() .FirstOrDefault(); if (copyrightAttribute != null) { return copyrightAttribute.Copyright; } Log.Error("Couldn't resolve copyright"); return "Unknown"; } } public static string CompanyPath { get { return GetCustomAttribute<CompanyPathAttr>(); } } public static string ServicePipeName { get { return GetCustomAttribute<ServicePipeNameAttr>(); } } public static string ClientID { get { return GetCustomAttribute<ClientIDAttr>(); } } public static string ClientSecret { get { return GetCustomAttribute<ClientSecretAttr>(); } } public static string LocalApplicationData { get { if (String.IsNullOrEmpty(_LocalApplicationData)) { _LocalApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData); } return _LocalApplicationData; } } public static string LocalGoogleDriveData { get { if (String.IsNullOrEmpty(_LocalGoogleDriveData) || !_LocalGoogleDriveData.Equals(LocalGoogleDriveDataUser)) { _LocalGoogleDriveData = System.IO.Path.Combine(LocalApplicationData, GoogleDriveFolder, LoggedUser); } CreateDirectory(_LocalGoogleDriveData); return _LocalGoogleDriveData; } } public static string LocalGoogleDriveDataUser { get { if (IsSignedIn) { _LocalGoogleDriveDataUser = System.IO.Path.Combine(LocalApplicationData, GoogleDriveFolder, LoggedUser); } CreateDirectory(_LocalGoogleDriveDataUser); return _LocalGoogleDriveDataUser; } } public static string ApplicationData { get { if (String.IsNullOrEmpty(_ApplicationData)) { _ApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); } return _ApplicationData; } } public static string GoogleDriveData { get { if (String.IsNullOrEmpty(_GoogleDriveData)) { _GoogleDriveData = System.IO.Path.Combine(ApplicationData, GoogleDriveFolder); } CreateDirectory(_GoogleDriveData); return _GoogleDriveData; } } public static string ImageFolderPath { get { if (String.IsNullOrEmpty(_imageFolderPath)) { _imageFolderPath = System.Reflection.Assembly.GetExecutingAssembly().Location; _imageFolderPath = System.IO.Path.GetDirectoryName(_imageFolderPath); _imageFolderPath = System.IO.Path.Combine(_imageFolderPath, _ImageFolder); } return _imageFolderPath; } } public static string DesktopOldIniFilePath { get { if (String.IsNullOrEmpty(_desktopOldIniFilePath)) { _desktopOldIniFilePath = System.IO.Path.Combine(LocalGoogleDriveData, _DesktopIniFileName); } return _desktopOldIniFilePath; } } public static string DesktopNewIniFilePath { get { if (String.IsNullOrEmpty(_desktopNewIniFilePath)) { string myDocuments = System.Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); _desktopNewIniFilePath = System.IO.Path.Combine(myDocuments, "My Google Drive", _DesktopIniFileName); } return _desktopNewIniFilePath; } } public static string TokenOldFilePath { get { if (String.IsNullOrEmpty(_tokenOldFilePath)) { _tokenOldFilePath = System.IO.Path.Combine(ApplicationData, string.Format("{0}\\{1}\\refreshtoken.dat", CompanyPath, Product)); } return _tokenOldFilePath; } } public static string TokenNewFilePath { get { if (String.IsNullOrEmpty(_tokenNewFilePath)) { _tokenNewFilePath = System.IO.Path.Combine(GoogleDriveData, "Token"); } return _tokenNewFilePath; } } public static string RootIdFilePath { get { if (String.IsNullOrEmpty(_rootIdFilePath)) { _rootIdFilePath = System.IO.Path.Combine(GoogleDriveData, LoggedUser, _RootIdFileName); } return _rootIdFilePath; } } public static string LastChangeIdPath { get { if (String.IsNullOrEmpty(_lastChangeIdPath)) { _lastChangeIdPath = System.IO.Path.Combine(GoogleDriveData, LoggedUser, _LastChangeIdFileName); } return _lastChangeIdPath; } } public static string JournalFolderPath { get { if (String.IsNullOrEmpty(_journalFolderPath)) { _journalFolderPath = System.IO.Path.Combine(GoogleDriveData, "Journal"); } return _journalFolderPath; } } public static string FileTitlesFilePath { get { if (String.IsNullOrEmpty(_fileTitlesFilePath) || !FileExists(_fileTitlesFilePath)) { _fileTitlesFilePath = System.IO.Path.Combine(GoogleDriveData, _FileTitlesFileName); } return _fileTitlesFilePath; } } public static string FilePath { get { if (String.IsNullOrEmpty(_filePath) || !FileExists(_filePath)) { _filePath = Win32.MakeFileNameWindowsSafe(UserName) + "." + _FileName; _filePath = System.IO.Path.Combine(GoogleDriveData, _filePath); } return _filePath; } } public static string LogFilePath { get { if (String.IsNullOrEmpty(_logFilePath) || !FileExists(_logFilePath)) { _logFilePath = System.IO.Path.Combine(GoogleDriveData, _LogFileName); } return _logFilePath; } set { _logFilePath = value; } } public static string ShellLogFilePath { get { if (String.IsNullOrEmpty(_shellLogFilePath) || !FileExists(_ShellLogFileName)) { _shellLogFilePath = System.IO.Path.Combine(GoogleDriveData, _ShellLogFileName); } return _shellLogFilePath; } } public static string UserName { get { try { if (String.IsNullOrEmpty(_UserName)) { _UserName = Environment.UserName; if (!String.IsNullOrEmpty(Environment.UserDomainName)) { _UserName += "@" + Environment.UserDomainName; } } return _UserName; } catch (Exception exception) { Log.Error(exception); return null; } } } public static string Location { get { if (String.IsNullOrEmpty(_Location)) { _Location = System.Reflection.Assembly.GetEntryAssembly().Location; } return _Location; } } public static string LocationFileName { get { if (String.IsNullOrEmpty(_LocationFileName)) { _LocationFileName = System.IO.Path.GetFileName(Location); } return _LocationFileName; } } public static LogType LogLevel { get { return Log.Level; } set { Log.Level = value; } } public static FileReturnType FileReturnType { get { if (_FileReturnType == FileReturnType.Unknown) { _FileReturnType = FileReturnType.FilterGoogleFiles; } return _FileReturnType; } set { _FileReturnType = value; } } public static bool UseCaching { get { if (_UseCaching == 0) { return false; } return true; } set { _UseCaching = value ? 1 : 0; } } public static bool IsStartingStartOnStartup { get { return IsRegisterOnStartup(); } set { if (value) { RegisterApplicationOnStartup(); } else { UnRegisterApplicationOnStartup(); } } } public static string LoggedUser { get { if (IsSignedIn && String.IsNullOrEmpty(_userLogged)) { AboutInfo aboutInfo = DriveService.GetAbout(); _userLogged = aboutInfo.Name; } return _userLogged; } set { _userLogged = String.IsNullOrEmpty(value) ? value : String.Empty; } } public static string GetCustomAttribute<T>() where T : DPSAttribute { T attr = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof (T), false) .OfType<T>() .FirstOrDefault(); if (attr != null) { return attr.attr_; } Log.Error("Couldn't resolve " + typeof (T).Name); return "Unknown"; } public static string GetJournalFilePath(string fileId, bool createDirectory = true) { string journalFilePath = System.IO.Path.Combine(GoogleDriveData, "Journal", LoggedUser); if (createDirectory) { CreateDirectory(journalFilePath); } journalFilePath = System.IO.Path.Combine(journalFilePath, fileId); return journalFilePath; } public static string[] GetLocalGoogleDriveDataSubFolders() { try { if (!System.IO.Directory.Exists(LocalGoogleDriveData)) { return new string[0]; } string[] folderPaths = System.IO.Directory.GetDirectories(LocalGoogleDriveData); return folderPaths; } catch (Exception exception) { Log.Error(exception); return null; } } public static void Load() { try { if (!FileExists(FilePath)) { Save(); } else { var iniFile = new IniFile(FilePath); string value = ""; LogLevel = LogType.Error; FileReturnType = FileReturnType.FilterGoogleFiles; value = iniFile.GetValue("Settings", "UseCaching"); UseCaching = ToBoolean(value); var logLevel = iniFile.GetValue("Settings", "LogLevel"); if (!string.IsNullOrEmpty(logLevel)) LogLevel = (LogType)Enum.Parse(typeof(LogType), iniFile.GetValue("Settings", "LogLevel")); var fileReturnType = iniFile.GetValue("Settings", "FileReturnType"); _FileReturnType = FileReturnType.FilterGoogleFiles; if (!string.IsNullOrEmpty(fileReturnType)) _FileReturnType = (FileReturnType)Enum.Parse(typeof(FileReturnType), fileReturnType); } } catch (Exception exception) { Log.Error(exception); } } private static bool ToBoolean(string value) { try { return (value == "1"); } catch { return true; } } public static void Save() { try { var iniFile = new IniFile(FilePath); iniFile.SetValue("Settings", "UseCaching", _UseCaching.ToString()); iniFile.SetValue("Settings", "LogLevel", LogLevel.ToString()); iniFile.SetValue("Settings", "FileReturnType", _FileReturnType.ToString()); } catch (Exception exception) { Log.Error(exception); } } private static bool IsRegisterOnStartup() { bool result = false; try { using (var registryKey = new Registry()) { if (registryKey.Open(RegistryKeyType.CurrentUser, _PathRegistryStartup, true)) { object value = registryKey.GetValue(Title); if (value != null) { result = !String.IsNullOrEmpty(value.ToString()); } } } } catch (Exception exception) { result = false; Log.Error(exception); } return result; } private static void RegisterApplicationOnStartup() { try { using (var registryKey = new Registry()) { if (registryKey.Open(RegistryKeyType.CurrentUser, _PathRegistryStartup, true)) { registryKey.SetValue(Title, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86) + String.Format("\\{0}\\{1}\\DriveProxy.Service.exe", CompanyPath, Product)); } } } catch (Exception exception) { Log.Error(exception); } } private static void UnRegisterApplicationOnStartup() { try { using (var registryKey = new Registry()) { if (registryKey.Open(RegistryKeyType.CurrentUser, _PathRegistryStartup, true)) { registryKey.DeleteValue(Title); } } } catch (Exception exception) { Log.Error(exception); } } } } }
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #endif namespace Newtonsoft.Json.Serialization { /// <summary> /// Contract details for a <see cref="System.Type"/> used by the <see cref="JsonSerializer"/>. /// </summary> public class JsonDictionaryContract : JsonContainerContract { /// <summary> /// Gets or sets the property name resolver. /// </summary> /// <value>The property name resolver.</value> [Obsolete("PropertyNameResolver is obsolete. Use DictionaryKeyResolver instead.")] public Func<string, string> PropertyNameResolver { get { return DictionaryKeyResolver; } set { DictionaryKeyResolver = value; } } /// <summary> /// Gets or sets the dictionary key resolver. /// </summary> /// <value>The dictionary key resolver.</value> public Func<string, string> DictionaryKeyResolver { get; set; } /// <summary> /// Gets the <see cref="System.Type"/> of the dictionary keys. /// </summary> /// <value>The <see cref="System.Type"/> of the dictionary keys.</value> public Type DictionaryKeyType { get; private set; } /// <summary> /// Gets the <see cref="System.Type"/> of the dictionary values. /// </summary> /// <value>The <see cref="System.Type"/> of the dictionary values.</value> public Type DictionaryValueType { get; private set; } internal JsonContract KeyContract { get; set; } private readonly Type _genericCollectionDefinitionType; private Type _genericWrapperType; private ObjectConstructor<object> _genericWrapperCreator; private Func<object> _genericTemporaryDictionaryCreator; internal bool ShouldCreateWrapper { get; private set; } private readonly ConstructorInfo _parameterizedConstructor; private ObjectConstructor<object> _overrideCreator; private ObjectConstructor<object> _parameterizedCreator; internal ObjectConstructor<object> ParameterizedCreator { get { if (_parameterizedCreator == null) { _parameterizedCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(_parameterizedConstructor); } return _parameterizedCreator; } } /// <summary> /// Gets or sets the function used to create the object. When set this function will override <see cref="JsonContract.DefaultCreator"/>. /// </summary> /// <value>The function used to create the object.</value> public ObjectConstructor<object> OverrideCreator { get { return _overrideCreator; } set { _overrideCreator = value; } } /// <summary> /// Gets a value indicating whether the creator has a parameter with the dictionary values. /// </summary> /// <value><c>true</c> if the creator has a parameter with the dictionary values; otherwise, <c>false</c>.</value> public bool HasParameterizedCreator { get; set; } internal bool HasParameterizedCreatorInternal { get { return (HasParameterizedCreator || _parameterizedCreator != null || _parameterizedConstructor != null); } } /// <summary> /// Initializes a new instance of the <see cref="JsonDictionaryContract"/> class. /// </summary> /// <param name="underlyingType">The underlying type for the contract.</param> public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { ContractType = JsonContractType.Dictionary; Type keyType; Type valueType; if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IDictionary<,>))) { CreatedType = typeof(Dictionary<,>).MakeGenericType(keyType, valueType); } #if !(NET40 || NET35 || NET20 || PORTABLE40) IsReadOnlyOrFixedSize = ReflectionUtils.InheritsGenericDefinition(underlyingType, typeof(ReadOnlyDictionary<,>)); #endif } #if !(NET40 || NET35 || NET20 || PORTABLE40) else if (ReflectionUtils.ImplementsGenericDefinition(underlyingType, typeof(IReadOnlyDictionary<,>), out _genericCollectionDefinitionType)) { keyType = _genericCollectionDefinitionType.GetGenericArguments()[0]; valueType = _genericCollectionDefinitionType.GetGenericArguments()[1]; if (ReflectionUtils.IsGenericDefinition(UnderlyingType, typeof(IReadOnlyDictionary<,>))) { CreatedType = typeof(ReadOnlyDictionary<,>).MakeGenericType(keyType, valueType); } IsReadOnlyOrFixedSize = true; } #endif else { ReflectionUtils.GetDictionaryKeyValueTypes(UnderlyingType, out keyType, out valueType); if (UnderlyingType == typeof(IDictionary)) { CreatedType = typeof(Dictionary<object, object>); } } if (keyType != null && valueType != null) { _parameterizedConstructor = CollectionUtils.ResolveEnumerableCollectionConstructor(CreatedType, typeof(KeyValuePair<,>).MakeGenericType(keyType, valueType)); #if !(NET35 || NET20) if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpMapTypeName) { FSharpUtils.EnsureInitialized(underlyingType.Assembly()); _parameterizedCreator = FSharpUtils.CreateMap(keyType, valueType); } #endif } ShouldCreateWrapper = !typeof(IDictionary).IsAssignableFrom(CreatedType); DictionaryKeyType = keyType; DictionaryValueType = valueType; #if (NET20 || NET35) if (DictionaryValueType != null && ReflectionUtils.IsNullableType(DictionaryValueType)) { Type tempDictioanryType; // bug in .NET 2.0 & 3.5 that Dictionary<TKey, Nullable<TValue>> throws an error when adding null via IDictionary[key] = object // wrapper will handle calling Add(T) instead if (ReflectionUtils.InheritsGenericDefinition(CreatedType, typeof(Dictionary<,>), out tempDictioanryType)) { ShouldCreateWrapper = true; } } #endif #if !(NET20 || NET35 || NET40) Type immutableCreatedType; ObjectConstructor<object> immutableParameterizedCreator; if (ImmutableCollectionsUtils.TryBuildImmutableForDictionaryContract(underlyingType, DictionaryKeyType, DictionaryValueType, out immutableCreatedType, out immutableParameterizedCreator)) { CreatedType = immutableCreatedType; _parameterizedCreator = immutableParameterizedCreator; IsReadOnlyOrFixedSize = true; } #endif } internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) { _genericWrapperType = typeof(DictionaryWrapper<,>).MakeGenericType(DictionaryKeyType, DictionaryValueType); ConstructorInfo genericWrapperConstructor = _genericWrapperType.GetConstructor(new[] { _genericCollectionDefinitionType }); _genericWrapperCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(genericWrapperConstructor); } return (IWrappedDictionary)_genericWrapperCreator(dictionary); } internal IDictionary CreateTemporaryDictionary() { if (_genericTemporaryDictionaryCreator == null) { Type temporaryDictionaryType = typeof(Dictionary<,>).MakeGenericType(DictionaryKeyType ?? typeof(object), DictionaryValueType ?? typeof(object)); _genericTemporaryDictionaryCreator = JsonTypeReflector.ReflectionDelegateFactory.CreateDefaultConstructor<object>(temporaryDictionaryType); } return (IDictionary)_genericTemporaryDictionaryCreator(); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using UMA; namespace UMA.Examples { public class UMACrowd : MonoBehaviour { public UMACrowdRandomSet[] randomPool; public UMAGeneratorBase generator; public UMAData umaData; public UMAContext umaContext; public RuntimeAnimatorController animationController; public float atlasResolutionScale = 1; public bool generateUMA; public bool generateLotsUMA; public bool hideWhileGeneratingLots; public bool stressTest; public Vector2 umaCrowdSize; public bool randomDna; public UMARecipeBase[] additionalRecipes; public float space = 1; public Transform zeroPoint; private int spawnX; private int spawnY; public SharedColorTable SkinColors; public SharedColorTable HairColors; // public SharedColorTable EyeColors; TODO: Add support for eye colors // public SharedColorTable ClothesColors; TODO: Add support for clothes colors public string[] keywords; public UMADataEvent CharacterCreated; public UMADataEvent CharacterDestroyed; public UMADataEvent CharacterUpdated; void Awake() { if (space <= 0) space = 1; } void Update() { if (generateUMA) { umaCrowdSize = Vector2.one; int randomResult = Random.Range(0, 2); GenerateOneUMA(randomResult); generateUMA = false; generateLotsUMA = false; } if (generateLotsUMA) { if (generator.IsIdle()) { int randomResult = Random.Range(0, 2); GenerateOneUMA(randomResult); } } if (stressTest && generator.IsIdle() && !generateLotsUMA && !generateUMA) { RandomizeAll(); } } private void DefineSlots(UMACrowdRandomSet.CrowdRaceData race) { Color skinColor; Color HairColor; Color Shine = Color.black; if (SkinColors != null) { OverlayColorData ocd = SkinColors.colors[Random.Range(0, SkinColors.colors.Length)]; skinColor = ocd.color; Shine = ocd.channelAdditiveMask[2]; } else { float skinTone = Random.Range(0.1f, 0.6f); skinColor = new Color(skinTone + Random.Range(0.35f, 0.4f), skinTone + Random.Range(0.25f, 0.4f), skinTone + Random.Range(0.35f, 0.4f), 1); } if (HairColors != null) { HairColor = HairColors.colors[Random.Range(0, HairColors.colors.Length)].color; } else { HairColor = new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1.0f); } var keywordsLookup = new HashSet<string>(keywords); UMACrowdRandomSet.Apply(umaData, race, skinColor, HairColor, Shine, keywordsLookup, umaContext); } void DefineSlots() { Color skinColor = new Color(1, 1, 1, 1); float skinTone; skinTone = Random.Range(0.1f, 0.6f); skinColor = new Color(skinTone + Random.Range(0.35f, 0.4f), skinTone + Random.Range(0.25f, 0.4f), skinTone + Random.Range(0.35f, 0.4f), 1); Color HairColor = new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1); if (umaData.umaRecipe.raceData.raceName == "HumanMale") { int randomResult = 0; //Male Avatar umaData.umaRecipe.slotDataList = new SlotData[15]; umaData.umaRecipe.slotDataList[0] = umaContext.InstantiateSlot("MaleEyes"); umaData.umaRecipe.slotDataList[0].AddOverlay(umaContext.InstantiateOverlay("EyeOverlay")); umaData.umaRecipe.slotDataList[0].AddOverlay(umaContext.InstantiateOverlay("EyeOverlayAdjust", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1] = umaContext.InstantiateSlot("MaleFace"); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHead01", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHead02", skinColor)); } } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1] = umaContext.InstantiateSlot("MaleHead_Head"); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHead01", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHead02", skinColor)); } umaData.umaRecipe.slotDataList[7] = umaContext.InstantiateSlot("MaleHead_Eyes", umaData.umaRecipe.slotDataList[1].GetOverlayList()); umaData.umaRecipe.slotDataList[9] = umaContext.InstantiateSlot("MaleHead_Mouth", umaData.umaRecipe.slotDataList[1].GetOverlayList()); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[10] = umaContext.InstantiateSlot("MaleHead_PigNose", umaData.umaRecipe.slotDataList[1].GetOverlayList()); umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHead_PigNose", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[10] = umaContext.InstantiateSlot("MaleHead_Nose", umaData.umaRecipe.slotDataList[1].GetOverlayList()); } randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[8] = umaContext.InstantiateSlot("MaleHead_ElvenEars"); umaData.umaRecipe.slotDataList[8].AddOverlay(umaContext.InstantiateOverlay("ElvenEars", skinColor)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[8] = umaContext.InstantiateSlot("MaleHead_Ears", umaData.umaRecipe.slotDataList[1].GetOverlayList()); } } randomResult = Random.Range(0, 3); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHair01", HairColor * 0.25f)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleHair02", HairColor * 0.25f)); } else { } randomResult = Random.Range(0, 4); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleBeard01", HairColor * 0.15f)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleBeard02", HairColor * 0.15f)); } else if (randomResult == 2) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleBeard03", HairColor * 0.15f)); } else { } //Extra beard composition randomResult = Random.Range(0, 4); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleBeard01", HairColor * 0.15f)); } else if (randomResult == 1) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleBeard02", HairColor * 0.15f)); } else if (randomResult == 2) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleBeard03", HairColor * 0.15f)); } else { } randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleEyebrow01", HairColor * 0.05f)); } else { umaData.umaRecipe.slotDataList[1].AddOverlay(umaContext.InstantiateOverlay("MaleEyebrow02", HairColor * 0.05f)); } umaData.umaRecipe.slotDataList[2] = umaContext.InstantiateSlot("MaleTorso"); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[2].AddOverlay(umaContext.InstantiateOverlay("MaleBody01", skinColor)); } else { umaData.umaRecipe.slotDataList[2].AddOverlay(umaContext.InstantiateOverlay("MaleBody02", skinColor)); } randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[2].AddOverlay(umaContext.InstantiateOverlay("MaleShirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } umaData.umaRecipe.slotDataList[3] = umaContext.InstantiateSlot("MaleHands", umaData.umaRecipe.slotDataList[2].GetOverlayList()); umaData.umaRecipe.slotDataList[4] = umaContext.InstantiateSlot("MaleInnerMouth"); umaData.umaRecipe.slotDataList[4].AddOverlay(umaContext.InstantiateOverlay("InnerMouth")); randomResult = Random.Range(0, 2); if (randomResult == 0) { umaData.umaRecipe.slotDataList[5] = umaContext.InstantiateSlot("MaleLegs", umaData.umaRecipe.slotDataList[2].GetOverlayList()); umaData.umaRecipe.slotDataList[2].AddOverlay(umaContext.InstantiateOverlay("MaleUnderwear01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else { umaData.umaRecipe.slotDataList[5] = umaContext.InstantiateSlot("MaleJeans01"); umaData.umaRecipe.slotDataList[5].AddOverlay(umaContext.InstantiateOverlay("MaleJeans01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } umaData.umaRecipe.slotDataList[6] = umaContext.InstantiateSlot("MaleFeet", umaData.umaRecipe.slotDataList[2].GetOverlayList()); } else if (umaData.umaRecipe.raceData.raceName == "HumanFemale") { int randomResult = 0; //Female Avatar //Example of dynamic list List<SlotData> tempSlotList = new List<SlotData>(); tempSlotList.Add(umaContext.InstantiateSlot("FemaleEyes")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("EyeOverlay")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("EyeOverlayAdjust", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); int headIndex = 0; randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleFace")); headIndex = tempSlotList.Count - 1; tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleHead01", skinColor)); tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleEyebrow01", new Color(0.125f, 0.065f, 0.065f, 1.0f))); randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleLipstick01", new Color(skinColor.r + Random.Range(0.0f, 0.3f), skinColor.g, skinColor.b + Random.Range(0.0f, 0.2f), 1))); } } else if (randomResult == 1) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleHead_Head")); headIndex = tempSlotList.Count - 1; tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleHead01", skinColor)); tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleEyebrow01", new Color(0.125f, 0.065f, 0.065f, 1.0f))); tempSlotList.Add(umaContext.InstantiateSlot("FemaleHead_Eyes", tempSlotList[headIndex].GetOverlayList())); tempSlotList.Add(umaContext.InstantiateSlot("FemaleHead_Mouth", tempSlotList[headIndex].GetOverlayList())); tempSlotList.Add(umaContext.InstantiateSlot("FemaleHead_Nose", tempSlotList[headIndex].GetOverlayList())); randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleHead_ElvenEars")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("ElvenEars", skinColor)); } else if (randomResult == 1) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleHead_Ears", tempSlotList[headIndex].GetOverlayList())); } randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleLipstick01", new Color(skinColor.r + Random.Range(0.0f, 0.3f), skinColor.g, skinColor.b + Random.Range(0.0f, 0.2f), 1))); } } tempSlotList.Add(umaContext.InstantiateSlot("FemaleEyelash")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("FemaleEyelash", Color.black)); tempSlotList.Add(umaContext.InstantiateSlot("FemaleTorso")); int bodyIndex = tempSlotList.Count - 1; randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList[bodyIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleBody01", skinColor)); } if (randomResult == 1) { tempSlotList[bodyIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleBody02", skinColor)); } tempSlotList[bodyIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleUnderwear01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); randomResult = Random.Range(0, 4); if (randomResult == 0) { tempSlotList[bodyIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleShirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else if (randomResult == 1) { tempSlotList[bodyIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleShirt02", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else if (randomResult == 2) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleTshirt01")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("FemaleTshirt01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } else { } tempSlotList.Add(umaContext.InstantiateSlot("FemaleHands", tempSlotList[bodyIndex].GetOverlayList())); tempSlotList.Add(umaContext.InstantiateSlot("FemaleInnerMouth")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("InnerMouth")); tempSlotList.Add(umaContext.InstantiateSlot("FemaleFeet", tempSlotList[bodyIndex].GetOverlayList())); randomResult = Random.Range(0, 2); if (randomResult == 0) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleLegs", tempSlotList[bodyIndex].GetOverlayList())); } else if (randomResult == 1) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleLegs", tempSlotList[bodyIndex].GetOverlayList())); tempSlotList[bodyIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleJeans01", new Color(Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), Random.Range(0.1f, 0.9f), 1))); } randomResult = Random.Range(0, 3); if (randomResult == 0) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleShortHair01", tempSlotList[headIndex].GetOverlayList())); tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleShortHair01", HairColor)); } else if (randomResult == 1) { tempSlotList.Add(umaContext.InstantiateSlot("FemaleLongHair01", tempSlotList[headIndex].GetOverlayList())); tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleLongHair01", HairColor)); } else { tempSlotList.Add(umaContext.InstantiateSlot("FemaleLongHair01", tempSlotList[headIndex].GetOverlayList())); tempSlotList[headIndex].AddOverlay(umaContext.InstantiateOverlay("FemaleLongHair01", HairColor)); tempSlotList.Add(umaContext.InstantiateSlot("FemaleLongHair01_Module")); tempSlotList[tempSlotList.Count - 1].AddOverlay(umaContext.InstantiateOverlay("FemaleLongHair01_Module", HairColor)); } umaData.SetSlots(tempSlotList.ToArray()); } } protected virtual void SetUMAData() { umaData.atlasResolutionScale = atlasResolutionScale; umaData.OnCharacterCreated += CharacterCreatedCallback; } void CharacterCreatedCallback(UMAData umaData) { if (generateLotsUMA && hideWhileGeneratingLots) { if (umaData.animator != null) umaData.animator.enabled = false; Renderer[] renderers = umaData.GetRenderers(); for (int i = 0; i < renderers.Length; i++) { renderers[i].enabled = false; } } } public static void RandomizeShape(UMAData umaData) { UMADnaHumanoid umaDna = umaData.umaRecipe.GetDna<UMADnaHumanoid>(); umaDna.height = Random.Range(0.4f, 0.5f); umaDna.headSize = Random.Range(0.485f, 0.515f); umaDna.headWidth = Random.Range(0.4f, 0.6f); umaDna.neckThickness = Random.Range(0.495f, 0.51f); if (umaData.umaRecipe.raceData.raceName == "HumanMale") { umaDna.handsSize = Random.Range(0.485f, 0.515f); umaDna.feetSize = Random.Range(0.485f, 0.515f); umaDna.legSeparation = Random.Range(0.4f, 0.6f); umaDna.waist = 0.5f; } else { umaDna.handsSize = Random.Range(0.485f, 0.515f); umaDna.feetSize = Random.Range(0.485f, 0.515f); umaDna.legSeparation = Random.Range(0.485f, 0.515f); umaDna.waist = Random.Range(0.3f, 0.8f); } umaDna.armLength = Random.Range(0.485f, 0.515f); umaDna.forearmLength = Random.Range(0.485f, 0.515f); umaDna.armWidth = Random.Range(0.3f, 0.8f); umaDna.forearmWidth = Random.Range(0.3f, 0.8f); umaDna.upperMuscle = Random.Range(0.0f, 1.0f); umaDna.upperWeight = Random.Range(-0.2f, 0.2f) + umaDna.upperMuscle; if (umaDna.upperWeight > 1.0) { umaDna.upperWeight = 1.0f; } if (umaDna.upperWeight < 0.0) { umaDna.upperWeight = 0.0f; } umaDna.lowerMuscle = Random.Range(-0.2f, 0.2f) + umaDna.upperMuscle; if (umaDna.lowerMuscle > 1.0) { umaDna.lowerMuscle = 1.0f; } if (umaDna.lowerMuscle < 0.0) { umaDna.lowerMuscle = 0.0f; } umaDna.lowerWeight = Random.Range(-0.1f, 0.1f) + umaDna.upperWeight; if (umaDna.lowerWeight > 1.0) { umaDna.lowerWeight = 1.0f; } if (umaDna.lowerWeight < 0.0) { umaDna.lowerWeight = 0.0f; } umaDna.belly = umaDna.upperWeight * Random.Range(0.0f,1.0f); umaDna.legsSize = Random.Range(0.45f, 0.6f); umaDna.gluteusSize = Random.Range(0.4f, 0.6f); umaDna.earsSize = Random.Range(0.3f, 0.8f); umaDna.earsPosition = Random.Range(0.3f, 0.8f); umaDna.earsRotation = Random.Range(0.3f, 0.8f); umaDna.noseSize = Random.Range(0.3f, 0.8f); umaDna.noseCurve = Random.Range(0.3f, 0.8f); umaDna.noseWidth = Random.Range(0.3f, 0.8f); umaDna.noseInclination = Random.Range(0.3f, 0.8f); umaDna.nosePosition = Random.Range(0.3f, 0.8f); umaDna.nosePronounced = Random.Range(0.3f, 0.8f); umaDna.noseFlatten = Random.Range(0.3f, 0.8f); umaDna.chinSize = Random.Range(0.3f, 0.8f); umaDna.chinPronounced = Random.Range(0.3f, 0.8f); umaDna.chinPosition = Random.Range(0.3f, 0.8f); umaDna.mandibleSize = Random.Range(0.45f, 0.52f); umaDna.jawsSize = Random.Range(0.3f, 0.8f); umaDna.jawsPosition = Random.Range(0.3f, 0.8f); umaDna.cheekSize = Random.Range(0.3f, 0.8f); umaDna.cheekPosition = Random.Range(0.3f, 0.8f); umaDna.lowCheekPronounced = Random.Range(0.3f, 0.8f); umaDna.lowCheekPosition = Random.Range(0.3f, 0.8f); umaDna.foreheadSize = Random.Range(0.3f, 0.8f); umaDna.foreheadPosition = Random.Range(0.15f, 0.65f); umaDna.lipsSize = Random.Range(0.3f, 0.8f); umaDna.mouthSize = Random.Range(0.3f, 0.8f); umaDna.eyeRotation = Random.Range(0.3f, 0.8f); umaDna.eyeSize = Random.Range(0.3f, 0.8f); umaDna.breastSize = Random.Range(0.3f, 0.8f); } protected virtual void GenerateUMAShapes() { UMADnaHumanoid umaDna = umaData.umaRecipe.GetDna<UMADnaHumanoid>(); if (umaDna == null) { umaDna = new UMADnaHumanoid(); umaData.umaRecipe.AddDna(umaDna); } if (randomDna) { RandomizeShape(umaData); } } public void ResetSpawnPos(){ spawnX = 0; spawnY = 0; } public GameObject GenerateUMA(int sex, Vector3 position) { GameObject newGO = new GameObject("Generated Character"); newGO.transform.parent = transform; newGO.transform.position = position; newGO.transform.rotation = zeroPoint != null ? zeroPoint.rotation : transform.rotation; UMADynamicAvatar umaDynamicAvatar = newGO.AddComponent<UMADynamicAvatar>(); umaDynamicAvatar.Initialize(); umaData = umaDynamicAvatar.umaData; umaData.CharacterCreated = new UMADataEvent(CharacterCreated); umaData.CharacterDestroyed = new UMADataEvent(CharacterDestroyed); umaData.CharacterUpdated = new UMADataEvent(CharacterUpdated); umaDynamicAvatar.umaGenerator = generator; umaData.umaGenerator = generator; var umaRecipe = umaDynamicAvatar.umaData.umaRecipe; UMACrowdRandomSet.CrowdRaceData race = null; if (randomPool != null && randomPool.Length > 0) { int randomResult = Random.Range(0, randomPool.Length); race = randomPool[randomResult].data; umaRecipe.SetRace(umaContext.GetRace(race.raceID)); } else { if (sex == 0) { umaRecipe.SetRace(umaContext.GetRace("HumanMale")); } else { umaRecipe.SetRace(umaContext.GetRace("HumanFemale")); } } SetUMAData(); if (race != null && race.slotElements.Length > 0) { DefineSlots(race); } else { DefineSlots(); } AddAdditionalSlots(); GenerateUMAShapes(); if (animationController != null) { umaDynamicAvatar.animationController = animationController; } umaDynamicAvatar.Show(); return newGO; } public GameObject GenerateOneUMA(int sex) { Vector3 zeroPos = Vector3.zero; if (zeroPoint != null) zeroPos = zeroPoint.position; Vector3 newPos = zeroPos + new Vector3((spawnX - umaCrowdSize.x / 2f + 0.5f) * space, 0f, (spawnY - umaCrowdSize.y / 2f + 0.5f) * space); if (spawnY < umaCrowdSize.y) { spawnX++; if (spawnX >= umaCrowdSize.x) { spawnX = 0; spawnY++; } } else { if (hideWhileGeneratingLots) { UMAData[] generatedCrowd = GetComponentsInChildren<UMAData>(); foreach (UMAData generatedData in generatedCrowd) { if (generatedData.animator != null) generatedData.animator.enabled = true; Renderer[] renderers = generatedData.GetRenderers(); for (int i = 0; i < renderers.Length; i++) { renderers[i].enabled = true; } } } generateLotsUMA = false; spawnX = 0; spawnY = 0; return null; } return GenerateUMA(sex, newPos); } private void AddAdditionalSlots() { umaData.AddAdditionalRecipes(additionalRecipes, UMAContext.FindInstance()); } public void ReplaceAll() { if (generateUMA || generateLotsUMA) { Debug.LogWarning("Can't replace while spawning."); return; } int childCount = gameObject.transform.childCount; while(--childCount >= 0) { Transform child = gameObject.transform.GetChild(childCount); UMAUtils.DestroySceneObject(child.gameObject); } if (umaCrowdSize.x <= 1 && umaCrowdSize.y <= 1) generateUMA = true; else generateLotsUMA = true; } public void RandomizeAllDna() { for (int i = 0; i < transform.childCount; i++) { var umaData = transform.GetChild(i).GetComponent<UMAData>(); UMACrowd.RandomizeShape(umaData); umaData.Dirty(true, false, false); } } public void RandomizeAll() { if (generateUMA || generateLotsUMA) { Debug.LogWarning("Can't randomize while spawning."); return; } int childCount = gameObject.transform.childCount; for (int i = 0; i < childCount; i++) { Transform child = gameObject.transform.GetChild(i); UMADynamicAvatar umaDynamicAvatar = child.gameObject.GetComponent<UMADynamicAvatar>(); if (umaDynamicAvatar == null) { Debug.Log("Couldn't find dynamic avatar on child: " + child.gameObject.name); continue; } umaData = umaDynamicAvatar.umaData; var umaRecipe = umaDynamicAvatar.umaData.umaRecipe; UMACrowdRandomSet.CrowdRaceData race = null; if (randomPool != null && randomPool.Length > 0) { int randomResult = Random.Range(0, randomPool.Length); race = randomPool[randomResult].data; umaRecipe.SetRace(umaContext.GetRace(race.raceID)); } else { if (Random.value < 0.5f) { umaRecipe.SetRace(umaContext.GetRace("HumanMale")); } else { umaRecipe.SetRace(umaContext.GetRace("HumanFemale")); } } // SetUMAData(); if (race != null && race.slotElements.Length > 0) { DefineSlots(race); } else { DefineSlots(); } AddAdditionalSlots(); GenerateUMAShapes(); if (animationController != null) { umaDynamicAvatar.animationController = animationController; } umaDynamicAvatar.Show(); } } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V9.Resources; using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using gaxgrpccore = Google.Api.Gax.Grpc.GrpcCore; using proto = Google.Protobuf; using grpccore = Grpc.Core; using grpcinter = Grpc.Core.Interceptors; using sys = System; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Ads.GoogleAds.V9.Services { /// <summary>Settings for <see cref="AssetFieldTypeViewServiceClient"/> instances.</summary> public sealed partial class AssetFieldTypeViewServiceSettings : gaxgrpc::ServiceSettingsBase { /// <summary>Get a new instance of the default <see cref="AssetFieldTypeViewServiceSettings"/>.</summary> /// <returns>A new instance of the default <see cref="AssetFieldTypeViewServiceSettings"/>.</returns> public static AssetFieldTypeViewServiceSettings GetDefault() => new AssetFieldTypeViewServiceSettings(); /// <summary> /// Constructs a new <see cref="AssetFieldTypeViewServiceSettings"/> object with default settings. /// </summary> public AssetFieldTypeViewServiceSettings() { } private AssetFieldTypeViewServiceSettings(AssetFieldTypeViewServiceSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); GetAssetFieldTypeViewSettings = existing.GetAssetFieldTypeViewSettings; OnCopy(existing); } partial void OnCopy(AssetFieldTypeViewServiceSettings existing); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>AssetFieldTypeViewServiceClient.GetAssetFieldTypeView</c> and /// <c>AssetFieldTypeViewServiceClient.GetAssetFieldTypeViewAsync</c>. /// </summary> /// <remarks> /// <list type="bullet"> /// <item><description>Initial retry delay: 5000 milliseconds.</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds.</description></item> /// <item><description>Maximum attempts: Unlimited</description></item> /// <item> /// <description> /// Retriable status codes: <see cref="grpccore::StatusCode.Unavailable"/>, /// <see cref="grpccore::StatusCode.DeadlineExceeded"/>. /// </description> /// </item> /// <item><description>Timeout: 3600 seconds.</description></item> /// </list> /// </remarks> public gaxgrpc::CallSettings GetAssetFieldTypeViewSettings { get; set; } = gaxgrpc::CallSettingsExtensions.WithRetry(gaxgrpc::CallSettings.FromExpiration(gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(3600000))), gaxgrpc::RetrySettings.FromExponentialBackoff(maxAttempts: 2147483647, initialBackoff: sys::TimeSpan.FromMilliseconds(5000), maxBackoff: sys::TimeSpan.FromMilliseconds(60000), backoffMultiplier: 1.3, retryFilter: gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable, grpccore::StatusCode.DeadlineExceeded))); /// <summary>Creates a deep clone of this object, with all the same property values.</summary> /// <returns>A deep clone of this <see cref="AssetFieldTypeViewServiceSettings"/> object.</returns> public AssetFieldTypeViewServiceSettings Clone() => new AssetFieldTypeViewServiceSettings(this); } /// <summary> /// Builder class for <see cref="AssetFieldTypeViewServiceClient"/> to provide simple configuration of credentials, /// endpoint etc. /// </summary> internal sealed partial class AssetFieldTypeViewServiceClientBuilder : gaxgrpc::ClientBuilderBase<AssetFieldTypeViewServiceClient> { /// <summary>The settings to use for RPCs, or <c>null</c> for the default settings.</summary> public AssetFieldTypeViewServiceSettings Settings { get; set; } /// <summary>Creates a new builder with default settings.</summary> public AssetFieldTypeViewServiceClientBuilder() { UseJwtAccessWithScopes = AssetFieldTypeViewServiceClient.UseJwtAccessWithScopes; } partial void InterceptBuild(ref AssetFieldTypeViewServiceClient client); partial void InterceptBuildAsync(st::CancellationToken cancellationToken, ref stt::Task<AssetFieldTypeViewServiceClient> task); /// <summary>Builds the resulting client.</summary> public override AssetFieldTypeViewServiceClient Build() { AssetFieldTypeViewServiceClient client = null; InterceptBuild(ref client); return client ?? BuildImpl(); } /// <summary>Builds the resulting client asynchronously.</summary> public override stt::Task<AssetFieldTypeViewServiceClient> BuildAsync(st::CancellationToken cancellationToken = default) { stt::Task<AssetFieldTypeViewServiceClient> task = null; InterceptBuildAsync(cancellationToken, ref task); return task ?? BuildAsyncImpl(cancellationToken); } private AssetFieldTypeViewServiceClient BuildImpl() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return AssetFieldTypeViewServiceClient.Create(callInvoker, Settings); } private async stt::Task<AssetFieldTypeViewServiceClient> BuildAsyncImpl(st::CancellationToken cancellationToken) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return AssetFieldTypeViewServiceClient.Create(callInvoker, Settings); } /// <summary>Returns the endpoint for this builder type, used if no endpoint is otherwise specified.</summary> protected override string GetDefaultEndpoint() => AssetFieldTypeViewServiceClient.DefaultEndpoint; /// <summary> /// Returns the default scopes for this builder type, used if no scopes are otherwise specified. /// </summary> protected override scg::IReadOnlyList<string> GetDefaultScopes() => AssetFieldTypeViewServiceClient.DefaultScopes; /// <summary>Returns the channel pool to use when no other options are specified.</summary> protected override gaxgrpc::ChannelPool GetChannelPool() => AssetFieldTypeViewServiceClient.ChannelPool; /// <summary>Returns the default <see cref="gaxgrpc::GrpcAdapter"/>to use if not otherwise specified.</summary> protected override gaxgrpc::GrpcAdapter DefaultGrpcAdapter => gaxgrpccore::GrpcCoreAdapter.Instance; } /// <summary>AssetFieldTypeViewService client wrapper, for convenient use.</summary> /// <remarks> /// Service to fetch asset field type views. /// </remarks> public abstract partial class AssetFieldTypeViewServiceClient { /// <summary> /// The default endpoint for the AssetFieldTypeViewService service, which is a host of /// "googleads.googleapis.com" and a port of 443. /// </summary> public static string DefaultEndpoint { get; } = "googleads.googleapis.com:443"; /// <summary>The default AssetFieldTypeViewService scopes.</summary> /// <remarks> /// The default AssetFieldTypeViewService scopes are: /// <list type="bullet"><item><description>https://www.googleapis.com/auth/adwords</description></item></list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/adwords", }); internal static gaxgrpc::ChannelPool ChannelPool { get; } = new gaxgrpc::ChannelPool(DefaultScopes, UseJwtAccessWithScopes); internal static bool UseJwtAccessWithScopes { get { bool useJwtAccessWithScopes = true; MaybeUseJwtAccessWithScopes(ref useJwtAccessWithScopes); return useJwtAccessWithScopes; } } static partial void MaybeUseJwtAccessWithScopes(ref bool useJwtAccessWithScopes); /// <summary> /// Asynchronously creates a <see cref="AssetFieldTypeViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AssetFieldTypeViewServiceClientBuilder"/>. /// </summary> /// <param name="cancellationToken"> /// The <see cref="st::CancellationToken"/> to use while creating the client. /// </param> /// <returns>The task representing the created <see cref="AssetFieldTypeViewServiceClient"/>.</returns> public static stt::Task<AssetFieldTypeViewServiceClient> CreateAsync(st::CancellationToken cancellationToken = default) => new AssetFieldTypeViewServiceClientBuilder().BuildAsync(cancellationToken); /// <summary> /// Synchronously creates a <see cref="AssetFieldTypeViewServiceClient"/> using the default credentials, /// endpoint and settings. To specify custom credentials or other settings, use /// <see cref="AssetFieldTypeViewServiceClientBuilder"/>. /// </summary> /// <returns>The created <see cref="AssetFieldTypeViewServiceClient"/>.</returns> public static AssetFieldTypeViewServiceClient Create() => new AssetFieldTypeViewServiceClientBuilder().Build(); /// <summary> /// Creates a <see cref="AssetFieldTypeViewServiceClient"/> which uses the specified call invoker for remote /// operations. /// </summary> /// <param name="callInvoker"> /// The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null. /// </param> /// <param name="settings">Optional <see cref="AssetFieldTypeViewServiceSettings"/>.</param> /// <returns>The created <see cref="AssetFieldTypeViewServiceClient"/>.</returns> internal static AssetFieldTypeViewServiceClient Create(grpccore::CallInvoker callInvoker, AssetFieldTypeViewServiceSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpcinter::Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpcinter::CallInvokerExtensions.Intercept(callInvoker, interceptor); } AssetFieldTypeViewService.AssetFieldTypeViewServiceClient grpcClient = new AssetFieldTypeViewService.AssetFieldTypeViewServiceClient(callInvoker); return new AssetFieldTypeViewServiceClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/>. Channels which weren't automatically created are not /// affected. /// </summary> /// <remarks> /// After calling this method, further calls to <see cref="Create()"/> and /// <see cref="CreateAsync(st::CancellationToken)"/> will create new channels, which could in turn be shut down /// by another call to this method. /// </remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => ChannelPool.ShutdownChannelsAsync(); /// <summary>The underlying gRPC AssetFieldTypeViewService client</summary> public virtual AssetFieldTypeViewService.AssetFieldTypeViewServiceClient GrpcClient => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AssetFieldTypeView GetAssetFieldTypeView(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null) => throw new sys::NotImplementedException(); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(GetAssetFieldTypeViewRequest request, st::CancellationToken cancellationToken) => GetAssetFieldTypeViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the asset field type view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AssetFieldTypeView GetAssetFieldTypeView(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAssetFieldTypeView(new GetAssetFieldTypeViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the asset field type view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(string resourceName, gaxgrpc::CallSettings callSettings = null) => GetAssetFieldTypeViewAsync(new GetAssetFieldTypeViewRequest { ResourceName = gax::GaxPreconditions.CheckNotNullOrEmpty(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the asset field type view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(string resourceName, st::CancellationToken cancellationToken) => GetAssetFieldTypeViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the asset field type view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public virtual gagvr::AssetFieldTypeView GetAssetFieldTypeView(gagvr::AssetFieldTypeViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAssetFieldTypeView(new GetAssetFieldTypeViewRequest { ResourceNameAsAssetFieldTypeViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the asset field type view to fetch. /// </param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(gagvr::AssetFieldTypeViewName resourceName, gaxgrpc::CallSettings callSettings = null) => GetAssetFieldTypeViewAsync(new GetAssetFieldTypeViewRequest { ResourceNameAsAssetFieldTypeViewName = gax::GaxPreconditions.CheckNotNull(resourceName, nameof(resourceName)), }, callSettings); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="resourceName"> /// Required. The resource name of the asset field type view to fetch. /// </param> /// <param name="cancellationToken">A <see cref="st::CancellationToken"/> to use for this RPC.</param> /// <returns>A Task containing the RPC response.</returns> public virtual stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(gagvr::AssetFieldTypeViewName resourceName, st::CancellationToken cancellationToken) => GetAssetFieldTypeViewAsync(resourceName, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); } /// <summary>AssetFieldTypeViewService client wrapper implementation, for convenient use.</summary> /// <remarks> /// Service to fetch asset field type views. /// </remarks> public sealed partial class AssetFieldTypeViewServiceClientImpl : AssetFieldTypeViewServiceClient { private readonly gaxgrpc::ApiCall<GetAssetFieldTypeViewRequest, gagvr::AssetFieldTypeView> _callGetAssetFieldTypeView; /// <summary> /// Constructs a client wrapper for the AssetFieldTypeViewService service, with the specified gRPC client and /// settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings"> /// The base <see cref="AssetFieldTypeViewServiceSettings"/> used within this client. /// </param> public AssetFieldTypeViewServiceClientImpl(AssetFieldTypeViewService.AssetFieldTypeViewServiceClient grpcClient, AssetFieldTypeViewServiceSettings settings) { GrpcClient = grpcClient; AssetFieldTypeViewServiceSettings effectiveSettings = settings ?? AssetFieldTypeViewServiceSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callGetAssetFieldTypeView = clientHelper.BuildApiCall<GetAssetFieldTypeViewRequest, gagvr::AssetFieldTypeView>(grpcClient.GetAssetFieldTypeViewAsync, grpcClient.GetAssetFieldTypeView, effectiveSettings.GetAssetFieldTypeViewSettings).WithGoogleRequestParam("resource_name", request => request.ResourceName); Modify_ApiCall(ref _callGetAssetFieldTypeView); Modify_GetAssetFieldTypeViewApiCall(ref _callGetAssetFieldTypeView); OnConstruction(grpcClient, effectiveSettings, clientHelper); } partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, proto::IMessage<TRequest> where TResponse : class, proto::IMessage<TResponse>; partial void Modify_GetAssetFieldTypeViewApiCall(ref gaxgrpc::ApiCall<GetAssetFieldTypeViewRequest, gagvr::AssetFieldTypeView> call); partial void OnConstruction(AssetFieldTypeViewService.AssetFieldTypeViewServiceClient grpcClient, AssetFieldTypeViewServiceSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary>The underlying gRPC AssetFieldTypeViewService client</summary> public override AssetFieldTypeViewService.AssetFieldTypeViewServiceClient GrpcClient { get; } partial void Modify_GetAssetFieldTypeViewRequest(ref GetAssetFieldTypeViewRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>The RPC response.</returns> public override gagvr::AssetFieldTypeView GetAssetFieldTypeView(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAssetFieldTypeViewRequest(ref request, ref callSettings); return _callGetAssetFieldTypeView.Sync(request, callSettings); } /// <summary> /// Returns the requested asset field type view in full detail. /// </summary> /// <param name="request">The request object containing all of the parameters for the API call.</param> /// <param name="callSettings">If not null, applies overrides to this RPC call.</param> /// <returns>A Task containing the RPC response.</returns> public override stt::Task<gagvr::AssetFieldTypeView> GetAssetFieldTypeViewAsync(GetAssetFieldTypeViewRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetAssetFieldTypeViewRequest(ref request, ref callSettings); return _callGetAssetFieldTypeView.Async(request, callSettings); } } }
#if OS_WINDOWS using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.IO; using System.Linq; using System.Security.Principal; using System.Security; using System.Text; namespace Microsoft.VisualStudio.Services.Agent.Listener.Configuration { public class WindowsServiceControlManager : ServiceControlManager, IWindowsServiceControlManager { public const string WindowsServiceControllerName = "AgentService.exe"; private const string ServiceNamePattern = "vstsagent.{0}.{1}"; private const string ServiceDisplayNamePattern = "VSTS Agent ({0}.{1})"; private INativeWindowsServiceHelper _windowsServiceHelper; private ITerminal _term; public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _windowsServiceHelper = HostContext.GetService<INativeWindowsServiceHelper>(); _term = HostContext.GetService<ITerminal>(); } public void ConfigureService(AgentSettings settings, CommandSettings command) { Trace.Entering(); if (!_windowsServiceHelper.IsRunningInElevatedMode()) { Trace.Error("Needs Administrator privileges for configure agent as windows service."); throw new SecurityException(StringUtil.Loc("NeedAdminForConfigAgentWinService")); } // TODO: Fix bug that exists in the legacy Windows agent where configuration using mirrored credentials causes an error, but the agent is still functional (after restarting). Mirrored credentials is a supported scenario and shouldn't manifest any errors. // We use NetworkService as default account for build and release agent // We use Local System as default account for deployment agent NTAccount defaultServiceAccount = command.DeploymentGroup ? _windowsServiceHelper.GetDefaultAdminServiceAccount() : _windowsServiceHelper.GetDefaultServiceAccount(); string logonAccount = command.GetWindowsLogonAccount(defaultValue: defaultServiceAccount.ToString(), descriptionMsg: StringUtil.Loc("WindowsLogonAccountNameDescription")); string domainName; string userName; GetAccountSegments(logonAccount, out domainName, out userName); if ((string.IsNullOrEmpty(domainName) || domainName.Equals(".", StringComparison.CurrentCultureIgnoreCase)) && !logonAccount.Contains('@')) { logonAccount = String.Format("{0}\\{1}", Environment.MachineName, userName); } Trace.Info("LogonAccount after transforming: {0}, user: {1}, domain: {2}", logonAccount, userName, domainName); string logonPassword = string.Empty; if (!defaultServiceAccount.Equals(new NTAccount(logonAccount)) && !NativeWindowsServiceHelper.IsWellKnownIdentity(logonAccount)) { while (true) { logonPassword = command.GetWindowsLogonPassword(logonAccount); if (_windowsServiceHelper.IsValidCredential(domainName, userName, logonPassword)) { Trace.Info("Credential validation succeed"); break; } else { if (!command.Unattended) { Trace.Info("Invalid credential entered"); _term.WriteLine(StringUtil.Loc("InvalidWindowsCredential")); } else { throw new SecurityException(StringUtil.Loc("InvalidWindowsCredential")); } } } } string serviceName; string serviceDisplayName; CalculateServiceName(settings, ServiceNamePattern, ServiceDisplayNamePattern, out serviceName, out serviceDisplayName); if (_windowsServiceHelper.IsServiceExists(serviceName)) { _term.WriteLine(StringUtil.Loc("ServiceAlreadyExists", serviceName)); _windowsServiceHelper.UninstallService(serviceName); } Trace.Info("Verifying if the account has LogonAsService permission"); if (_windowsServiceHelper.IsUserHasLogonAsServicePrivilege(domainName, userName)) { Trace.Info($"Account: {logonAccount} already has Logon As Service Privilege."); } else { if (!_windowsServiceHelper.GrantUserLogonAsServicePrivilage(domainName, userName)) { throw new InvalidOperationException(StringUtil.Loc("CanNotGrantPermission", logonAccount)); } } Trace.Info("Create local group and grant folder permission to service logon account."); GrantDirectoryPermissionForAccount(logonAccount); // install service. _windowsServiceHelper.InstallService(serviceName, serviceDisplayName, logonAccount, logonPassword); // create .service file with service name. SaveServiceSettings(serviceName); // Add registry key after installation _windowsServiceHelper.CreateVstsAgentRegistryKey(); Trace.Info("Configuration was successful, trying to start the service"); _windowsServiceHelper.StartService(serviceName); } private void GrantDirectoryPermissionForAccount(string accountName) { Trace.Entering(); string groupName = _windowsServiceHelper.GetUniqueBuildGroupName(); Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName)); if (!_windowsServiceHelper.LocalGroupExists(groupName)) { Trace.Info(StringUtil.Format("Trying to create group {0}", groupName)); _windowsServiceHelper.CreateLocalGroup(groupName); } Trace.Info(StringUtil.Format("Trying to add userName {0} to the group {1}", accountName, groupName)); _windowsServiceHelper.AddMemberToLocalGroup(accountName, groupName); // grant permssion for agent root folder string agentRoot = IOUtil.GetRootPath(); Trace.Info(StringUtil.Format("Set full access control to group for the folder {0}", agentRoot)); _windowsServiceHelper.GrantFullControlToGroup(agentRoot, groupName); // grant permssion for work folder string workFolder = IOUtil.GetWorkPath(HostContext); Directory.CreateDirectory(workFolder); Trace.Info(StringUtil.Format("Set full access control to group for the folder {0}", workFolder)); _windowsServiceHelper.GrantFullControlToGroup(workFolder, groupName); } private void RevokeDirectoryPermissionForAccount() { Trace.Entering(); string groupName = _windowsServiceHelper.GetUniqueBuildGroupName(); Trace.Info(StringUtil.Format("Calculated unique group name {0}", groupName)); // remove the group from the work folder string workFolder = IOUtil.GetWorkPath(HostContext); if (Directory.Exists(workFolder)) { Trace.Info(StringUtil.Format($"Remove the group {groupName} for the folder {workFolder}.")); _windowsServiceHelper.RemoveGroupFromFolderSecuritySetting(workFolder, groupName); } //remove group from agent root folder string agentRoot = IOUtil.GetRootPath(); if (Directory.Exists(agentRoot)) { Trace.Info(StringUtil.Format($"Remove the group {groupName} for the folder {agentRoot}.")); _windowsServiceHelper.RemoveGroupFromFolderSecuritySetting(agentRoot, groupName); } //delete group Trace.Info(StringUtil.Format($"Delete the group {groupName}.")); _windowsServiceHelper.DeleteLocalGroup(groupName); } public void UnconfigureService() { if (!_windowsServiceHelper.IsRunningInElevatedMode()) { Trace.Error("Needs Administrator privileges for unconfigure windows service agent."); throw new SecurityException(StringUtil.Loc("NeedAdminForUnconfigWinServiceAgent")); } string serviceConfigPath = IOUtil.GetServiceConfigFilePath(); string serviceName = File.ReadAllText(serviceConfigPath); if (_windowsServiceHelper.IsServiceExists(serviceName)) { _windowsServiceHelper.StopService(serviceName); _windowsServiceHelper.UninstallService(serviceName); // Delete local group we created during confiure. RevokeDirectoryPermissionForAccount(); // Remove registry key only on Windows _windowsServiceHelper.DeleteVstsAgentRegistryKey(); } IOUtil.DeleteFile(serviceConfigPath); } private void SaveServiceSettings(string serviceName) { string serviceConfigPath = IOUtil.GetServiceConfigFilePath(); if (File.Exists(serviceConfigPath)) { IOUtil.DeleteFile(serviceConfigPath); } File.WriteAllText(serviceConfigPath, serviceName, new UTF8Encoding(false)); File.SetAttributes(serviceConfigPath, File.GetAttributes(serviceConfigPath) | FileAttributes.Hidden); } private void GetAccountSegments(string account, out string domain, out string user) { string[] segments = account.Split('\\'); domain = string.Empty; user = account; if (segments.Length == 2) { domain = segments[0]; user = segments[1]; } } } } #endif
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using Agent.Sdk.Knob; using BuildXL.Cache.ContentStore.Hashing; using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Blob; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.BlobStore.Common; using Microsoft.VisualStudio.Services.BlobStore.WebApi; using Microsoft.VisualStudio.Services.Content.Common; using Microsoft.VisualStudio.Services.Content.Common.Tracing; using Microsoft.VisualStudio.Services.FileContainer; using Microsoft.VisualStudio.Services.FileContainer.Client; using Microsoft.VisualStudio.Services.WebApi; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Threading.Tasks.Dataflow; namespace Agent.Plugins { internal class FileContainerProvider : IArtifactProvider { private readonly VssConnection connection; private readonly FileContainerHttpClient containerClient; private readonly IAppTraceSource tracer; [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Maintainability", "CA2000:Dispose objects before losing scope", MessageId = "connection2")] public FileContainerProvider(VssConnection connection, IAppTraceSource tracer) { BuildHttpClient buildHttpClient = connection.GetClient<BuildHttpClient>(); var connection2 = new VssConnection(buildHttpClient.BaseAddress, connection.Credentials); containerClient = connection2.GetClient<FileContainerHttpClient>(); this.tracer = tracer; this.connection = connection; } public async Task DownloadSingleArtifactAsync(ArtifactDownloadParameters downloadParameters, BuildArtifact buildArtifact, CancellationToken cancellationToken, AgentTaskPluginExecutionContext context) { IEnumerable<FileContainerItem> items = await GetArtifactItems(downloadParameters, buildArtifact); await this.DownloadFileContainerAsync(items, downloadParameters, buildArtifact, downloadParameters.TargetDirectory, context, cancellationToken); IEnumerable<string> fileArtifactPaths = items .Where((item) => item.ItemType == ContainerItemType.File) .Select((fileItem) => Path.Combine(downloadParameters.TargetDirectory, fileItem.Path)); if (downloadParameters.ExtractTars) { ExtractTarsIfPresent(context, fileArtifactPaths, downloadParameters.TargetDirectory, downloadParameters.ExtractedTarsTempPath); } } public async Task DownloadMultipleArtifactsAsync(ArtifactDownloadParameters downloadParameters, IEnumerable<BuildArtifact> buildArtifacts, CancellationToken cancellationToken, AgentTaskPluginExecutionContext context) { var allFileArtifactPaths = new List<string>(); foreach (var buildArtifact in buildArtifacts) { var dirPath = downloadParameters.AppendArtifactNameToTargetPath ? Path.Combine(downloadParameters.TargetDirectory, buildArtifact.Name) : downloadParameters.TargetDirectory; IEnumerable<FileContainerItem> items = await GetArtifactItems(downloadParameters, buildArtifact); IEnumerable<string> fileArtifactPaths = items .Where((item) => item.ItemType == ContainerItemType.File) .Select((fileItem) => Path.Combine(dirPath, fileItem.Path)); allFileArtifactPaths.AddRange(fileArtifactPaths); await DownloadFileContainerAsync(items, downloadParameters, buildArtifact, dirPath, context, cancellationToken, isSingleArtifactDownload: false); } if (downloadParameters.ExtractTars) { ExtractTarsIfPresent(context, allFileArtifactPaths, downloadParameters.TargetDirectory, downloadParameters.ExtractedTarsTempPath); } } private (long, string) ParseContainerId(string resourceData) { // Example of resourceData: "#/7029766/artifacttool-alpine-x64-Debug" string[] segments = resourceData.Split('/'); long containerId; if (segments.Length < 3) { throw new ArgumentException($"Resource data value '{resourceData}' is invalid."); } if (segments.Length >= 3 && segments[0] == "#" && long.TryParse(segments[1], out containerId)) { var artifactName = String.Join('/', segments, 2, segments.Length - 2); return ( containerId, artifactName ); } else { var message = $"Resource data value '{resourceData}' is invalid."; throw new ArgumentException(message, nameof(resourceData)); } } private async Task DownloadFileContainerAsync(IEnumerable<FileContainerItem> items, ArtifactDownloadParameters downloadParameters, BuildArtifact artifact, string rootPath, AgentTaskPluginExecutionContext context, CancellationToken cancellationToken, bool isSingleArtifactDownload = true) { var containerIdAndRoot = ParseContainerId(artifact.Resource.Data); var projectId = downloadParameters.ProjectId; tracer.Info($"Start downloading FCS artifact- {artifact.Name}"); if (!isSingleArtifactDownload && items.Any()) { Directory.CreateDirectory(rootPath); } var folderItems = items.Where(i => i.ItemType == ContainerItemType.Folder); Parallel.ForEach(folderItems, (folder) => { var targetPath = ResolveTargetPath(rootPath, folder, containerIdAndRoot.Item2, downloadParameters.IncludeArtifactNameInPath); Directory.CreateDirectory(targetPath); }); var fileItems = items.Where(i => i.ItemType == ContainerItemType.File); // Only initialize these clients if we know we need to download from Blobstore // If a client cannot connect to Blobstore, we shouldn't stop them from downloading from FCS var downloadFromBlob = !AgentKnobs.DisableBuildArtifactsToBlob.GetValue(context).AsBoolean(); DedupStoreClient dedupClient = null; BlobStoreClientTelemetryTfs clientTelemetry = null; if (downloadFromBlob && fileItems.Any(x => x.BlobMetadata != null)) { try { (dedupClient, clientTelemetry) = await DedupManifestArtifactClientFactory.Instance.CreateDedupClientAsync( false, (str) => this.tracer.Info(str), this.connection, cancellationToken); } catch { // Fall back to streaming through TFS if we cannot reach blobstore downloadFromBlob = false; tracer.Warn(StringUtil.Loc("BlobStoreDownloadWarning")); } } var downloadBlock = NonSwallowingActionBlock.Create<FileContainerItem>( async item => { var targetPath = ResolveTargetPath(rootPath, item, containerIdAndRoot.Item2, downloadParameters.IncludeArtifactNameInPath); var directory = Path.GetDirectoryName(targetPath); Directory.CreateDirectory(directory); await AsyncHttpRetryHelper.InvokeVoidAsync( async () => { tracer.Info($"Downloading: {targetPath}"); if (item.BlobMetadata != null && downloadFromBlob) { await this.DownloadFileFromBlobAsync(context, containerIdAndRoot, targetPath, projectId, item, dedupClient, clientTelemetry, cancellationToken); } else { using (var sourceStream = await this.DownloadFileAsync(containerIdAndRoot, projectId, containerClient, item, cancellationToken)) using (var targetStream = new FileStream(targetPath, FileMode.Create)) { await sourceStream.CopyToAsync(targetStream); } } }, maxRetries: downloadParameters.RetryDownloadCount, cancellationToken: cancellationToken, tracer: tracer, continueOnCapturedContext: false, canRetryDelegate: exception => exception is IOException, context: null ); }, new ExecutionDataflowBlockOptions() { BoundedCapacity = 5000, MaxDegreeOfParallelism = downloadParameters.ParallelizationLimit, CancellationToken = cancellationToken, }); await downloadBlock.SendAllAndCompleteSingleBlockNetworkAsync(fileItems, cancellationToken); // Send results to CustomerIntelligence if (clientTelemetry != null) { var planId = new Guid(context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.PlanId)?.Value ?? Guid.Empty.ToString()); var jobId = new Guid(context.Variables.GetValueOrDefault(WellKnownDistributedTaskVariables.JobId)?.Value ?? Guid.Empty.ToString()); context.PublishTelemetry(area: PipelineArtifactConstants.AzurePipelinesAgent, feature: PipelineArtifactConstants.BuildArtifactDownload, properties: clientTelemetry.GetArtifactDownloadTelemetry(planId, jobId)); } // check files (will throw an exception if a file is corrupt) if (downloadParameters.CheckDownloadedFiles) { CheckDownloads(items, rootPath, containerIdAndRoot.Item2, downloadParameters.IncludeArtifactNameInPath); } } // Returns all artifact items. Uses minimatch filters specified in downloadParameters. private async Task<IEnumerable<FileContainerItem>> GetArtifactItems(ArtifactDownloadParameters downloadParameters, BuildArtifact buildArtifact) { (long, string) containerIdAndRoot = ParseContainerId(buildArtifact.Resource.Data); Guid projectId = downloadParameters.ProjectId; string[] minimatchPatterns = downloadParameters.MinimatchFilters; List<FileContainerItem> items = await containerClient.QueryContainerItemsAsync( containerIdAndRoot.Item1, projectId, isShallow: false, includeBlobMetadata: true, containerIdAndRoot.Item2 ); IEnumerable<Func<string, bool>> minimatcherFuncs = MinimatchHelper.GetMinimatchFuncs( minimatchPatterns, tracer, downloadParameters.CustomMinimatchOptions ); if (minimatcherFuncs != null && minimatcherFuncs.Count() != 0) { items = this.GetFilteredItems(items, minimatcherFuncs); } return items; } private void CheckDownloads(IEnumerable<FileContainerItem> items, string rootPath, string artifactName, bool includeArtifactName) { tracer.Info(StringUtil.Loc("BeginArtifactItemsIntegrityCheck")); var corruptedItems = new List<FileContainerItem>(); foreach (var item in items.Where(x => x.ItemType == ContainerItemType.File)) { var targetPath = ResolveTargetPath(rootPath, item, artifactName, includeArtifactName); var fileInfo = new FileInfo(targetPath); if (fileInfo.Length != item.FileLength) { corruptedItems.Add(item); } } if (corruptedItems.Count > 0) { tracer.Warn(StringUtil.Loc("CorruptedArtifactItemsList")); corruptedItems.ForEach(item => tracer.Warn(item.ItemLocation)); throw new Exception(StringUtil.Loc("IntegrityCheckNotPassed")); } tracer.Info(StringUtil.Loc("IntegrityCheckPassed")); } private async Task<Stream> DownloadFileAsync( (long, string) containerIdAndRoot, Guid scopeIdentifier, FileContainerHttpClient containerClient, FileContainerItem item, CancellationToken cancellationToken) { Stream responseStream = await AsyncHttpRetryHelper.InvokeAsync( async () => { Stream internalResponseStream = await containerClient.DownloadFileAsync(containerIdAndRoot.Item1, item.Path, cancellationToken, scopeIdentifier); return internalResponseStream; }, maxRetries: 5, cancellationToken: cancellationToken, tracer: this.tracer, continueOnCapturedContext: false ); return responseStream; } private async Task DownloadFileFromBlobAsync( AgentTaskPluginExecutionContext context, (long, string) containerIdAndRoot, string destinationPath, Guid scopeIdentifier, FileContainerItem item, DedupStoreClient dedupClient, BlobStoreClientTelemetryTfs clientTelemetry, CancellationToken cancellationToken) { var dedupIdentifier = DedupIdentifier.Deserialize(item.BlobMetadata.ArtifactHash); var downloadRecord = clientTelemetry.CreateRecord<BuildArtifactActionRecord>((level, uri, type) => new BuildArtifactActionRecord(level, uri, type, nameof(DownloadFileContainerAsync), context)); await clientTelemetry.MeasureActionAsync( record: downloadRecord, actionAsync: async () => { return await AsyncHttpRetryHelper.InvokeAsync( async () => { if (item.BlobMetadata.CompressionType == BlobCompressionType.GZip) { using (var targetFileStream = new FileStream(destinationPath, FileMode.Create)) using (var uncompressStream = new GZipStream(targetFileStream, CompressionMode.Decompress)) { await dedupClient.DownloadToStreamAsync(dedupIdentifier, uncompressStream, null, EdgeCache.Allowed, (size) => {}, (size) => {}, cancellationToken); } } else { await dedupClient.DownloadToFileAsync(dedupIdentifier, destinationPath, null, null, EdgeCache.Allowed, cancellationToken); } return dedupClient.DownloadStatistics; }, maxRetries: 3, tracer: tracer, canRetryDelegate: e => true, context: nameof(DownloadFileFromBlobAsync), cancellationToken: cancellationToken, continueOnCapturedContext: false); }); } private string ResolveTargetPath(string rootPath, FileContainerItem item, string artifactName, bool includeArtifactName) { if (includeArtifactName) { return Path.Combine(rootPath, item.Path); } //Example of item.Path&artifactName: item.Path = "drop3", "drop3/HelloWorld.exe"; artifactName = "drop3" string tempArtifactName; if (item.Path.Length == artifactName.Length) { tempArtifactName = artifactName; } else if (item.Path.Length > artifactName.Length) { tempArtifactName = artifactName + "/"; } else { throw new ArgumentException($"Item path {item.Path} cannot be smaller than artifact {artifactName}"); } var itemPathWithoutDirectoryPrefix = item.Path.Replace(tempArtifactName, String.Empty); var absolutePath = Path.Combine(rootPath, itemPathWithoutDirectoryPrefix); return absolutePath; } private List<FileContainerItem> GetFilteredItems(List<FileContainerItem> items, IEnumerable<Func<string, bool>> minimatchFuncs) { List<FileContainerItem> filteredItems = new List<FileContainerItem>(); foreach (FileContainerItem item in items) { if (minimatchFuncs.Any(match => match(item.Path))) { filteredItems.Add(item); } } var excludedItems = items.Except(filteredItems); foreach (FileContainerItem item in excludedItems) { tracer.Info($"Item excluded: {item.Path}"); } return filteredItems; } // Checks all specified artifact paths, searches for files ending with '.tar'. // If any files were found, extracts them to extractedTarsTempPath and moves to rootPath/extracted_tars. private void ExtractTarsIfPresent(AgentTaskPluginExecutionContext context, IEnumerable<string> fileArtifactPaths, string rootPath, string extractedTarsTempPath) { tracer.Info(StringUtil.Loc("TarSearchStart")); int tarsFoundCount = 0; foreach (var fileArtifactPath in fileArtifactPaths) { if (fileArtifactPath.EndsWith(".tar")) { tarsFoundCount += 1; // fileArtifactPath is a combination of rootPath and the relative artifact path string relativeFileArtifactPath = fileArtifactPath.Substring(rootPath.Length); string relativeFileArtifactDirPath = Path.GetDirectoryName(relativeFileArtifactPath).TrimStart('/'); string extractedFilesDir = Path.Combine(extractedTarsTempPath, relativeFileArtifactDirPath); ExtractTar(fileArtifactPath, extractedFilesDir); File.Delete(fileArtifactPath); } } if (tarsFoundCount == 0) { context.Warning(StringUtil.Loc("TarsNotFound")); } else { tracer.Info(StringUtil.Loc("TarsFound", tarsFoundCount)); string targetDirectory = Path.Combine(rootPath, "extracted_tars"); Directory.CreateDirectory(targetDirectory); MoveDirectory(extractedTarsTempPath, targetDirectory); } } // Extracts tar archive at tarArchivePath to extractedFilesDir. // Uses 'tar' utility like this: tar xf `tarArchivePath` --directory `extractedFilesDir`. // Throws if any errors are encountered. private void ExtractTar(string tarArchivePath, string extractedFilesDir) { tracer.Info(StringUtil.Loc("TarExtraction", tarArchivePath)); Directory.CreateDirectory(extractedFilesDir); var extractionProcessInfo = new ProcessStartInfo("tar") { Arguments = $"xf {tarArchivePath} --directory {extractedFilesDir}", UseShellExecute = false, RedirectStandardError = true }; Process extractionProcess = Process.Start(extractionProcessInfo); extractionProcess.WaitForExit(); var extractionStderr = extractionProcess.StandardError.ReadToEnd(); if (extractionStderr.Length != 0 || extractionProcess.ExitCode != 0) { throw new Exception(StringUtil.Loc("TarExtractionError", tarArchivePath, extractionStderr)); } } // Recursively moves sourcePath directory to targetPath private void MoveDirectory(string sourcePath, string targetPath) { var sourceDirectoryInfo = new DirectoryInfo(sourcePath); foreach (FileInfo file in sourceDirectoryInfo.GetFiles("*", SearchOption.TopDirectoryOnly)) { file.MoveTo(Path.Combine(targetPath, file.Name), true); } foreach (DirectoryInfo subdirectory in sourceDirectoryInfo.GetDirectories("*", SearchOption.TopDirectoryOnly)) { string subdirectoryDestinationPath = Path.Combine(targetPath, subdirectory.Name); var subdirectoryDestination = new DirectoryInfo(subdirectoryDestinationPath); if (subdirectoryDestination.Exists) { MoveDirectory( Path.Combine(sourcePath, subdirectory.Name), Path.Combine(targetPath, subdirectory.Name) ); } else { subdirectory.MoveTo(Path.Combine(targetPath, subdirectory.Name)); } } } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using Microsoft.VisualStudio.Services.Agent.Util; using Newtonsoft.Json; using System; using System.IO; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Globalization; namespace Microsoft.VisualStudio.Services.Agent.Worker.Release { [ServiceLocator(Default = typeof(ReleaseTrackingManager))] public interface IReleaseTrackingManager : IAgentService { ReleaseTrackingConfig LoadIfExists(IExecutionContext executionContext, string file); void MarkExpiredForGarbageCollection(IExecutionContext executionContext, TimeSpan expiration); void DisposeCollectedGarbage(IExecutionContext executionContext); } public sealed class ReleaseTrackingManager : AgentService, IReleaseTrackingManager { public ReleaseTrackingConfig LoadIfExists(IExecutionContext executionContext, string file) { Trace.Entering(); // The tracking config will not exist for a new definition. if (!File.Exists(file)) { return null; } string content = File.ReadAllText(file); return JsonConvert.DeserializeObject<ReleaseTrackingConfig>(content); } private void MarkForGarbageCollection(IExecutionContext executionContext, ReleaseTrackingConfig config) { Trace.Entering(); // Write a copy of the tracking config to the GC folder. string gcDirectory = Path.Combine( HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Release.Path.RootMappingDirectory, Constants.Release.Path.GarbageCollectionDirectory); string file = Path.Combine( gcDirectory, StringUtil.Format("{0}.json", Guid.NewGuid())); WriteToFile(file, config); } public void MarkExpiredForGarbageCollection(IExecutionContext executionContext, TimeSpan expiration) { Trace.Entering(); Trace.Info("Scan all SourceFolder tracking files."); string searchRoot = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Release.Path.RootMappingDirectory); if (!Directory.Exists(searchRoot)) { executionContext.Output(StringUtil.Loc("GCDirNotExist", searchRoot)); return; } var allTrackingFiles = Directory.EnumerateFiles(searchRoot, Constants.Release.Path.TrackingConfigFile, SearchOption.AllDirectories); Trace.Verbose($"Find {allTrackingFiles.Count()} tracking files."); executionContext.Output(StringUtil.Loc("DirExpireLimit", expiration.TotalDays)); executionContext.Output(StringUtil.Loc("CurrentUTC", DateTime.UtcNow.ToString("o"))); // scan all sourcefolder tracking file, find which folder has never been used since UTC-expiration // the scan and garbage discovery should be best effort. // if the tracking file is in old format, just delete the folder since the first time the folder been use we will convert the tracking file to new format. foreach (var trackingFile in allTrackingFiles) { try { executionContext.Output(StringUtil.Loc("EvaluateReleaseTrackingFile", trackingFile)); ReleaseTrackingConfig tracking = LoadIfExists(executionContext, trackingFile); if (tracking.LastRunOn == null) { Trace.Verbose($"{trackingFile} is a old format tracking file."); executionContext.Output(StringUtil.Loc("GCOldFormatTrackingFile", trackingFile)); MarkForGarbageCollection(executionContext, tracking); IOUtil.DeleteFile(trackingFile); } else { Trace.Verbose($"{trackingFile} is a new format tracking file."); ArgUtil.NotNull(tracking.LastRunOn, nameof(tracking.LastRunOn)); executionContext.Output(StringUtil.Loc("ReleaseDirLastUseTime", Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), tracking.ReleaseDirectory), tracking.LastRunOn?.ToString("u"))); if (DateTime.UtcNow - expiration > tracking.LastRunOn) { executionContext.Output(StringUtil.Loc("GCUnusedTrackingFile", trackingFile, expiration.TotalDays)); MarkForGarbageCollection(executionContext, tracking); IOUtil.DeleteFile(trackingFile); } } } catch (Exception ex) { executionContext.Error(StringUtil.Loc("ErrorDuringReleaseGC", trackingFile)); executionContext.Error(ex); } } } public void DisposeCollectedGarbage(IExecutionContext executionContext) { ArgUtil.NotNull(executionContext, nameof(executionContext)); Trace.Entering(); PrintOutDiskUsage(executionContext); string gcDirectory = Path.Combine( HostContext.GetDirectory(WellKnownDirectory.Work), Constants.Release.Path.RootMappingDirectory, Constants.Release.Path.GarbageCollectionDirectory); if (!Directory.Exists(gcDirectory)) { executionContext.Output(StringUtil.Loc("GCReleaseDirNotExist", gcDirectory)); return; } IEnumerable<string> gcTrackingFiles = Directory.EnumerateFiles(gcDirectory, "*.json"); if (gcTrackingFiles == null || gcTrackingFiles.Count() == 0) { executionContext.Output(StringUtil.Loc("GCReleaseDirIsEmpty", gcDirectory)); return; } Trace.Info($"Find {gcTrackingFiles.Count()} GC tracking files."); if (gcTrackingFiles.Count() > 0) { foreach (string gcFile in gcTrackingFiles) { // maintenance has been cancelled. executionContext.CancellationToken.ThrowIfCancellationRequested(); try { var gcConfig = LoadIfExists(executionContext, gcFile) as ReleaseTrackingConfig; ArgUtil.NotNull(gcConfig, nameof(ReleaseTrackingConfig)); string fullPath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Work), gcConfig.ReleaseDirectory); executionContext.Output(StringUtil.Loc("Deleting", fullPath)); IOUtil.DeleteDirectory(fullPath, executionContext.CancellationToken); executionContext.Output(StringUtil.Loc("DeleteGCTrackingFile", fullPath)); IOUtil.DeleteFile(gcFile); } catch (Exception ex) { executionContext.Error(StringUtil.Loc("ErrorDuringReleaseGCDelete", gcFile)); executionContext.Error(ex); } } PrintOutDiskUsage(executionContext); } } private void PrintOutDiskUsage(IExecutionContext context) { // Print disk usage should be best effort, since DriveInfo can't detect usage of UNC share. try { context.Output($"Disk usage for working directory: {HostContext.GetDirectory(WellKnownDirectory.Work)}"); var workDirectoryDrive = new DriveInfo(HostContext.GetDirectory(WellKnownDirectory.Work)); long freeSpace = workDirectoryDrive.AvailableFreeSpace; long totalSpace = workDirectoryDrive.TotalSize; if (PlatformUtil.RunningOnWindows) { context.Output($"Working directory belongs to drive: '{workDirectoryDrive.Name}'"); } else { context.Output($"Information about file system on which working directory resides."); } context.Output($"Total size: '{totalSpace / 1024.0 / 1024.0} MB'"); context.Output($"Available space: '{freeSpace / 1024.0 / 1024.0} MB'"); } catch (Exception ex) { context.Warning($"Unable inspect disk usage for working directory {HostContext.GetDirectory(WellKnownDirectory.Work)}."); Trace.Error(ex); context.Debug(ex.ToString()); } } private void WriteToFile(string file, object value) { Trace.Entering(); Trace.Verbose($"Writing config to file: {file}"); // Create the directory if it does not exist. Directory.CreateDirectory(Path.GetDirectoryName(file)); IOUtil.SaveObject(value, file); } } }
//------------------------------------------------------------------------------ // <copyright file="TdsParserSessionPool.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System; using System.Collections.Generic; using System.Data.Common; using System.Data.ProviderBase; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Collections.Concurrent; internal class TdsParserSessionPool { // NOTE: This is a very simplistic, lightweight pooler. It wasn't // intended to handle huge number of items, just to keep track // of the session objects to ensure that they're cleaned up in // a timely manner, to avoid holding on to an unacceptible // amount of server-side resources in the event that consumers // let their data readers be GC'd, instead of explicitly // closing or disposing of them private const int MaxInactiveCount = 10; // pick something, preferably small... private static int _objectTypeCount; // Bid counter private readonly int _objectID = System.Threading.Interlocked.Increment(ref _objectTypeCount); private readonly TdsParser _parser; // parser that owns us private readonly List<TdsParserStateObject> _cache; // collection of all known sessions private int _cachedCount; // lock-free _cache.Count private TdsParserStateObject[] _freeStateObjects; // collection of all sessions available for reuse private int _freeStateObjectCount; // Number of available free sessions internal TdsParserSessionPool(TdsParser parser) { _parser = parser; _cache = new List<TdsParserStateObject>(); _freeStateObjects = new TdsParserStateObject[MaxInactiveCount]; _freeStateObjectCount = 0; if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.ctor|ADV> %d# created session pool for parser %d\n", ObjectID, parser.ObjectID); } } private bool IsDisposed { get { return (null == _freeStateObjects); } } internal int ObjectID { get { return _objectID; } } internal void Deactivate() { // When being deactivated, we check all the sessions in the // cache to make sure they're cleaned up and then we dispose of // sessions that are past what we want to keep around. IntPtr hscp; Bid.ScopeEnter(out hscp, "<sc.TdsParserSessionPool.Deactivate|ADV> %d# deactivating cachedCount=%d\n", ObjectID, _cachedCount); try { lock(_cache) { // NOTE: The PutSession call below may choose to remove the // session from the cache, which will throw off our // enumerator. We avoid that by simply indexing backward // through the array. for (int i = _cache.Count - 1; i >= 0 ; i--) { TdsParserStateObject session = _cache[i]; if (null != session) { if (session.IsOrphaned) { // if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.Deactivate|ADV> %d# reclaiming session %d\n", ObjectID, session.ObjectID); } PutSession(session); } } } // } } finally { Bid.ScopeLeave(ref hscp); } } // This is called from a ThreadAbort - ensure that it can be run from a CER Catch internal void BestEffortCleanup() { for (int i = 0; i < _cache.Count; i++) { TdsParserStateObject session = _cache[i]; if (null != session) { var sessionHandle = session.Handle; if (sessionHandle != null) { sessionHandle.Dispose(); } } } } internal void Dispose() { if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.Dispose|ADV> %d# disposing cachedCount=%d\n", ObjectID, _cachedCount); } lock(_cache) { // Dispose free sessions for (int i = 0; i < _freeStateObjectCount; i++) { if (_freeStateObjects[i] != null) { _freeStateObjects[i].Dispose(); } } _freeStateObjects = null; _freeStateObjectCount = 0; // Dispose orphaned sessions for (int i = 0; i < _cache.Count; i++) { if (_cache[i] != null) { if (_cache[i].IsOrphaned) { _cache[i].Dispose(); } else { // Remove the "initial" callback (this will allow the stateObj to be GC collected if need be) _cache[i].DecrementPendingCallbacks(false); } } } _cache.Clear(); _cachedCount = 0; // Any active sessions will take care of themselves // (It's too dangerous to dispose them, as this can cause AVs) } } internal TdsParserStateObject GetSession(object owner) { TdsParserStateObject session; lock (_cache) { if (IsDisposed) { throw ADP.ClosedConnectionError(); } else if (_freeStateObjectCount > 0) { // Free state object - grab it _freeStateObjectCount--; session = _freeStateObjects[_freeStateObjectCount]; _freeStateObjects[_freeStateObjectCount] = null; Debug.Assert(session != null, "There was a null session in the free session list?"); } else { // No free objects, create a new one session = _parser.CreateSession(); if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.CreateSession|ADV> %d# adding session %d to pool\n", ObjectID, session.ObjectID); } _cache.Add(session); _cachedCount = _cache.Count; } session.Activate(owner); } if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.GetSession|ADV> %d# using session %d\n", ObjectID, session.ObjectID); } return session; } internal void PutSession(TdsParserStateObject session) { Debug.Assert (null != session, "null session?"); //Debug.Assert(null != session.Owner, "session without owner?"); bool okToReuse = session.Deactivate(); lock (_cache) { if (IsDisposed) { // We're diposed - just clean out the session Debug.Assert(_cachedCount == 0, "SessionPool is disposed, but there are still sessions in the cache?"); session.Dispose(); } else if ((okToReuse) && (_freeStateObjectCount < MaxInactiveCount)) { // Session is good to re-use and our cache has space if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.PutSession|ADV> %d# keeping session %d cachedCount=%d\n", ObjectID, session.ObjectID, _cachedCount); } Debug.Assert(!session._pendingData, "pending data on a pooled session?"); _freeStateObjects[_freeStateObjectCount] = session; _freeStateObjectCount++; } else { // Either the session is bad, or we have no cache space - so dispose the session and remove it if (Bid.AdvancedOn) { Bid.Trace("<sc.TdsParserSessionPool.PutSession|ADV> %d# disposing session %d cachedCount=%d\n", ObjectID, session.ObjectID, _cachedCount); } bool removed = _cache.Remove(session); Debug.Assert(removed, "session not in pool?"); _cachedCount = _cache.Count; session.Dispose(); } session.RemoveOwner(); } } internal string TraceString() { return String.Format(/*IFormatProvider*/ null, "(ObjID={0}, free={1}, cached={2}, total={3})", _objectID, null == _freeStateObjects ? "(null)" : _freeStateObjectCount.ToString((IFormatProvider) null), _cachedCount, _cache.Count); } internal int ActiveSessionsCount { get { return _cachedCount - _freeStateObjectCount; } } } }
using System; using System.Collections; using System.Text; using Inform; using System.Data; using System.Web; namespace Xenosynth.Web.UI { /// <summary> /// The base class for directories in the Xenosynth CMS. /// </summary> [TypeMapping(BaseType = typeof(CmsFile))] public abstract class CmsDirectory : CmsFile { [MemberMapping(ColumnName = "IsRestricted")] protected bool isRestricted; private CmsFileCollection files; private CmsDirectoryCollection subdirectories; protected CmsDirectory(Guid fileTypeID) : base(fileTypeID) { } /// <summary> /// Returns both a collection of both pages and subdirectories. /// </summary> public CmsFileCollection Files { get { if (files == null) { files = CmsFile.FindByDirectoryID(this.FileID); } return files; } } /// <summary> /// Returns both a collection of pages and subdirectories that are not hidden. /// </summary> public CmsFileCollection DisplayedFiles { get { return new CmsFileCollection(FindDisplayed(Files)); } } public bool HasFiles { get { return (Files.Count > 0); } } /// <summary> /// Returns a collection of directories under this directory. /// </summary> public CmsDirectoryCollection Subdirectories { get { if (subdirectories == null) { subdirectories = CmsDirectory.FindDirectoryByDirectoryID(this.FileID); } return subdirectories; } } /// <summary> /// Returns a collection of directories under this directory that are not hidden. /// </summary> public CmsDirectoryCollection DisplayedSubdirectories { get { return new CmsDirectoryCollection(FindDisplayed(Subdirectories)); } } /// <summary> /// Finds all directories for a directory. /// </summary> /// <param name="directoryID"> /// A <see cref="Guid"/> /// </param> /// <returns> /// A <see cref="CmsDirectoryCollection"/> /// </returns> public static CmsDirectoryCollection FindDirectoryByDirectoryID(Guid directoryID) { return FindDirectoryByDirectoryID(directoryID, CmsHttpContext.Current.Mode != CmsMode.Published); } /// <summary> /// Finds a the subdirectories for a directory. /// </summary> /// <param name="directoryID"> /// A <see cref="Guid"/> /// </param> /// <param name="showUnpublished"> /// A <see cref="System.Boolean"/> /// </param> /// <returns> /// A <see cref="CmsDirectoryCollection"/> /// </returns> public static CmsDirectoryCollection FindDirectoryByDirectoryID(Guid directoryID, bool showUnpublished) { DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); IFindCollectionCommand cmd = null; if (!showUnpublished) { if (HttpContext.Current.User != null && HttpContext.Current.User.Identity.IsAuthenticated && CmsContext.Current.IsInAuthoringRole(HttpContext.Current.User)) { cmd = ds.CreateFindCollectionCommand(typeof(CmsDirectory), "WHERE ParentID = @ParentID AND State = @State ORDER BY SortOrder", true); cmd.CreateInputParameter("@State", CmsState.Published); } else { //enforce dates cmd = ds.CreateFindCollectionCommand(typeof(CmsDirectory), "WHERE ParentID = @ParentID AND State = @State AND (CmsFiles.PublishStart IS NULL OR CmsFiles.PublishStart < @Date) AND (CmsFiles.PublishEnd IS NULL OR CmsFiles.PublishEnd > @Date) ORDER BY SortOrder", true); cmd.CreateInputParameter("@State", CmsState.Published); cmd.CreateInputParameter("@Date", DateTime.Now); } } else { //TODO: switch to fileID? cmd = ds.CreateFindCollectionCommand(typeof(CmsDirectory), "WHERE CmsFiles.ParentID = @ParentID AND State < @State AND CmsFiles.ID NOT IN (SELECT CmsFiles.RevisionSourceID FROM CmsFiles WHERE NOT CmsFiles.RevisionSourceID IS NULL) ORDER BY SortOrder", true); cmd.CreateInputParameter("@State", CmsState.Deleted); } cmd.CreateInputParameter("@ParentID", directoryID); return new CmsDirectoryCollection(cmd.Execute()); } /// <summary> /// This method supports the Xenosynth CMS Module and is not intended to be used directly from your code. /// </summary> /// <param name="files"> /// A <see cref="CmsFileCollection"/> /// </param> /// <returns> /// A <see cref="IList"/> /// </returns> protected IList FindDisplayed(CmsFileCollection files) { ArrayList displayedFiles = new ArrayList(); foreach (CmsFile f in files) { if (!f.IsHidden) { displayedFiles.Add(f); } } return displayedFiles; } /// <summary> /// Reorders and incrementally updates the sort order of the pages after adding or removing pages. /// </summary> public void UpdateSortOrder() { CmsFileCollection files = this.Files; int i = 0; foreach (CmsFile f in files) { f.SortOrder = i++; f.Update(); //TODO: Fire full update with Audit Logging? } } public void RefreshDescendentFullPaths() { foreach (CmsFile f in Files) { f.RefreshFullPath(); f.Update(); if (f.FileType.IsDirectory) { CmsDirectory dir = (CmsDirectory)f; dir.RefreshDescendentFullPaths(); } } } /// <summary> /// Marks this CmsDirectory as deleted. /// </summary> public override void Delete() { if (HasFiles) { throw new ApplicationException("Can not delete CmsDirectory that has dependencies."); } base.Delete(); } /// <summary> /// Deletes this CmsDirectory from the database. /// </summary> public override void PermanentlyDelete() { if (HasFiles) { throw new ApplicationException("Can not permanently delete CmsDirectory that has dependencies."); } base.PermanentlyDelete(); } /// <summary> /// Finds all CmsFiles in this directory that have all the specified attributes. /// </summary> /// <param name="recursive"> /// A <see cref="System.Boolean"/> /// </param> /// <param name="attributes"> /// A <see cref="CmsAttribute[]"/> /// </param> /// <returns> /// A <see cref="IList"/> of CmsFiles. /// </returns> public IList FindFilesByAttributes(bool recursive, params CmsAttribute[] attributes) { //TODO: Faster search! Recursive? CmsFileCollection files = this.Files; ArrayList selectedFiles = new ArrayList(); foreach (CmsFile f in files) { bool hasAll = true; foreach (CmsAttribute attr in attributes) { bool found = false; string[] values = f.Attributes.GetValues(attr.Name); if (values != null) { foreach (string v in values) { if (v == attr.Value) { found = true; break; } } } if (!found) { hasAll = false; break; } } if (hasAll) { selectedFiles.Add(f); } if(recursive && f.FileType.IsDirectory){ CmsDirectory d = (CmsDirectory)f; selectedFiles.AddRange(d.FindFilesByAttributes(recursive, attributes)); } } return selectedFiles; } /// <summary> /// Finds all the CmsFiles in the directory that has any of the specified attributes. /// </summary> /// <param name="recursive"> /// A <see cref="System.Boolean"/> /// </param> /// <param name="attributes"> /// A <see cref="CmsAttribute[]"/> /// </param> /// <returns> /// A <see cref="IList"/> /// </returns> public IList FindFilesByAnyAttributes(bool recursive, params CmsAttribute[] attributes) { //TODO: Faster search! Recursive? CmsFileCollection files = this.Files; ArrayList selectedFiles = new ArrayList(); foreach (CmsFile f in files) { bool hasAll = true; foreach (CmsAttribute attr in attributes) { bool found = false; string[] values = f.Attributes.GetValues(attr.Name); if (values != null) { foreach (string v in values) { if (v == attr.Value) { selectedFiles.Add(f); break; } } } } if (recursive && f.FileType.IsDirectory) { CmsDirectory d = (CmsDirectory)f; selectedFiles.AddRange(d.FindFilesByAttributes(recursive, attributes)); } } return selectedFiles; } /// <summary> /// Gets a list of all the unique <see cref="String"> values for the attribute in this directory. /// </summary> /// <param name="name"> /// A <see cref="System.String"/> /// </param> /// <param name="attributes"> /// A <see cref="CmsAttribute[]"/> /// </param> /// <returns> /// A <see cref="IList"/> /// </returns> public IList FindUniqueAttributeValues(string name, params CmsAttribute[] attributes) { IList files = this.FindFilesByAttributes(false, attributes); ArrayList list = new ArrayList(); foreach (CmsFile f in files) { string[] values = f.Attributes.GetValues(name); if (values != null) { foreach (string v in values) { if (!list.Contains(v)) { list.Add(v); } } } } list.Sort(); return list; } /// <summary> /// Gets a list of all the unique <see cref="String"> values for the attribute in this directory. /// </summary> /// <param name="name"> /// A <see cref="System.String"/> /// </param> /// <param name="recursive"> /// A <see cref="System.Boolean"/> /// </param> /// <returns> /// A <see cref="System.String[]"/> /// </returns> public string[] FindUniqueAttributeValues(string name, bool recursive) { string sql = null; if (recursive) { sql = @" SELECT DISTINCT Value FROM CmsFileAttributes WHERE Name = @Name AND FileID IN ( SELECT ID FROM CmsFiles WHERE State >= @State1 AND State < @State2 AND FullPath LIKE @FullPath ) ORDER BY Value "; } else { sql = @" SELECT DISTINCT Value FROM CmsFileAttributes WHERE Name = @Name AND FileID IN ( SELECT ID FROM CmsFiles WHERE State >= @State1 AND State < @State2 AND ParentID = @ParentID ) ORDER BY Value "; } DataStore ds = DataStoreServices.GetDataStore("Xenosynth"); IDataAccessCommand cmd = ds.CreateDataAccessCommand(sql); cmd.CreateInputParameter("@Name", name); if (recursive) { cmd.CreateInputParameter("@FullPath", this.FullPath + "%"); } else { cmd.CreateInputParameter("@ParentID", this.ID); } cmd.CreateInputParameter("@State1", CmsHttpContext.Current.SearchScopeLowerBound); cmd.CreateInputParameter("@State2", CmsHttpContext.Current.SearchScopeUpperBound); IDataReader r = cmd.ExecuteReader(); ArrayList values = new ArrayList(); while (r.Read()) { values.Add(r["Value"].ToString()); } return (string[])values.ToArray(typeof(string)); } public virtual CmsFile DefaultFile { //TODO: Expand this logic! get { return this.Files[0]; } } public virtual string DefaultFileName { get { if (DefaultFile == null) { return null; } else { return DefaultFile.FileName; } } } } }
using System; using NUnit.Framework; using System.Collections.Generic; namespace ProtoFFITests { public class TestData { public static double MultiplyDoubles(double x, double y) { return x * y; } public static double MultiplyFloats(float x, float y) { return x * y; } public static float GetFloat() { return 2.5F; } public static decimal MultiplyDecimals(decimal x, decimal y) { return Decimal.Multiply(x, y); } public static byte IncrementByte(byte value) { return ++value; } public static sbyte IncrementSByte(sbyte value) { return ++value; } public static char GetAlphabet(int index) { int c = 'a'; return (char)(c + index); } public static char ToUpper(char c) { return char.ToUpper(c); } public static char ToChar(object o) { return (char)(int)o; } public static int ToAscii(char c) { return c; } public static int Combine(byte x, byte y) { return x << 8 | y; } public static long MultiplyShorts(short x, short y) { return x * y; } public static long MultiplyUShorts(ushort x, ushort y) { return x * y; } public static long MultiplyUInts(uint x, uint y) { return x * y; } public static ulong MultiplyULongs(ulong x, ulong y) { return x * y; } public static bool Equals(float x, float y) { return Math.Abs(x - y) < 0.0001; } public static bool Equals(Decimal x, Decimal y) { return Decimal.Equals(x, y); } public static IEnumerable<int> GetSomePrimes() { return new List<int> { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 }; } public static IEnumerable<int> GetNumbersByDouble(int x) { for (int i = 0; i < x; ++i) { yield return i * 2; } } public static IEnumerable<int> DoubleThem(IEnumerable<int> nums) { foreach (var item in nums) { yield return item * 2; } } public object[] GetMixedObjects() { object[] objs = { new DerivedDummy(), new Derived1(), new TestDispose(), new DummyDispose() }; return objs; } public override bool Equals(Object obj) { return true; } public object FuncReturningVariousObjectTypes(int x) { switch (x) { case 0: { ulong u = 1; return u; } case 1: { Byte b = 1; return b; } case 2: { sbyte s = 1; return s; } case 3: { short s = 1; return s; } case 4: { UInt16 u = 1; return u; } case 5: { return new DummyDispose(); } case 6: { UInt64 u = 1; return u; } case 7: { char c = '1'; return c; } case 8: { float f = 1; return f; } case 9: { Decimal d = 1; return d; } case 10: { ushort u = 1; return u; } case 11: { return new DerivedDummy(); } case 12: { return new TestDisposeDerived(); } case 13: { return new Derived1(); } case 14: { return new TestDispose(); } case 15: { string s = "test"; return s; } case 16: { int i = 1; return i; } case 17: { double d = 1; return d; } case 18: { Boolean b = true; return b; } default: return 0; } } public int TestUlong(ulong x) { if (x == 1) return 1; else return 0; } public int TestUlong2(object x) { ulong y = Convert.ToUInt64(x); if (y == 1) return 1; else return 0; } public int TestByte(Byte x) { if (x == 1) return 1; else return 0; } public int TestSbyte(sbyte x) { if (x == 1) return 1; else return 0; } public int TestShort(short x) { if (x == 1) return 1; else return 0; } public int TestUint16(UInt16 x) { if (x == 1) return 1; else return 0; } public int TestDummyDispose(DummyDispose x) { return x.Value; } public int TestUint64(UInt64 x) { if (x == 1) return 1; else return 0; } public int TestChar(Char x) { if (x == '1') return 1; else return 0; } public int TestFloat(float x) { if (x == 1) return 1; else return 0; } public int TestDecimal(Decimal x) { if (x == 1) return 1; else return 0; } public int TestUshort(ushort x) { if (x == 1) return 1; else return 0; } public double TestDerivedDummy(DerivedDummy x) { return x.random123(); } public int TestDerivedDummyClass(DerivedDummy x) { return x.random123(); } public int TestDerivedDisposeClass(TestDisposeDerived x) { return x.get_MyValue(); } public double TestDerived1(Derived1 x) { return x.GetNumber(); } public int TestDisposeClass(TestDispose x) { return x.get_MyValue(); } public int TestString(String x) { return x.Length; } public int TestInt(int x) { return x; } public int TestInt2(object x) { int y = Convert.ToInt32(x); return y; } public int TestDouble(Double x) { if (x == 1) return 1; else return 0; } public int TestBoolean(Boolean x) { if (x == true) return 1; else return 0; } public int TestIEnumerable(IEnumerable<int> x) { IEnumerator<int> y2 = x.GetEnumerator(); y2.Reset(); y2.MoveNext(); return y2.Current; } public int TestIEnumerable2(object x) { IEnumerable<int> y = (IEnumerable<int>)x; IEnumerator<int> y2 = y.GetEnumerator(); y2.Reset(); y2.MoveNext(); return y2.Current; } public object GetIEnumerable() { return new List<int> { 2, 2, 2, 2 }; } public object GetInt() { int x = 1; return x; } public object GetUlong() { ulong x = 1; return x; } public Object FuncReturningByteAsObject() { Byte b = 1; return b; } public double FuncVerifyingVariousObjectTypes(object y, int x) { switch (x) { case 0: return this.TestUlong(Convert.ToUInt64(y)); case 1: return this.TestByte(Convert.ToByte(y)); case 2: return this.TestSbyte(Convert.ToSByte(y)); case 3: return this.TestShort(Convert.ToInt16(y)); case 4: return this.TestUint16(Convert.ToUInt16(y)); case 5: return this.TestDummyDispose((DummyDispose)y); case 6: return this.TestUint64(Convert.ToUInt64(y)); case 7: return this.TestChar(Convert.ToChar(y)); case 8: return this.TestFloat(Convert.ToSingle(y)); case 9: return this.TestDecimal(Convert.ToDecimal(y)); case 10: return this.TestUshort(Convert.ToUInt16(y)); case 11: return this.TestDerivedDummyClass((DerivedDummy)y); case 12: return this.TestDerivedDisposeClass((TestDisposeDerived)y); case 13: return this.TestDerived1((Derived1)y); case 14: return this.TestDisposeClass((TestDispose)y); case 15: return this.TestString(Convert.ToString(y)); case 16: return this.TestInt(Convert.ToInt32(y)); case 17: return this.TestDouble(Convert.ToDouble(y)); case 18: return this.TestBoolean(Convert.ToBoolean(y)); default: return -1; } } public object CreateInternalClass(int y) { return InternalClass.CreateObject(5); } public int TestInternalClass(object y) { InternalClass x = (InternalClass)y; return x.GetValue(); } } internal class InternalClass { private int x = 5; public static InternalClass CreateObject(int y) { return new InternalClass { x = y }; } public int GetValue() { return x; } } public class MethodOverloadingClass { float f = 1.5F; public float GetValue() { return f; } public int foo(double x) { return 1; } public int foo(float x) { return 0; } } class CSFFIDataMarshalingTest : FFITestSetup { [Test] public void TestDoubles() { String code = @" //import(""ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null""); value = TestData.MultiplyDoubles(11111, 11111); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "value", ExpectedValue = 123454321.0, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestFloats() { String code = @" value = TestData.MultiplyFloats(111.11, 1111.1); success = TestData.Equals(value, 123454.321); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "success", ExpectedValue = true, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestFloatOut() { String code = @" value = TestData.GetFloat(); success = TestData.Equals(value, 2.5); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "success", ExpectedValue = true, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestFloatsOutOfRangeWarning() { String code = @" value = TestData.MultiplyFloats(3.40282e+039, 0.001); "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = null; Assert.IsTrue(ExecuteAndVerify(code, data) == 1); } [Test] public void TestDecimals() { String code = @" import(TestData from ""ProtoTest.dll""); import(""System.Decimal""); x = Decimal.Decimal(1.1111e+10); y = Decimal.Decimal(1.1111e+5); value = TestData.MultiplyDecimals(x, y); result = Decimal.Decimal(1.23454321e+15); success = Decimal.Equals(value, result); "; ValidationData[] data = { new ValidationData { ValueName = "success", ExpectedValue = true, BlockIndex = 0 } }; int nErrors = -1; ExecuteAndVerify(code, data, out nErrors); Assert.IsTrue(nErrors == 0); } [Test] public void TestChar() { String code = @" f = TestData.GetAlphabet(5); //5th alphabet c = TestData.ToUpper(f); F = TestData.ToAscii(c); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); int F = 'F'; ValidationData[] data = { new ValidationData { ValueName = "F", ExpectedValue = F, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestCharOutOfRangeWarning() { String code = @" XYZ = TestData.ToUpper(70000); //out of range char value. "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = null; ExecuteAndVerify(code, data); } [Test] public void TestByte() { String code = @" f = TestData.IncrementByte(101); c = TestData.ToUpper(TestData.ToChar(f)); F = TestData.ToAscii(c); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); int F = 'F'; ValidationData[] data = { new ValidationData { ValueName = "F", ExpectedValue = F, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestByteOutOfRangeWarning() { String code = @" XYZ = TestData.IncrementByte(257); //out of range byte value. "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = null; Assert.IsTrue(ExecuteAndVerify(code, data) == 1); } [Test] public void TestSByte() { String code = @" f = TestData.IncrementSByte(101); c = TestData.ToUpper(TestData.ToChar(f)); F = TestData.ToAscii(c); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); int F = 'F'; ValidationData[] data = { new ValidationData { ValueName = "F", ExpectedValue = F, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestSByteOutOfRangeWarning() { String code = @" XYZ = TestData.IncrementSByte(257); //out of range sbyte value. "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = null; Assert.IsTrue(ExecuteAndVerify(code, data) == 1); } [Test] public void TestCombineByte() { String code = @" value = TestData.Combine(100, 100); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "value", ExpectedValue = 25700, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestShort() { String code = @" value = TestData.MultiplyShorts(100, 100); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "value", ExpectedValue = 10000, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestUShort() { String code = @" value = TestData.MultiplyUShorts(100, 100); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "value", ExpectedValue = 10000, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestUInt() { String code = @" value = TestData.MultiplyUInts(100, 100); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "value", ExpectedValue = 10000, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestULong() { String code = @" value = TestData.MultiplyULongs(100, 100); "; Type t = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "value", ExpectedValue = 10000, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestNullForPrimitiveType() //Defect 1462014 { String code = @" bytevalue = TestData.IncrementSByte(null); dvalue = TestData.MultiplyDoubles(bytevalue, 45.0); fvalue = TestData.MultiplyFloats(dvalue, 2324.0); ulvalue = TestData.MultiplyULongs(dvalue, fvalue); "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "bytevalue", ExpectedValue = null, BlockIndex = 0 }, new ValidationData { ValueName = "dvalue", ExpectedValue = null, BlockIndex = 0 }, new ValidationData { ValueName = "fvalue", ExpectedValue = null, BlockIndex = 0 }, new ValidationData { ValueName = "ulvalue", ExpectedValue = null, BlockIndex = 0 } }; ExecuteAndVerify(code, data); } [Test] public void TestIEnumerable() { String code = @" primes = TestData.GetSomePrimes(); prime = primes[5]; "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "prime", ExpectedValue = 13, BlockIndex = 0 }, }; ExecuteAndVerify(code, data); } [Test] public void TestIEnumerable2() { String code = @" nums = TestData.GetNumbersByDouble(10); num = nums[5]; "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "num", ExpectedValue = 10, BlockIndex = 0 }, }; ExecuteAndVerify(code, data); } [Test] public void TestIEnumerable3() { String code = @" nums = TestData.DoubleThem({1,2,3,4,5}); num = nums[4]; "; Type t = Type.GetType("ProtoFFITests.TestData"); //"ProtoFFITests.TestData, ProtoTest, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" code = string.Format("import(\"{0}\");\r\n{1}", t.AssemblyQualifiedName, code); ValidationData[] data = { new ValidationData { ValueName = "num", ExpectedValue = 10, BlockIndex = 0 }, }; ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_IEnumerable_Implicit_Cast() { string code = @" t = TestData.TestData(); t1 = t.GetIEnumerable(); // creates an IEnumerable class and returns as an 'object' t2 = t.TestIEnumerable(t1); // implicitly casts the 'object' to IEnumerable based on the argument 'type', and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 2, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_IEnumerable_Explicit_Cast() { string code = @" t = TestData.TestData(); t1 = t.GetIEnumerable(); // creates an IEnumerable class and returns as an 'object' t2 = t.TestIEnumerable2(t1); // explicitly casts the 'object' to IEnumerable inside the function, and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 2, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Int_Implicit_Cast() { string code = @" t = TestData.TestData(); t1 = t.GetInt(); // creates an int and returns as 'object' t2 = t.TestInt(t1); // implicitly casts the 'object' to int based on the argument 'type', and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 1, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Int_Explicit_Cast() { string code = @" t = TestData.TestData(); t1 = t.GetInt(); // creates an int and returns as 'object' t2 = t.TestInt2(t1); // explicitly casts the 'object' to int inside the function, and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 1, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Ulong_Implicit_Cast() { string code = @" t = TestData.TestData(); t1 = t.GetUlong(); // creates a 'ulong' and returns as 'object' t2 = t.TestUlong(t1); // implicitly casts the 'object' to ulong based on the argument 'type', and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 1, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Ulong_Explicit_Cast() { string code = @" t = TestData.TestData(); t1 = t.GetUlong(); // creates a 'ulong' and returns as 'object' t2 = t.TestUlong2(t1); // explicitly casts the the 'object' to ulong inside the function, and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 1, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Over_Internal_Classes() { string code = @" t = TestData.TestData(); t1 = t.CreateInternalClass(5); // creates an internal class returned as an 'object' t2 = t.TestInternalClass(t1); // internally converts the 'object' to the class and tests its value "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 5, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Using_Implicit_Type_Cast_In_Method_Arguments() { string code = @" t = TestData.TestData(); t1 = t.FuncReturningVariousObjectTypes(0..18); // this function uses replication to create 19 different 'types' of variables, returned as 'objects' // Now each of those objects are passed to respective functions where the values are verified t2 = t.TestUlong(t1[0]);//1 t3 = t.TestByte(t1[1]);//1 t4 = t.TestSbyte(t1[2]);//1 t5 = t.TestShort(t1[3]);//1 t6 = t.TestUint16(t1[4]);//1 t7 = t.TestDummyDispose(t1[5]);//20 t8 = t.TestUint64(t1[6]);//1 t9 = t.TestChar(t1[7]); //1 t10 = t.TestFloat(t1[8]);//1 t11 = t.TestDecimal(t1[9]);//1 t12 = t.TestUshort(t1[10]);//1 t13 = t.TestDerivedDummyClass(t1[11]);//123 t14 = t.TestDerivedDisposeClass(t1[12]);//5 t15 = t.TestDerived1(t1[13]);//20 t16 = t.TestDisposeClass(t1[14]);//5 t17 = t.TestString(t1[15]); //4 t18 = t.TestInt(t1[16]); //1 t19 = t.TestDouble(t1[17]); //1 t20 = t.TestBoolean(t1[18]); //1 t21 = { t2, t3, t4, t5, t6, t7, t8, t9, t10, t11, t12, t13, t14, t15, t16, t17 , t18, t19, t20}; "; object[] b = new object[] { 1, 1, 1, 1, 1, 20, 1, 1, 1, 1, 1, 123, 5, 20.0, 5, 4, 1, 1, 1 }; ValidationData[] data = { new ValidationData { ValueName = "t21", ExpectedValue = b, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_DataMasrshalling_Using_Explicit_Type_Cast_In_Methods() { string code = @" t = TestData.TestData(); t1 = t.FuncReturningVariousObjectTypes(0..18); // Using replication : t1 is an array of 19 different 'types' , returned as 'object's t2 = t.FuncVerifyingVariousObjectTypes(t1, 0..18); // Again using replication, the objects are passed to relevant functions and the vlaues verified "; object[] b = new object[] { 1.0, 1.0, 1.0, 1.0, 1.0, 20.0, 1.0, 1.0, 1.0, 1.0, 1.0, 123.0, 5.0, 20.0, 5.0, 4.0, 1.0, 1.0, 1.0 }; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = b, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.TestData"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } [Test] public void Test_MethodOverloading_In_Csharp_Classes() { string code = @" t = MethodOverloadingClass.MethodOverloadingClass(); t1 = t.GetValue(); t2 = t.foo(t1); "; ValidationData[] data = { new ValidationData { ValueName = "t2", ExpectedValue = 0, BlockIndex = 0 } }; Type dummy = Type.GetType("ProtoFFITests.MethodOverloadingClass"); code = string.Format("import(\"{0}\");\r\n{1}", dummy.AssemblyQualifiedName, code); ExecuteAndVerify(code, data); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading.Tasks; using BTDB.Buffer; using BTDB.Collections; using BTDB.KVDBLayer; using BTDB.StreamLayer; namespace BTDB.ODBLayer { public interface IRelationModificationCounter { int ModificationCounter { get; } void CheckModifiedDuringEnum(int prevModification); } public interface IRelationDbManipulator : IRelation, IRelationModificationCounter { public IInternalObjectDBTransaction Transaction { get; } public RelationInfo RelationInfo { get; } public object? CreateInstanceFromSecondaryKey(RelationInfo.ItemLoaderInfo itemLoader, uint secondaryKeyIndex, uint fieldInFirstBufferCount, in ReadOnlySpan<byte> firstPart, in ReadOnlySpan<byte> secondPart); } public class RelationDBManipulator<T> : IRelation<T>, IRelationDbManipulator where T : class { readonly IInternalObjectDBTransaction _transaction; readonly IKeyValueDBTransaction _kvtr; readonly RelationInfo _relationInfo; public IInternalObjectDBTransaction Transaction => _transaction; public RelationInfo RelationInfo => _relationInfo; const string AssertNotDerivedTypesMsg = "Derived types are not supported."; public RelationDBManipulator(IObjectDBTransaction transaction, RelationInfo relationInfo) { _transaction = (IInternalObjectDBTransaction) transaction; _kvtr = _transaction.KeyValueDBTransaction; _relationInfo = relationInfo; _hasSecondaryIndexes = _relationInfo.ClientRelationVersionInfo.HasSecondaryIndexes; } int _modificationCounter; public int ModificationCounter => _modificationCounter; public void CheckModifiedDuringEnum(int prevModification) { if (prevModification != _modificationCounter) throw new InvalidOperationException("Relation modified during iteration."); } public void MarkModification() { _modificationCounter++; } ReadOnlySpan<byte> ValueBytes(T obj, ref SpanWriter writer) { writer.WriteVUInt32(_relationInfo.ClientTypeVersion); _relationInfo.ValueSaver(_transaction, ref writer, obj); return writer.GetPersistentSpanAndReset(); } ReadOnlySpan<byte> KeyBytes(T obj, ref SpanWriter writer) { WriteRelationPKPrefix(ref writer); _relationInfo.PrimaryKeysSaver(_transaction, ref writer, obj); return writer.GetPersistentSpanAndReset(); } public void WriteRelationPKPrefix(ref SpanWriter writer) { writer.WriteBlock(_relationInfo.Prefix); } public void WriteRelationSKPrefix(ref SpanWriter writer, uint secondaryKeyIndex) { writer.WriteBlock(_relationInfo.PrefixSecondary); writer.WriteUInt8((byte) secondaryKeyIndex); } public uint RemapPrimeSK(uint primeSecondaryKeyIndex) { return _relationInfo.PrimeSK2Real![primeSecondaryKeyIndex]; } readonly bool _hasSecondaryIndexes; class SerializationCallbacks : IInternalSerializationCallbacks { public readonly ContinuousMemoryBlockWriter Metadata = new ContinuousMemoryBlockWriter(); public readonly ContinuousMemoryBlockWriter Data = new ContinuousMemoryBlockWriter(); public void MetadataCreateKeyValue(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value) { var writer = new SpanWriter(Metadata); writer.WriteByteArray(key); writer.WriteByteArray(value); writer.Sync(); } public void CreateKeyValue(in ReadOnlySpan<byte> key, in ReadOnlySpan<byte> value) { var writer = new SpanWriter(Data); if (value.IsEmpty) { writer.WriteUInt8((byte) SerializationCommand.CreateKey); writer.WriteByteArray(key); } else { writer.WriteUInt8((byte) SerializationCommand.CreateKeyValue); writer.WriteByteArray(key); writer.WriteByteArray(value); } writer.Sync(); } } SerializationCallbacks? _serializationCallbacks; public void SerializeInsert(ref SpanWriter writer, T obj) { Debug.Assert(typeof(T) == obj.GetType(), AssertNotDerivedTypesMsg); _transaction.SetSerializationCallbacks(_serializationCallbacks ??= new SerializationCallbacks()); writer.WriteUInt8((byte) SerializationCommand.CreateKeyValue); var start = writer.StartWriteByteArray(); WriteRelationPKPrefix(ref writer); _relationInfo.PrimaryKeysSaver(_transaction, ref writer, obj); writer.FinishWriteByteArray(start); start = writer.StartWriteByteArray(); writer.WriteVUInt32(_relationInfo.ClientTypeVersion); _relationInfo.ValueSaver(_transaction, ref writer, obj); writer.FinishWriteByteArray(start); if (_hasSecondaryIndexes) { foreach (var sk in _relationInfo.ClientRelationVersionInfo.SecondaryKeys) { writer.WriteUInt8((byte) SerializationCommand.CreateKey); start = writer.StartWriteByteArray(); WriteRelationSKPrefix(ref writer, sk.Key); var keySaver = _relationInfo.GetSecondaryKeysKeySaver(sk.Key); keySaver(_transaction, ref writer, obj); writer.FinishWriteByteArray(start); } } _transaction.SetSerializationCallbacks(null); if (_serializationCallbacks!.Metadata.GetCurrentPositionWithoutWriter() > 0 || _serializationCallbacks.Data.GetCurrentPositionWithoutWriter() > 0) { var toCreate = _serializationCallbacks!.Metadata.GetByteBuffer(); _serializationCallbacks!.Metadata.ResetAndFreeMemory(); _kvtr.Owner.StartWritingTransaction().AsTask().ContinueWith(task => { var tr = task.Result; var reader = new SpanReader(toCreate); while (!reader.Eof) { var key = reader.ReadByteArrayAsSpan(); var value = reader.ReadByteArrayAsSpan(); tr.CreateOrUpdateKeyValue(key, value); } ((ObjectDB) _transaction.Owner).CommitLastObjIdAndDictId(tr); tr.Commit(); }, TaskContinuationOptions.ExecuteSynchronously); } writer.WriteBlock(_serializationCallbacks.Data.GetSpan()); _serializationCallbacks.Data.Reset(); } [SkipLocalsInit] public bool Insert(T obj) { Debug.Assert(typeof(T) == obj.GetType(), AssertNotDerivedTypesMsg); Span<byte> buf = stackalloc byte[512]; var writer = new SpanWriter(buf); var keyBytes = KeyBytes(obj, ref writer); if (_kvtr.FindExactKey(keyBytes)) return false; var valueBytes = ValueBytes(obj, ref writer); _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); if (_hasSecondaryIndexes) { writer = new SpanWriter(buf); AddIntoSecondaryIndexes(obj, ref writer); } MarkModification(); return true; } [SkipLocalsInit] public bool Upsert(T obj) { Debug.Assert(typeof(T) == obj.GetType(), AssertNotDerivedTypesMsg); Span<byte> buf = stackalloc byte[512]; var writer = new SpanWriter(buf); var keyBytes = KeyBytes(obj, ref writer); var valueBytes = ValueBytes(obj, ref writer); if (_kvtr.FindExactKey(keyBytes)) { var oldValueBytes = _kvtr.GetClonedValue(ref MemoryMarshal.GetReference(writer.Buf), writer.Buf.Length); _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); if (_hasSecondaryIndexes) { Span<byte> buf2 = stackalloc byte[512]; var writer2 = new SpanWriter(buf2); if (UpdateSecondaryIndexes(obj, keyBytes, oldValueBytes, ref writer2)) MarkModification(); } FreeContentInUpdate(oldValueBytes, valueBytes); return false; } _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); if (_hasSecondaryIndexes) { writer = new SpanWriter(buf); AddIntoSecondaryIndexes(obj, ref writer); } MarkModification(); return true; } [SkipLocalsInit] public bool ShallowUpsert(T obj) { Debug.Assert(typeof(T) == obj.GetType(), AssertNotDerivedTypesMsg); Span<byte> buf = stackalloc byte[512]; var writer = new SpanWriter(buf); var keyBytes = KeyBytes(obj, ref writer); var valueBytes = ValueBytes(obj, ref writer); if (_hasSecondaryIndexes) { if (_kvtr.FindExactKey(keyBytes)) { var oldValueBytes = _kvtr.GetClonedValue(ref MemoryMarshal.GetReference(writer.Buf), writer.Buf.Length); _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); Span<byte> buf2 = stackalloc byte[512]; var writer2 = new SpanWriter(buf2); if (UpdateSecondaryIndexes(obj, keyBytes, oldValueBytes, ref writer2)) MarkModification(); return false; } _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); writer = new SpanWriter(buf); AddIntoSecondaryIndexes(obj, ref writer); } else { if (!_kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes)) { return false; } } MarkModification(); return true; } [SkipLocalsInit] public void Update(T obj) { Debug.Assert(typeof(T) == obj.GetType(), AssertNotDerivedTypesMsg); Span<byte> buf = stackalloc byte[512]; var writer = new SpanWriter(buf); var keyBytes = KeyBytes(obj, ref writer); var valueBytes = ValueBytes(obj, ref writer); if (!_kvtr.FindExactKey(keyBytes)) throw new BTDBException("Not found record to update."); var oldValueBytes = _kvtr.GetClonedValue(ref MemoryMarshal.GetReference(writer.Buf), writer.Buf.Length); _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); if (_hasSecondaryIndexes) { Span<byte> buf2 = stackalloc byte[512]; var writer2 = new SpanWriter(buf2); if (UpdateSecondaryIndexes(obj, keyBytes, oldValueBytes, ref writer2)) MarkModification(); } FreeContentInUpdate(oldValueBytes, valueBytes); } [SkipLocalsInit] public void ShallowUpdate(T obj) { Debug.Assert(typeof(T) == obj.GetType(), AssertNotDerivedTypesMsg); Span<byte> buf = stackalloc byte[512]; var writer = new SpanWriter(buf); var keyBytes = KeyBytes(obj, ref writer); var valueBytes = ValueBytes(obj, ref writer); if (!_kvtr.FindExactKey(keyBytes)) throw new BTDBException("Not found record to update."); if (_hasSecondaryIndexes) { var oldValueBytes = _kvtr.GetClonedValue(ref MemoryMarshal.GetReference(writer.Buf), writer.Buf.Length); _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); if (_hasSecondaryIndexes) { Span<byte> buf2 = stackalloc byte[512]; var writer2 = new SpanWriter(buf2); if (UpdateSecondaryIndexes(obj, keyBytes, oldValueBytes, ref writer2)) MarkModification(); } } else { _kvtr.CreateOrUpdateKeyValue(keyBytes, valueBytes); } } public bool Contains(in ReadOnlySpan<byte> keyBytes) { return _kvtr.FindExactKey(keyBytes); } void CompareAndRelease(List<ulong> oldItems, List<ulong> newItems, Action<IInternalObjectDBTransaction, ulong> freeAction) { if (newItems.Count == 0) { foreach (var id in oldItems) freeAction(_transaction, id); } else if (newItems.Count < 10) { foreach (var id in oldItems) { if (newItems.Contains(id)) continue; freeAction(_transaction, id); } } else { var newItemsDictionary = new HashSet<ulong>(newItems); foreach (var id in oldItems) { if (newItemsDictionary.Contains(id)) continue; freeAction(_transaction, id); } } } void FreeContentInUpdate(in ReadOnlySpan<byte> oldValueBytes, in ReadOnlySpan<byte> newValueBytes) { var oldDicts = _relationInfo.FreeContentOldDict; oldDicts.Clear(); _relationInfo.FindUsedObjectsToFree(_transaction, oldValueBytes, oldDicts); if (oldDicts.Count == 0) return; var newDicts = _relationInfo.FreeContentNewDict; newDicts.Clear(); _relationInfo.FindUsedObjectsToFree(_transaction, newValueBytes, newDicts); CompareAndRelease(oldDicts, newDicts, RelationInfo.FreeIDictionary); } [SkipLocalsInit] public bool RemoveById(in ReadOnlySpan<byte> keyBytes, bool throwWhenNotFound) { Span<byte> valueBuffer = stackalloc byte[512]; if (!_kvtr.EraseCurrent(keyBytes, ref MemoryMarshal.GetReference(valueBuffer), valueBuffer.Length, out var value)) { if (throwWhenNotFound) throw new BTDBException("Not found record to delete."); return false; } if (_hasSecondaryIndexes) { RemoveSecondaryIndexes(keyBytes, value); } _relationInfo.FreeContent(_transaction, value); MarkModification(); return true; } [SkipLocalsInit] public bool ShallowRemoveById(in ReadOnlySpan<byte> keyBytes, bool throwWhenNotFound) { if (_hasSecondaryIndexes) { Span<byte> valueBuffer = stackalloc byte[512]; if (!_kvtr.EraseCurrent(keyBytes, ref valueBuffer.GetPinnableReference(), valueBuffer.Length, out var value)) { if (throwWhenNotFound) throw new BTDBException("Not found record to delete."); return false; } RemoveSecondaryIndexes(keyBytes, value); } else { if (!_kvtr.EraseCurrent(keyBytes)) { if (throwWhenNotFound) throw new BTDBException("Not found record to delete."); return false; } } MarkModification(); return true; } public int RemoveByPrimaryKeyPrefix(in ReadOnlySpan<byte> keyBytesPrefix) { var keysToDelete = new StructList<byte[]>(); var enumerator = new RelationPrimaryKeyEnumerator<T>(_transaction, _relationInfo, keyBytesPrefix, this, 0); while (enumerator.MoveNext()) { keysToDelete.Add(enumerator.GetKeyBytes()); } foreach (var key in keysToDelete) { if (!_kvtr.FindExactKey(key)) throw new BTDBException("Not found record to delete."); var valueBytes = _kvtr.GetValue(); if (_hasSecondaryIndexes) RemoveSecondaryIndexes(key, valueBytes); if (_relationInfo.NeedImplementFreeContent()) _relationInfo.FreeContent(_transaction, valueBytes); } return RemovePrimaryKeysByPrefix(keyBytesPrefix); } public int RemoveByPrimaryKeyPrefixPartial(in ReadOnlySpan<byte> keyBytesPrefix, int maxCount) { var enumerator = new RelationPrimaryKeyEnumerator<T>(_transaction, _relationInfo, keyBytesPrefix, this, 0); var keysToDelete = new StructList<byte[]>(); while (enumerator.MoveNext()) { keysToDelete.Add(enumerator.GetKeyBytes()); if (keysToDelete.Count == maxCount) break; } foreach (var key in keysToDelete) { RemoveById(key, true); } return (int) keysToDelete.Count; } public int RemoveByKeyPrefixWithoutIterate(in ReadOnlySpan<byte> keyBytesPrefix) { if (_relationInfo.NeedImplementFreeContent()) { return RemoveByPrimaryKeyPrefix(keyBytesPrefix); } if (_hasSecondaryIndexes) { //keyBytePrefix contains [3, Index Relation, Primary key prefix] we need // [4, Index Relation, Secondary Key Index, Primary key prefix] var idBytesLength = 1 + PackUnpack.LengthVUInt(_relationInfo.Id); var writer = new SpanWriter(); foreach (var secKey in _relationInfo.ClientRelationVersionInfo.SecondaryKeys) { WriteRelationSKPrefix(ref writer, secKey.Key); writer.WriteBlock(keyBytesPrefix.Slice((int) idBytesLength)); _kvtr.EraseAll(writer.GetSpan()); writer.Reset(); } } return RemovePrimaryKeysByPrefix(keyBytesPrefix); } int RemovePrimaryKeysByPrefix(in ReadOnlySpan<byte> keyBytesPrefix) { MarkModification(); return (int) _kvtr.EraseAll(keyBytesPrefix); } public long CountWithPrefix(in ReadOnlySpan<byte> keyBytesPrefix) { return _kvtr.GetKeyValueCount(keyBytesPrefix); } public bool AnyWithPrefix(in ReadOnlySpan<byte> keyBytesPrefix) { return _kvtr.FindFirstKey(keyBytesPrefix); } public bool AnyWithProposition(KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes) { return 0 < CountWithProposition(startKeyProposition, prefixLen, startKeyBytes, endKeyProposition, endKeyBytes); } public long CountWithProposition(KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes) { if (!_kvtr.FindFirstKey(startKeyBytes.Slice(0, prefixLen))) return 0; var prefixIndex = _kvtr.GetKeyIndex(); var realEndKeyBytes = endKeyBytes; if (endKeyProposition == KeyProposition.Included) realEndKeyBytes = RelationAdvancedEnumerator<T>.FindLastKeyWithPrefix(endKeyBytes, _kvtr); long startIndex; long endIndex; if (endKeyProposition == KeyProposition.Ignored) { _kvtr.FindLastKey(startKeyBytes.Slice(0, prefixLen)); endIndex = _kvtr.GetKeyIndex() - prefixIndex; } else { switch (_kvtr.Find(realEndKeyBytes, (uint) prefixLen)) { case FindResult.Exact: endIndex = _kvtr.GetKeyIndex() - prefixIndex; if (endKeyProposition == KeyProposition.Excluded) { endIndex--; } break; case FindResult.Previous: endIndex = _kvtr.GetKeyIndex() - prefixIndex; break; case FindResult.Next: endIndex = _kvtr.GetKeyIndex() - prefixIndex - 1; break; case FindResult.NotFound: endIndex = -1; break; default: throw new ArgumentOutOfRangeException(); } } if (startKeyProposition == KeyProposition.Ignored) { startIndex = 0; } else { switch (_kvtr.Find(startKeyBytes, (uint) prefixLen)) { case FindResult.Exact: startIndex = _kvtr.GetKeyIndex() - prefixIndex; if (startKeyProposition == KeyProposition.Excluded) { startIndex++; } break; case FindResult.Previous: startIndex = _kvtr.GetKeyIndex() - prefixIndex + 1; break; case FindResult.Next: startIndex = _kvtr.GetKeyIndex() - prefixIndex; break; case FindResult.NotFound: startIndex = 0; break; default: throw new ArgumentOutOfRangeException(); } } return Math.Max(0, endIndex - startIndex + 1); } public int RemoveByIdAdvancedParam(uint prefixFieldCount, EnumerationOrder order, KeyProposition startKeyProposition, int prefixLen, in ReadOnlySpan<byte> startKeyBytes, KeyProposition endKeyProposition, in ReadOnlySpan<byte> endKeyBytes) { using var enumerator = new RelationAdvancedEnumerator<T>(this, prefixFieldCount, order, startKeyProposition, prefixLen, startKeyBytes, endKeyProposition, endKeyBytes, 0); var keysToDelete = new StructList<byte[]>(); while (enumerator.MoveNext()) { keysToDelete.Add(enumerator.GetKeyBytes()); } foreach (var key in keysToDelete) { RemoveById(key, true); } return (int) keysToDelete.Count; } public IEnumerator<T> GetEnumerator() { return new RelationEnumerator<T>(_transaction, _relationInfo, _relationInfo.Prefix, this, 0); } public TItem FindByIdOrDefault<TItem>(in ReadOnlySpan<byte> keyBytes, bool throwWhenNotFound, int loaderIndex) { return (TItem) FindByIdOrDefaultInternal(_relationInfo.ItemLoaderInfos[loaderIndex], keyBytes, throwWhenNotFound); } object? FindByIdOrDefaultInternal(RelationInfo.ItemLoaderInfo itemLoader, in ReadOnlySpan<byte> keyBytes, bool throwWhenNotFound) { if (!_kvtr.FindExactKey(keyBytes)) { if (throwWhenNotFound) throw new BTDBException("Not found."); return default; } return itemLoader.CreateInstance(_transaction, keyBytes, _kvtr); } public IEnumerator<TItem> FindByPrimaryKeyPrefix<TItem>(in ReadOnlySpan<byte> keyBytesPrefix, int loaderIndex) { return new RelationPrimaryKeyEnumerator<TItem>(_transaction, _relationInfo, keyBytesPrefix, this, loaderIndex); } public object? CreateInstanceFromSecondaryKey(RelationInfo.ItemLoaderInfo itemLoader, uint secondaryKeyIndex, uint fieldInFirstBufferCount, in ReadOnlySpan<byte> firstPart, in ReadOnlySpan<byte> secondPart) { var pkWriter = new SpanWriter(); WriteRelationPKPrefix(ref pkWriter); var readerFirst = new SpanReader(firstPart); var readerSecond = new SpanReader(secondPart); _relationInfo.GetSKKeyValueToPKMerger(secondaryKeyIndex, fieldInFirstBufferCount) (ref readerFirst, ref readerSecond, ref pkWriter); return FindByIdOrDefaultInternal(itemLoader, pkWriter.GetSpan(), true); } public IEnumerator<TItem> FindBySecondaryKey<TItem>(uint secondaryKeyIndex, uint prefixFieldCount, in ReadOnlySpan<byte> secKeyBytes, int loaderIndex) { return new RelationSecondaryKeyEnumerator<TItem>(_transaction, _relationInfo, secKeyBytes, secondaryKeyIndex, prefixFieldCount, this, loaderIndex); } //secKeyBytes contains already AllRelationsSKPrefix public TItem FindBySecondaryKeyOrDefault<TItem>(uint secondaryKeyIndex, uint prefixParametersCount, in ReadOnlySpan<byte> secKeyBytes, bool throwWhenNotFound, int loaderIndex) { _kvtr.InvalidateCurrentKey(); if (!_kvtr.FindFirstKey(secKeyBytes)) { if (throwWhenNotFound) throw new BTDBException("Not found."); return default; } var keyBytes = _kvtr.GetKey(); if (_kvtr.FindNextKey(secKeyBytes)) throw new BTDBException("Ambiguous result."); return (TItem) CreateInstanceFromSecondaryKey(_relationInfo.ItemLoaderInfos[loaderIndex], secondaryKeyIndex, prefixParametersCount, secKeyBytes, keyBytes.Slice(secKeyBytes.Length)); } ReadOnlySpan<byte> WriteSecondaryKeyKey(uint secondaryKeyIndex, T obj, ref SpanWriter writer) { var keySaver = _relationInfo.GetSecondaryKeysKeySaver(secondaryKeyIndex); WriteRelationSKPrefix(ref writer, secondaryKeyIndex); keySaver(_transaction, ref writer, obj); //secondary key return writer.GetSpan(); } ReadOnlySpan<byte> WriteSecondaryKeyKey(uint secondaryKeyIndex, in ReadOnlySpan<byte> keyBytes, in ReadOnlySpan<byte> valueBytes) { var keyWriter = new SpanWriter(); WriteRelationSKPrefix(ref keyWriter, secondaryKeyIndex); var version = (uint) PackUnpack.UnpackVUInt(valueBytes); var keySaver = _relationInfo.GetPKValToSKMerger(version, secondaryKeyIndex); var keyReader = new SpanReader(keyBytes); var valueReader = new SpanReader(valueBytes); keySaver(_transaction, ref keyWriter, ref keyReader, ref valueReader, _relationInfo.DefaultClientObject); return keyWriter.GetSpan(); } void AddIntoSecondaryIndexes(T obj, ref SpanWriter writer) { foreach (var sk in _relationInfo.ClientRelationVersionInfo.SecondaryKeys) { var keyBytes = WriteSecondaryKeyKey(sk.Key, obj, ref writer); _kvtr.CreateOrUpdateKeyValue(keyBytes, new ReadOnlySpan<byte>()); writer.Reset(); } } bool UpdateSecondaryIndexes(T newValue, in ReadOnlySpan<byte> oldKey, in ReadOnlySpan<byte> oldValue, ref SpanWriter writer) { var changed = false; foreach (var (key, _) in _relationInfo.ClientRelationVersionInfo.SecondaryKeys) { writer.Reset(); var newKeyBytes = WriteSecondaryKeyKey(key, newValue, ref writer); var oldKeyBytes = WriteSecondaryKeyKey(key, oldKey, oldValue); if (oldKeyBytes.SequenceEqual(newKeyBytes)) continue; //remove old index EraseOldSecondaryKey(oldKey, oldKeyBytes, key); //insert new value _kvtr.CreateOrUpdateKeyValue(newKeyBytes, new ReadOnlySpan<byte>()); changed = true; } return changed; } void RemoveSecondaryIndexes(in ReadOnlySpan<byte> oldKey, in ReadOnlySpan<byte> oldValue) { foreach (var (key, _) in _relationInfo.ClientRelationVersionInfo.SecondaryKeys) { var keyBytes = WriteSecondaryKeyKey(key, oldKey, oldValue); EraseOldSecondaryKey(oldKey, keyBytes, key); } } void EraseOldSecondaryKey(in ReadOnlySpan<byte> primaryKey, in ReadOnlySpan<byte> keyBytes, uint skKey) { if (!_kvtr.EraseCurrent(keyBytes)) { var sk = _relationInfo.ClientRelationVersionInfo.SecondaryKeys[skKey]; throw new BTDBException( $"Error in removing secondary indexes, previous index entry not found. {_relationInfo.Name}:{sk.Name} PK:{BitConverter.ToString(primaryKey.ToArray()).Replace("-", "")}"); } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public int Count => (int) _kvtr.GetKeyValueCount(_relationInfo.Prefix); public Type BtdbInternalGetRelationInterfaceType() { return _relationInfo.InterfaceType!; } public IRelation? BtdbInternalNextInChain { get; set; } } }
using Amazon.CloudWatchLogs; using Amazon.CloudWatchLogs.Model; using Moq; using Serilog.Events; using Serilog.Formatting; using Serilog.Parsing; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Serilog.Sinks.AwsCloudWatch.Tests { public class CloudWatchLogsSinkTests { private const string Alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static Random random = new Random((int)DateTime.Now.Ticks); public CloudWatchLogsSinkTests(ITestOutputHelper output) { // so we can inspect what will be output to selflog Debugging.SelfLog.Enable(msg => output.WriteLine(msg)); } [Fact(DisplayName = "EmitBatchAsync - Single batch")] public async Task SingleBatch() { // expect a single batch of events to be posted to CloudWatch Logs var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Single(putLogEventsCalls); var request = putLogEventsCalls.First().Request; Assert.Equal(options.LogGroupName, request.LogGroupName); Assert.Null(request.SequenceToken); Assert.Equal(10, request.LogEvents.Count); for (var i = 0; i < events.Length; i++) { Assert.Equal(events[i].MessageTemplate.Text, request.LogEvents.ElementAt(i).Message); } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Single batch (log group exists)")] public async Task SingleBatch_LogGroupExists() { // expect a single batch of events to be posted to CloudWatch Logs var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { LogGroupName = Guid.NewGuid().ToString(), TextFormatter = textFormatterMock.Object }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, LogGroups = new List<LogGroup> { new LogGroup { LogGroupName = options.LogGroupName } } }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Single(putLogEventsCalls); var request = putLogEventsCalls.First().Request; Assert.Equal(options.LogGroupName, request.LogGroupName); Assert.Null(request.SequenceToken); Assert.Equal(10, request.LogEvents.Count); for (var i = 0; i < events.Length; i++) { Assert.Equal(events[i].MessageTemplate.Text, request.LogEvents.ElementAt(i).Message); } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Single batch (do not create log group)")] public async Task SingleBatch_WithoutCreatingLogGroup() { // expect a single batch of events to be posted to CloudWatch Logs var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { CreateLogGroup = false, TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Single(putLogEventsCalls); var request = putLogEventsCalls.First().Request; Assert.Equal(options.LogGroupName, request.LogGroupName); Assert.Null(request.SequenceToken); Assert.Equal(10, request.LogEvents.Count); for (var i = 0; i < events.Length; i++) { Assert.Equal(events[i].MessageTemplate.Text, request.LogEvents.ElementAt(i).Message); } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Single batch (log stream exists)")] public async Task SingleBatch_LogStreamExists() { // expect a single batch of events to be posted to CloudWatch Logs var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { LogGroupName = Guid.NewGuid().ToString(), LogStreamNameProvider = new NonUniqueLogStreamNameProvider(), TextFormatter = textFormatterMock.Object }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, LogGroups = new List<LogGroup> { new LogGroup { LogGroupName = options.LogGroupName } } }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, LogStreams = new List<LogStream> { new LogStream { LogStreamName = options.LogStreamNameProvider.GetLogStreamName() } } }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Single(putLogEventsCalls); var request = putLogEventsCalls.First().Request; Assert.Equal(options.LogGroupName, request.LogGroupName); Assert.Equal(options.LogStreamNameProvider.GetLogStreamName(), request.LogStreamName); Assert.Null(request.SequenceToken); Assert.Equal(10, request.LogEvents.Count); for (var i = 0; i < events.Length; i++) { Assert.Equal(events[i].MessageTemplate.Text, request.LogEvents.ElementAt(i).Message); } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Large message")] public async Task LargeMessage() { // expect an event with a length beyond the MaxLogEventSize will be truncated to the MaxLogEventSize var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var largeEventMessage = CreateMessage(CloudWatchLogSink.MaxLogEventSize + 1); var events = new LogEvent[] { new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(largeEventMessage), Enumerable.Empty<LogEventProperty>()) }; client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Single(putLogEventsCalls); var request = putLogEventsCalls.First().Request; Assert.Equal(options.LogGroupName, request.LogGroupName); Assert.Null(request.SequenceToken); Assert.Single(request.LogEvents); Assert.Equal(largeEventMessage.Substring(0, CloudWatchLogSink.MaxLogEventSize), request.LogEvents.First().Message); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Beyond batch span")] public async Task MultipleDays() { // expect a batch to be posted for each 24-hour period var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 20) .Select(i => // create multipe events with message length of 12 new LogEvent( DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays((i % 2) * 2)), // split the events into two days LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Equal(2, putLogEventsCalls.Count); for (var i = 0; i < putLogEventsCalls.Count; i++) { var call = putLogEventsCalls[i]; var request = call.Request; Assert.Equal(options.LogGroupName, request.LogGroupName); Assert.Equal(events.Length / putLogEventsCalls.Count, request.LogEvents.Count); // make sure the events are ordered for (var index = 1; index < call.Request.LogEvents.Count; index++) { Assert.True(call.Request.LogEvents.ElementAt(index).Timestamp >= call.Request.LogEvents.ElementAt(index - 1).Timestamp); } if (i == 0) // first call { Assert.Null(request.SequenceToken); } else { Assert.NotNull(request.SequenceToken); } } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Beyond max batch count")] public async Task MoreThanMaxBatchCount() { // expect multiple batches, all having a batch count less than the maximum var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, CloudWatchLogSink.MaxLogEventBatchCount + 1) .Select(i => new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(2)), // make sure size is not an issue Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Equal(2, putLogEventsCalls.Count); for (var i = 0; i < putLogEventsCalls.Count; i++) { var call = putLogEventsCalls[i]; var request = call.Request; Assert.Equal(options.LogGroupName, request.LogGroupName); if (i == 0) // first call { Assert.Null(request.SequenceToken); Assert.Equal(CloudWatchLogSink.MaxLogEventBatchCount, request.LogEvents.Count); } else { Assert.NotNull(request.SequenceToken); Assert.Single(request.LogEvents); } } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Beyond batch size")] public async Task MoreThanMaxBatchSize() { // expect multiple batches, all having a batch size less than the maximum var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 256) // 256 4 KB messages matches our max batch size, but we want to test a "less nice" scenario, so we'll create 256 5 KB messages .Select(i => new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(1024 * 5)), // 5 KB messages Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); Assert.Equal(2, putLogEventsCalls.Count); for (var i = 0; i < putLogEventsCalls.Count; i++) { var call = putLogEventsCalls[i]; var request = call.Request; Assert.Equal(options.LogGroupName, request.LogGroupName); if (i == 0) // first call { Assert.Null(request.SequenceToken); Assert.Equal(203, request.LogEvents.Count); // expect 203 of the 256 messages in the first batch } else { Assert.NotNull(request.SequenceToken); Assert.Equal(53, request.LogEvents.Count); // expect 53 of the 256 messages in the second batch } } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Service unavailable")] public async Task ServiceUnavailable() { // expect retries until exhausted var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ThrowsAsync(new ServiceUnavailableException("unavailable")); await sink.EmitBatchAsync(events); Assert.Equal(options.RetryAttempts + 1, putLogEventsCalls.Count); var lastInterval = TimeSpan.Zero; for (var i = 1; i < putLogEventsCalls.Count; i++) { // ensure retry attempts are throttled properly var interval = putLogEventsCalls[i].DateTime.Subtract(putLogEventsCalls[i - 1].DateTime); Assert.True(interval.TotalMilliseconds + 5 >= (CloudWatchLogSink.ErrorBackoffStartingInterval.Milliseconds * Math.Pow(2, i - 1)), $"{interval.TotalMilliseconds} >= {CloudWatchLogSink.ErrorBackoffStartingInterval.Milliseconds * Math.Pow(2, i - 1)}"); lastInterval = interval; } client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Service unavailable with eventual success")] public async Task ServiceUnavailable_WithEventualSuccess() { // expect successful posting of batch after retry var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.SetupSequence(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .ThrowsAsync(new ServiceUnavailableException("unavailable")) .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); client.Verify(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Resource not found")] public async Task ResourceNotFound() { // expect failure, creation of log group/stream, and evenutal success var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); List<CreateLogStreamRequest> createLogStreamRequests = new List<CreateLogStreamRequest>(); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateLogStreamRequest, CancellationToken>((createLogStreamRequest, cancellationToken) => createLogStreamRequests.Add(createLogStreamRequest)) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.SetupSequence(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .ThrowsAsync(new ResourceNotFoundException("no resource")) .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); client.Verify(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogGroupAsync(It.Is<CreateLogGroupRequest>(req => req.LogGroupName == options.LogGroupName), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); Assert.Equal(createLogStreamRequests.ElementAt(0).LogStreamName, createLogStreamRequests.ElementAt(1).LogStreamName); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Unable to create resource")] public async Task ResourceNotFound_CannotCreateResource() { // expect failure with failure to successfully create resources upon retries var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.SetupSequence(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }) .ThrowsAsync(new Exception("can't create a new log stream")); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .ThrowsAsync(new ResourceNotFoundException("no resource")); await sink.EmitBatchAsync(events); client.Verify(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(1)); client.Verify(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogGroupAsync(It.Is<CreateLogGroupRequest>(req => req.LogGroupName == options.LogGroupName), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Invalid parameter")] public async Task InvalidParameter() { // expect batch dropped var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); var putLogEventsCalls = new List<RequestCall<PutLogEventsRequest>>(); client.Setup(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .Callback<PutLogEventsRequest, CancellationToken>((putLogEventsRequest, cancellationToken) => putLogEventsCalls.Add(new RequestCall<PutLogEventsRequest>(putLogEventsRequest))) // keep track of the requests made .ThrowsAsync(new InvalidParameterException("invalid param")); await sink.EmitBatchAsync(events); Assert.Single(putLogEventsCalls); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Invalid sequence token")] public async Task InvalidSequenceToken() { // expect update of sequence token and successful retry var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextToken = Guid.NewGuid().ToString() }); List<CreateLogStreamRequest> createLogStreamRequests = new List<CreateLogStreamRequest>(); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateLogStreamRequest, CancellationToken>((createLogStreamRequest, cancellationToken) => createLogStreamRequests.Add(createLogStreamRequest)) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.SetupSequence(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .ThrowsAsync(new InvalidSequenceTokenException("invalid sequence")) .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); client.Verify(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.DescribeLogStreamsAsync(It.Is<DescribeLogStreamsRequest>(req => req.LogGroupName == options.LogGroupName && req.LogStreamNamePrefix == createLogStreamRequests.First().LogStreamName), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>()), Times.Once); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Invalid sequence token with new log stream")] public async Task InvalidSequenceToken_CannotUpdateSequenceToken() { // expect update of sequence token and success on a new log stream var logStreamNameProvider = new Mock<ILogStreamNameProvider>(); logStreamNameProvider.SetupSequence(mock => mock.GetLogStreamName()) .Returns("a") .Returns("b"); var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { LogStreamNameProvider = logStreamNameProvider.Object, TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.SetupSequence(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }) .ThrowsAsync(new Exception("no describe log stream")) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); List<CreateLogStreamRequest> createLogStreamRequests = new List<CreateLogStreamRequest>(); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateLogStreamRequest, CancellationToken>((createLogStreamRequest, cancellationToken) => createLogStreamRequests.Add(createLogStreamRequest)) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.PutLogEventsAsync(It.Is<PutLogEventsRequest>(req => req.LogStreamName == "a"), It.IsAny<CancellationToken>())) .ThrowsAsync(new InvalidSequenceTokenException("invalid sequence")); client.Setup(mock => mock.PutLogEventsAsync(It.Is<PutLogEventsRequest>(req => req.LogStreamName == "b"), It.IsAny<CancellationToken>())) .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); client.Verify(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.DescribeLogStreamsAsync(It.Is<DescribeLogStreamsRequest>(req => req.LogGroupName == options.LogGroupName && req.LogStreamNamePrefix == createLogStreamRequests.First().LogStreamName), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); Assert.Equal(2, createLogStreamRequests.Count); Assert.NotEqual(createLogStreamRequests.ElementAt(0).LogStreamName, createLogStreamRequests.ElementAt(1).LogStreamName); client.VerifyAll(); } [Fact(DisplayName = "EmitBatchAsync - Data already accepted")] public async Task DataAlreadyAccepted() { // expect update of sequence token and successful retry var client = new Mock<IAmazonCloudWatchLogs>(MockBehavior.Strict); var textFormatterMock = new Mock<ITextFormatter>(MockBehavior.Strict); textFormatterMock.Setup(s => s.Format(It.IsAny<LogEvent>(), It.IsAny<TextWriter>())).Callback((LogEvent l, TextWriter t) => l.RenderMessage(t)); var options = new CloudWatchSinkOptions { TextFormatter = textFormatterMock.Object, LogGroupName = "Test-Log-Group-Name" }; var sink = new CloudWatchLogSink(client.Object, options); var events = Enumerable.Range(0, 10) .Select(_ => // create 10 events with message length of 12 new LogEvent( DateTimeOffset.UtcNow, LogEventLevel.Information, null, new MessageTemplateParser().Parse(CreateMessage(12)), Enumerable.Empty<LogEventProperty>())) .ToArray(); client.Setup(mock => mock.DescribeLogGroupsAsync(It.IsAny<DescribeLogGroupsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogGroupsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.CreateLogGroupAsync(It.IsAny<CreateLogGroupRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new CreateLogGroupResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.Setup(mock => mock.DescribeLogStreamsAsync(It.IsAny<DescribeLogStreamsRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new DescribeLogStreamsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextToken = Guid.NewGuid().ToString() }); List<CreateLogStreamRequest> createLogStreamRequests = new List<CreateLogStreamRequest>(); client.Setup(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>())) .Callback<CreateLogStreamRequest, CancellationToken>((createLogStreamRequest, cancellationToken) => createLogStreamRequests.Add(createLogStreamRequest)) .ReturnsAsync(new CreateLogStreamResponse { HttpStatusCode = System.Net.HttpStatusCode.OK }); client.SetupSequence(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>())) .ThrowsAsync(new DataAlreadyAcceptedException("data already accepted")) .ReturnsAsync(new PutLogEventsResponse { HttpStatusCode = System.Net.HttpStatusCode.OK, NextSequenceToken = Guid.NewGuid().ToString() }); await sink.EmitBatchAsync(events); client.Verify(mock => mock.PutLogEventsAsync(It.IsAny<PutLogEventsRequest>(), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.DescribeLogStreamsAsync(It.Is<DescribeLogStreamsRequest>(req => req.LogGroupName == options.LogGroupName && req.LogStreamNamePrefix == createLogStreamRequests.First().LogStreamName), It.IsAny<CancellationToken>()), Times.Exactly(2)); client.Verify(mock => mock.CreateLogStreamAsync(It.IsAny<CreateLogStreamRequest>(), It.IsAny<CancellationToken>()), Times.Once); client.VerifyAll(); } /// <summary> /// Creates a message of random characters of the given size. /// </summary> /// <param name="size">The size of the message.</param> /// <returns>A string consisting of random characters from the alphabet.</returns> private string CreateMessage(int size) { var message = new string(Enumerable.Range(0, size).Select(_ => Alphabet[random.Next(0, Alphabet.Length)]).ToArray()); Assert.Equal(size, message.Length); return message; } /// <summary> /// Private class to keep track of calls made to CloudWatch Logs. /// </summary> /// <typeparam name="T"></typeparam> /// <remarks> /// Necessary because ValueTuple isn't supported until .NET 4.7, and we want to test at .NET 4.5.2. /// </remarks> private class RequestCall<T> where T : AmazonCloudWatchLogsRequest { public RequestCall(T request) { Request = request; DateTime = DateTime.UtcNow; } public T Request { get; private set; } public DateTime DateTime { get; private set; } } /// <summary> /// Provides a log stream name that can be reused. /// </summary> private class NonUniqueLogStreamNameProvider : ILogStreamNameProvider { public string GetLogStreamName() { return "NonUniqueName"; } } } }
using System; using System.Reflection; using System.Linq.Expressions; using NUnit.Framework; namespace Tests { public class OpClass { public static OpClass operator +(OpClass a, OpClass b) { return a; } public static OpClass operator -(OpClass a, OpClass b) { return a; } public static OpClass operator *(OpClass a, OpClass b) { return a; } public static OpClass operator /(OpClass a, OpClass b) { return a; } public static OpClass operator %(OpClass a, OpClass b) { return a; } public static OpClass operator &(OpClass a, OpClass b) { return a; } public static OpClass operator |(OpClass a, OpClass b) { return a; } public static OpClass operator ^(OpClass a, OpClass b) { return a; } public static OpClass operator >>(OpClass a, int b) { return a; } public static OpClass operator <<(OpClass a, int b) { return a; } public static bool operator true(OpClass a) { return false; } public static bool operator false(OpClass a) { return false; } public static bool operator >(OpClass a, OpClass b) { return false; } public static bool operator <(OpClass a, OpClass b) { return false; } public static bool operator >=(OpClass a, OpClass b) { return false; } public static bool operator <=(OpClass a, OpClass b) { return false; } public static OpClass operator +(OpClass a) { return a; } public static OpClass operator -(OpClass a) { return a; } public static OpClass operator !(OpClass a) { return a; } public static OpClass operator ~(OpClass a) { return a; } public static void WrongUnaryReturnVoid(OpClass a) { } public static OpClass WrongUnaryParameterCount(OpClass a, OpClass b) { return a; } public OpClass WrongUnaryNotStatic(OpClass a) { return a; } public static bool operator ==(OpClass a, OpClass b) { return ((object)a) == ((object)b); } public static bool operator !=(OpClass a, OpClass b) { return ((object)a) != ((object)b); } // // Required when you have == or != // public override bool Equals(object o) { return ((object)this) == o; } public override int GetHashCode() { return 1; } } public class NoOpClass { // No user-defined operators here (we use this class to test for exceptions.) } public class MemberClass { public int TestField1 = 0; public readonly int TestField2 = 1; public int TestProperty1 { get { return TestField1; } } public int TestProperty2 { get { return TestField1; } set { TestField1 = value; } } public int TestMethod(int i) { return TestField1 + i; } public T TestGenericMethod<T>(T arg) { return arg; } public delegate int TestDelegate(int i); public event TestDelegate TestEvent; public void DoNothing() { // Just to avoid a compiler warning if (TestEvent != null) { return; } } public static int StaticField = 0; public static int StaticProperty { get { return StaticField; } set { StaticField = value; } } public static int StaticMethod(int i) { return 1 + i; } public static T StaticGenericMethod<T>(T arg) { return arg; } public static MethodInfo GetMethodInfo() { return typeof(MemberClass).GetMethod("TestMethod"); } public static FieldInfo GetRoFieldInfo() { return typeof(MemberClass).GetField("TestField1"); } public static FieldInfo GetRwFieldInfo() { return typeof(MemberClass).GetField("TestField2"); } public static PropertyInfo GetRoPropertyInfo() { return typeof(MemberClass).GetProperty("TestProperty1"); } public static PropertyInfo GetRwPropertyInfo() { return typeof(MemberClass).GetProperty("TestProperty2"); } public static EventInfo GetEventInfo() { return typeof(MemberClass).GetEvent("TestEvent"); } public static FieldInfo GetStaticFieldInfo() { return typeof(MemberClass).GetField("StaticField"); } public static PropertyInfo GetStaticPropertyInfo() { return typeof(MemberClass).GetProperty("StaticProperty"); } } public struct OpStruct { public static OpStruct operator +(OpStruct a, OpStruct b) { return a; } public static OpStruct operator -(OpStruct a, OpStruct b) { return a; } public static OpStruct operator *(OpStruct a, OpStruct b) { return a; } public static OpStruct operator &(OpStruct a, OpStruct b) { return a; } } static class ExpressionExtensions { public static ConstantExpression ToConstant<T>(this T t) { return Expression.Constant(t); } public static void AssertThrows(this Action action, Type type) { try { action(); Assert.Fail(); } catch (Exception e) { if (e.GetType() != type) { Assert.Fail(); } } } } class Item<T> { bool left_called; T left; public T Left { get { left_called = true; return left; } } public bool LeftCalled { get { return left_called; } } bool right_called; T right; public T Right { get { right_called = true; return right; } } public bool RightCalled { get { return right_called; } } public Item(T left, T right) { this.left = left; this.right = right; } } }
// EasyJoystick library is copyright (c) of Hedgehog Team // Please send feedback or bug reports to the.hedgehog.team@gmail.com using UnityEngine; using System.Collections; /// <summary> /// Release notes: /// EasyJoystick V2.3 October 2013 /// ============================= /// * New /// ----------------- /// - Add SetManual(Vector2 movement), to control the joystick /// /// * Bugs fixed /// ------------ /// - Fix debug area /// /// EasyJoystick V2.2 Mai 2013 /// ============================= /// * Dynamic joystick no longer show when there are hover reserved area /// /// EasyJoystick V2.1 Mai 2013 /// ============================= /// * Bugs fixed /// ------------ /// - The joystick touch wasn't been correct in some case /// /// /// EasyJoystick V2.0 Avril 2013 /// ============================= /// * New /// ----------------- /// - Add virtual screen to keep size position /// - Add new joystick events : On_JoystickMoveStart, On_JoystickTouchStart, On_JoystickTap, On_JoystickDoubleTap,On_JoystickTouchUp /// - Add new option to reset joystick position, when touch exit the joystick area /// - Add the possibility to enable / disable joystick axis X or Y /// - Add new member isActivated to desactivated the joystick, but it always show on the screen /// - Add new member to clamp rotation in direct mode when you're in localrotation /// - Add new member to do an auto stabilisation in direct mode when you're in localrotation /// - Add show dynamic joystick in edit mode /// - Some optimisations /// - Add new method Axis2Angle to MovingJoystick class that allow to return the joystick angle direction between -170 to 170 /// - Add option to show real area use by the joystick texture /// - Add UseGuiLayout option /// - Add Gui depth parameter /// /// * Bugs fixed /// ------------ /// - Gravity is now always apply correctly /// - Dead zone is correctly take into account /// - the event JoystickMoveEnd don't send any more at startup /// /// V1.0 November 2012 /// ============================= /// - First release /// <summary> /// This is the main class of EasyJoystick engine. /// /// For add joystick to your scene, use the menu Hedgehog Team<br> /// </summary> [ExecuteInEditMode] public class EasyJoystick : MonoBehaviour { #region Delegate public delegate void JoystickMoveStartHandler(MovingJoystick move); public delegate void JoystickMoveHandler(MovingJoystick move); public delegate void JoystickMoveEndHandler(MovingJoystick move); public delegate void JoystickTouchStartHandler(MovingJoystick move); public delegate void JoystickTapHandler(MovingJoystick move); public delegate void JoystickDoubleTapHandler(MovingJoystick move); public delegate void JoystickTouchUpHandler(MovingJoystick move); #endregion #region Event /// <summary> /// Occurs the joystick starts move. /// </summary> public static event JoystickMoveStartHandler On_JoystickMoveStart; /// <summary> /// Occurs when the joystick move. /// </summary> public static event JoystickMoveHandler On_JoystickMove; /// <summary> /// Occurs when the joystick stops move /// </summary> public static event JoystickMoveEndHandler On_JoystickMoveEnd; /// <summary> /// Occurs when a touch start hover the joystick /// </summary> public static event JoystickTouchStartHandler On_JoystickTouchStart; /// <summary> /// Occurs when a tap happen's on the joystick /// </summary> public static event JoystickTapHandler On_JoystickTap; /// <summary> /// Occurs when a double tap happen's on the joystick /// </summary> public static event JoystickDoubleTapHandler On_JoystickDoubleTap; /// <summary> /// Occurs when touch up happen's on the joystick /// </summary> public static event JoystickTouchUpHandler On_JoystickTouchUp; #endregion #region Enumeration /// <summary> /// Joystick anchor. /// </summary> public enum JoystickAnchor {None,UpperLeft, UpperCenter, UpperRight, MiddleLeft, MiddleCenter, MiddleRight, LowerLeft, LowerCenter, LowerRight}; /// <summary> /// Properties influenced by the joystick /// </summary> public enum PropertiesInfluenced {Rotate, RotateLocal,Translate, TranslateLocal, Scale} /// <summary> /// Axis influenced by the joystick /// </summary> public enum AxisInfluenced{X,Y,Z,XYZ} /// <summary> /// Dynamic area zone. /// </summary> public enum DynamicArea {FullScreen, Left,Right,Top, Bottom, TopLeft, TopRight, BottomLeft, BottomRight}; /// <summary> /// Interaction type. /// </summary> public enum InteractionType {Direct, Include, EventNotification, DirectAndEvent} /// <summary> /// Broadcast mode for javascript /// </summary> public enum Broadcast {SendMessage,SendMessageUpwards,BroadcastMessage } /// <summary> /// Message name. /// </summary> private enum MessageName{On_JoystickMoveStart,On_JoystickTouchStart, On_JoystickTouchUp, On_JoystickMove, On_JoystickMoveEnd, On_JoystickTap, On_JoystickDoubleTap}; #endregion #region Members #region Public Members #region property private Vector2 joystickAxis; /// <summary> /// Gets the joystick axis value between -1 & 1... /// </summary> /// <value> /// The joystick axis. /// </value> public Vector2 JoystickAxis { get { return this.joystickAxis; } } /// <summary> /// Gest or set the touch position. /// </summary> private Vector2 joystickTouch; public Vector2 JoystickTouch { get { return new Vector2(this.joystickTouch.x/zoneRadius, this.joystickTouch.y/zoneRadius); } set { float x = Mathf.Clamp( value.x,-1f,1f)*zoneRadius; float y = Mathf.Clamp( value.y,-1f,1f)*zoneRadius; joystickTouch = new Vector2(x,y); } } private Vector2 joystickValue; /// <summary> /// Gets the joystick value = joystic axis value * jostick speed * Time.deltaTime... /// </summary> /// <value> /// The joystick value. /// </value> public Vector2 JoystickValue { get { return this.joystickValue; } } #endregion #region public joystick properties /// <summary> /// Enable or disable the joystick. /// </summary> public bool enable = true; public bool visible = true; /// <summary> /// Activacte or deactivate the joystick /// </summary> public bool isActivated = true; /// <summary> /// The show debug radius area /// </summary> public bool showDebugRadius=false; public bool selected = false; /// <summary> /// Use fixed update. /// </summary> public bool useFixedUpdate = false; /// <summary> /// Disable this lets you skip the GUI layout phase. /// </summary> public bool isUseGuiLayout=true; #endregion #region Joystick Position & size [SerializeField] private bool dynamicJoystick=false; /// <summary> /// Gets or sets a value indicating whether this is a dynamic joystick. /// When this option is enabled, the joystick will display the location of the touch /// </summary> /// <value> /// <c>true</c> if dynamic joystick; otherwise, <c>false</c>. /// </value> public bool DynamicJoystick { get { return this.dynamicJoystick; } set { if (!Application.isPlaying){ joystickIndex=-1; dynamicJoystick = value; if (dynamicJoystick){ virtualJoystick=false; } else{ virtualJoystick=true; joystickCenter = joystickPositionOffset; } } } } /// <summary> /// When the joystick is dynamic mode, this value indicates the area authorized for display /// </summary> public DynamicArea area = DynamicArea.FullScreen; /// <summary> /// The joystick anchor. /// </summary> [SerializeField] private JoystickAnchor joyAnchor = JoystickAnchor.LowerLeft; public JoystickAnchor JoyAnchor { get { return this.joyAnchor; } set { joyAnchor = value; ComputeJoystickAnchor(joyAnchor); } } /// <summary> /// The joystick position on the screen /// </summary> [SerializeField] private Vector2 joystickPositionOffset = Vector2.zero; public Vector2 JoystickPositionOffset { get { return this.joystickPositionOffset; } set { joystickPositionOffset = value; joystickCenter = joystickPositionOffset; ComputeJoystickAnchor(joyAnchor); } } /// <summary> /// The zone radius size. /// </summary> /// [SerializeField] private float zoneRadius=100f; public float ZoneRadius { get { return this.zoneRadius; } set { zoneRadius = value; ComputeJoystickAnchor(joyAnchor); } } [SerializeField] private float touchSize = 30; /// <summary> /// Gets or sets the size of the touch. /// /// </summary> /// <value> /// The size of the touch. /// </value> public float TouchSize { get { return this.touchSize; } set { touchSize = value; if (touchSize>zoneRadius/2 && restrictArea){ touchSize =zoneRadius/2; } ComputeJoystickAnchor(joyAnchor); } } /// <summary> /// The dead zone size. While the touch is in this area, the joystick is considered stalled /// </summary> public float deadZone=20; [SerializeField] private bool restrictArea=false; /// <summary> /// Gets or sets a value indicating whether the touch must be in the radius area. /// </summary> /// <value> /// <c>true</c> if restrict area; otherwise, <c>false</c>. /// </value> public bool RestrictArea { get { return this.restrictArea; } set { restrictArea = value; if (restrictArea){ touchSizeCoef = touchSize; } else{ touchSizeCoef=0; } ComputeJoystickAnchor(joyAnchor); } } /// <summary> /// The reset finger exit. /// </summary> public bool resetFingerExit = false; #endregion #region Joystick axes properties & event /// <summary> /// The interaction. /// </summary> [SerializeField] private InteractionType interaction = InteractionType.Direct; public InteractionType Interaction { get { return this.interaction; } set { interaction = value; if (interaction == InteractionType.Direct || interaction == InteractionType.Include){ useBroadcast = false; } } } /// <summary> /// The use broadcast for javascript /// </summary> public bool useBroadcast = false; /// <summary> /// The message sending mode fro broacast /// </summary> public Broadcast messageMode; // Messaging /// <summary> /// The receiver gameobject when you're in broacast mode for events /// </summary> public GameObject receiverGameObject; /// <summary> /// The speed of each joystick axis /// </summary> public Vector2 speed; #region X axis public bool enableXaxis = true; [SerializeField] private Transform xAxisTransform; /// <summary> /// Gets or sets the transform influenced by x axis of the joystick. /// </summary> /// <value> /// The X axis transform. /// </value> public Transform XAxisTransform { get { return this.xAxisTransform; } set { xAxisTransform = value; if (xAxisTransform!=null){ xAxisCharacterController = xAxisTransform.GetComponent<CharacterController>(); } else{ xAxisCharacterController=null; xAxisGravity=0; } } } /// <summary> /// The character controller attached to the X axis transform (if exist) /// </summary> public CharacterController xAxisCharacterController; /// <summary> /// The gravity. /// </summary> public float xAxisGravity=0; [SerializeField] private PropertiesInfluenced xTI; /// <summary> /// The Property influenced by the x axis joystick /// </summary> public PropertiesInfluenced XTI { get { return this.xTI; } set { xTI = value; if (xTI != PropertiesInfluenced.RotateLocal){ enableXAutoStab = false; enableXClamp = false; } } } /// <summary> /// The axis influenced by the x axis joystick /// </summary> public AxisInfluenced xAI; /// <summary> /// Inverse X axis. /// </summary> public bool inverseXAxis=false; /// <summary> /// The limit angle. /// </summary> public bool enableXClamp=false; /// <summary> /// The clamp X max. /// </summary> public float clampXMax; /// <summary> /// The clamp X minimum. /// </summary> public float clampXMin; /// <summary> /// The enable X auto stab. /// </summary> public bool enableXAutoStab=false; [SerializeField] private float thresholdX=0.01f; /// <summary> /// Gets or sets the threshold x. /// </summary> /// <value> /// The threshold x. /// </value> public float ThresholdX { get { return this.thresholdX; } set { if (value<=0){ thresholdX=value*-1f; } else{ thresholdX = value; } } } [SerializeField] private float stabSpeedX = 20f; /// <summary> /// Gets or sets the stab speed x. /// </summary> /// <value> /// The stab speed x. /// </value> public float StabSpeedX { get { return this.stabSpeedX; } set { if (value<=0){ stabSpeedX = value*-1f; } else{ stabSpeedX = value; } } } #endregion #region Y axis public bool enableYaxis = true; [SerializeField] private Transform yAxisTransform; /// <summary> /// Gets or sets the transform influenced by y axis of the joystick. /// </summary> /// <value> /// The Y axis transform. /// </value> public Transform YAxisTransform { get { return this.yAxisTransform; } set { yAxisTransform = value; if (yAxisTransform!=null){ yAxisCharacterController = yAxisTransform.GetComponent<CharacterController>(); } else{ yAxisCharacterController=null; yAxisGravity=0; } } } /// <summary> /// The character controller attached to the X axis transform (if exist) /// </summary> public CharacterController yAxisCharacterController; /// <summary> /// The y axis gravity. /// </summary> public float yAxisGravity=0; /// <summary> /// The Property influenced by the y axis joystick /// </summary> [SerializeField] private PropertiesInfluenced yTI; public PropertiesInfluenced YTI { get { return this.yTI; } set { yTI = value; if (yTI != PropertiesInfluenced.RotateLocal){ enableYAutoStab = false; enableYClamp = false; } } } /// <summary> /// The axis influenced by the y axis joystick /// </summary> public AxisInfluenced yAI; /// <summary> /// Inverse Y axis. /// </summary> public bool inverseYAxis=false; /// <summary> /// The enable Y clamp. /// </summary> public bool enableYClamp=false; /// <summary> /// The clamp Y max. /// </summary> public float clampYMax; /// <summary> /// The clamp Y minimum. /// </summary> public float clampYMin; /// <summary> /// The enable Y auto stab. /// </summary> public bool enableYAutoStab = false; [SerializeField] private float thresholdY=0.01f; /// <summary> /// Gets or sets the threshold y. /// </summary> /// <value> /// The threshold y. /// </value> public float ThresholdY { get { return this.thresholdY; } set { if (value<=0){ thresholdY=value*-1f; } else{ thresholdY = value; } } } [SerializeField] private float stabSpeedY = 20f; /// <summary> /// Gets or sets the stab speed y. /// </summary> /// <value> /// The stab speed y. /// </value> public float StabSpeedY { get { return this.stabSpeedY; } set { if (value<=0){ stabSpeedY=value*-1f; } else{ stabSpeedY = value; }; } } #endregion /// <summary> /// The enable smoothing.When smoothing is enabled, resets the joystick slowly in the start position /// </summary> public bool enableSmoothing = false; [SerializeField] public Vector2 smoothing = new Vector2(2f,2f); /// <summary> /// Gets or sets the smoothing values /// </summary> /// <value> /// The smoothing. /// </value> public Vector2 Smoothing { get { return this.smoothing; } set { smoothing = value; if (smoothing.x<0f){ smoothing.x=0; } if (smoothing.y<0){ smoothing.y=0; } } } /// <summary> /// The enable inertia. Inertia simulates sliding movements (like a hovercraft, for example) /// </summary> public bool enableInertia = false; [SerializeField] public Vector2 inertia = new Vector2(100,100); /// <summary> /// Gets or sets the inertia values /// </summary> /// <value> /// The inertia. /// </value> public Vector2 Inertia { get { return this.inertia; } set { inertia = value; if (inertia.x<=0){ inertia.x=1; } if (inertia.y<=0){ inertia.y=1; } } } #endregion #region Joystick textures & color /// <summary> /// The GUI depth. /// </summary> public int guiDepth = 0; // Joystick Texture /// <summary> /// The show zone. /// </summary> public bool showZone = true; /// <summary> /// The show touch. /// </summary> public bool showTouch = true; /// <summary> /// The show dead zone. /// </summary> public bool showDeadZone = true; /// <summary> /// The area texture. /// </summary> public Texture areaTexture; /// <summary> /// The color of the area. /// </summary> public Color areaColor = Color.white; /// <summary> /// The touch texture. /// </summary> public Texture touchTexture; /// <summary> /// The color of the touch. /// </summary> public Color touchColor = Color.white; /// <summary> /// The dead texture. /// </summary> public Texture deadTexture; #endregion #region Inspector public bool showProperties=true; public bool showInteraction=false; public bool showAppearance=false; public bool showPosition=true; #endregion #endregion #region private members // Joystick properties private Vector2 joystickCenter; private Rect areaRect; private Rect deadRect; private Vector2 anchorPosition = Vector2.zero; private bool virtualJoystick = true; private int joystickIndex=-1; private float touchSizeCoef=0; private bool sendEnd=true; private float startXLocalAngle=0; private float startYLocalAngle=0; #endregion #endregion #region Monobehaviour methods void OnEnable(){ EasyTouch.On_TouchStart += On_TouchStart; EasyTouch.On_TouchUp += On_TouchUp; EasyTouch.On_TouchDown += On_TouchDown; EasyTouch.On_SimpleTap += On_SimpleTap; EasyTouch.On_DoubleTap += On_DoubleTap; } void OnDisable(){ EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_TouchDown -= On_TouchDown; EasyTouch.On_SimpleTap -= On_SimpleTap; EasyTouch.On_DoubleTap -= On_DoubleTap; if (Application.isPlaying){ //EasyTouch.RemoveReservedArea( areaRect ); EasyTouch.instance.reservedVirtualAreas.Remove( areaRect); } } void OnDestroy(){ EasyTouch.On_TouchStart -= On_TouchStart; EasyTouch.On_TouchUp -= On_TouchUp; EasyTouch.On_TouchDown -= On_TouchDown; EasyTouch.On_SimpleTap -= On_SimpleTap; EasyTouch.On_DoubleTap -= On_DoubleTap; if (Application.isPlaying){ //EasyTouch.RemoveReservedArea( areaRect); EasyTouch.instance.reservedVirtualAreas.Remove( areaRect); } } void Start(){ if (!dynamicJoystick){ joystickCenter = joystickPositionOffset; ComputeJoystickAnchor(joyAnchor); virtualJoystick = true; } else{ virtualJoystick = false; } VirtualScreen.ComputeVirtualScreen(); startXLocalAngle = GetStartAutoStabAngle( xAxisTransform, xAI); startYLocalAngle = GetStartAutoStabAngle( yAxisTransform, yAI); } void Update(){ if (!useFixedUpdate && enable){ UpdateJoystick(); } } void FixedUpdate(){ if (useFixedUpdate && enable){ UpdateJoystick(); } } void UpdateJoystick(){ if (Application.isPlaying){ if (isActivated){ if ((joystickIndex==-1) || (joystickAxis == Vector2.zero && joystickIndex>-1)){ if (enableXAutoStab){ DoAutoStabilisation(xAxisTransform, xAI,thresholdX,stabSpeedX,startXLocalAngle); } if (enableYAutoStab){ DoAutoStabilisation(yAxisTransform, yAI,thresholdY,stabSpeedY,startYLocalAngle); } } if (!dynamicJoystick){ joystickCenter = joystickPositionOffset; } // Reset to initial position if (joystickIndex==-1){ if (!enableSmoothing){ joystickTouch = Vector2.zero; } else{ if (joystickTouch.sqrMagnitude>0.0001){ joystickTouch = new Vector2( joystickTouch.x - joystickTouch.x*smoothing.x*Time.deltaTime, joystickTouch.y - joystickTouch.y*smoothing.y*Time.deltaTime); } else{ joystickTouch = Vector2.zero; } } } // Joystick Axis & dead zone Vector2 oldJoystickAxis = new Vector2(joystickAxis.x,joystickAxis.y); float deadCoef = ComputeDeadZone(); joystickAxis= new Vector2(joystickTouch.x*deadCoef, joystickTouch.y*deadCoef); // Inverse axis ? if (inverseXAxis){ joystickAxis.x *= -1; } if (inverseYAxis){ joystickAxis.y *= -1; } // Joystick Value Vector2 realvalue = new Vector2( speed.x*joystickAxis.x,speed.y*joystickAxis.y); if (enableInertia){ Vector2 tmp = (realvalue - joystickValue); tmp.x /= inertia.x; tmp.y /= inertia.y; joystickValue += tmp; } else{ joystickValue = realvalue; } // Start moving if (oldJoystickAxis == Vector2.zero && joystickAxis != Vector2.zero){ if (interaction != InteractionType.Direct && interaction != InteractionType.Include){ CreateEvent(MessageName.On_JoystickMoveStart); } } // interaction manager UpdateGravity(); if (joystickAxis != Vector2.zero){ sendEnd = false; switch(interaction){ case InteractionType.Direct: UpdateDirect(); break; case InteractionType.EventNotification: CreateEvent(MessageName.On_JoystickMove); break; case InteractionType.DirectAndEvent: UpdateDirect(); CreateEvent(MessageName.On_JoystickMove); break; } } else{ if (!sendEnd){ CreateEvent(MessageName.On_JoystickMoveEnd); sendEnd = true; } } } } } void OnGUI(){ if (enable && visible){ GUI.depth = guiDepth; useGUILayout = isUseGuiLayout; if (dynamicJoystick && Application.isEditor && !Application.isPlaying){ switch (area){ case DynamicArea.Bottom: ComputeJoystickAnchor(JoystickAnchor.LowerCenter); break; case DynamicArea.BottomLeft: ComputeJoystickAnchor(JoystickAnchor.LowerLeft); break; case DynamicArea.BottomRight: ComputeJoystickAnchor(JoystickAnchor.LowerRight); break; case DynamicArea.FullScreen: ComputeJoystickAnchor(JoystickAnchor.MiddleCenter); break; case DynamicArea.Left: ComputeJoystickAnchor(JoystickAnchor.MiddleLeft); break; case DynamicArea.Right: ComputeJoystickAnchor(JoystickAnchor.MiddleRight); break; case DynamicArea.Top: ComputeJoystickAnchor(JoystickAnchor.UpperCenter); break; case DynamicArea.TopLeft: ComputeJoystickAnchor(JoystickAnchor.UpperLeft); break; case DynamicArea.TopRight: ComputeJoystickAnchor(JoystickAnchor.UpperRight); break; } } if (Application.isEditor && !Application.isPlaying){ VirtualScreen.ComputeVirtualScreen(); ComputeJoystickAnchor( joyAnchor); } VirtualScreen.SetGuiScaleMatrix(); // area zone if ((showZone && areaTexture!=null && !dynamicJoystick) || (showZone && dynamicJoystick && virtualJoystick && areaTexture!=null) || (dynamicJoystick && Application.isEditor && !Application.isPlaying)){ if (isActivated){ GUI.color = areaColor; if (Application.isPlaying && !dynamicJoystick){ EasyTouch.instance.reservedVirtualAreas.Remove( areaRect); EasyTouch.instance.reservedVirtualAreas.Add( areaRect ); } } else{ GUI.color = new Color(areaColor.r,areaColor.g,areaColor.b,0.2f); if (Application.isPlaying && !dynamicJoystick){ EasyTouch.instance.reservedVirtualAreas.Remove( areaRect); } } if (showDebugRadius && Application.isEditor && selected && !Application.isPlaying){ GUI.Box( areaRect,""); } GUI.DrawTexture( areaRect, areaTexture,ScaleMode.StretchToFill,true); } // area touch if ((showTouch && touchTexture!=null && !dynamicJoystick)|| (showTouch && dynamicJoystick && virtualJoystick && touchTexture!=null) || (dynamicJoystick && Application.isEditor && !Application.isPlaying)){ if (isActivated){ GUI.color = touchColor; } else{ GUI.color = new Color(touchColor.r,touchColor.g,touchColor.b,0.2f); } GUI.DrawTexture( new Rect(anchorPosition.x + joystickCenter.x+(joystickTouch.x -touchSize) ,anchorPosition.y + joystickCenter.y-(joystickTouch.y+touchSize),touchSize*2,touchSize*2), touchTexture,ScaleMode.ScaleToFit,true); } // dead zone if ((showDeadZone && deadTexture!=null && !dynamicJoystick)|| (showDeadZone && dynamicJoystick && virtualJoystick && deadTexture!=null) || (dynamicJoystick && Application.isEditor && !Application.isPlaying)){ GUI.DrawTexture( deadRect, deadTexture,ScaleMode.ScaleToFit,true); } GUI.color = Color.white; } else{ if (Application.isPlaying){ EasyTouch.instance.reservedVirtualAreas.Remove( areaRect); } } } void OnDrawGizmos(){ } #endregion #region Private methods void CreateEvent(MessageName message){ MovingJoystick move = new MovingJoystick(); move.joystickName = gameObject.name; move.joystickAxis = joystickAxis; move.joystickValue = joystickValue; move.joystick = this; // if (!useBroadcast){ switch (message){ case MessageName.On_JoystickMoveStart: if (On_JoystickMoveStart!=null){ On_JoystickMoveStart( move); } break; case MessageName.On_JoystickMove: if (On_JoystickMove!=null){ On_JoystickMove( move); } break; case MessageName.On_JoystickMoveEnd: if (On_JoystickMoveEnd!=null){ On_JoystickMoveEnd( move); } break; case MessageName.On_JoystickTouchStart: if (On_JoystickTouchStart!=null){ On_JoystickTouchStart( move); } break; case MessageName.On_JoystickTap: if (On_JoystickTap!=null){ On_JoystickTap( move); } break; case MessageName.On_JoystickDoubleTap: if (On_JoystickDoubleTap!=null){ On_JoystickDoubleTap( move); } break; case MessageName.On_JoystickTouchUp: if (On_JoystickTouchUp!=null){ On_JoystickTouchUp( move); } break; } } else if (useBroadcast){ if (receiverGameObject!=null){ switch(messageMode){ case Broadcast.BroadcastMessage: receiverGameObject.BroadcastMessage( message.ToString(),move,SendMessageOptions.DontRequireReceiver); break; case Broadcast.SendMessage: receiverGameObject.SendMessage( message.ToString(),move,SendMessageOptions.DontRequireReceiver); break; case Broadcast.SendMessageUpwards: receiverGameObject.SendMessageUpwards( message.ToString(),move,SendMessageOptions.DontRequireReceiver); break; } } else{ Debug.LogError("Joystick : " + gameObject.name + " : you must setup receiver gameobject"); } } } void UpdateDirect(){ // X joystick axis if (xAxisTransform !=null){ // Axis influenced Vector3 axis =GetInfluencedAxis( xAI); // Action DoActionDirect( xAxisTransform, xTI, axis, joystickValue.x, xAxisCharacterController); if (enableXClamp && xTI == PropertiesInfluenced.RotateLocal){ DoAngleLimitation( xAxisTransform, xAI, clampXMin,clampXMax, startXLocalAngle ); } } // y joystick axis if (YAxisTransform !=null){ // Axis Vector3 axis = GetInfluencedAxis(yAI); // Action DoActionDirect( yAxisTransform, yTI, axis,joystickValue.y, yAxisCharacterController); if (enableYClamp && yTI == PropertiesInfluenced.RotateLocal){ DoAngleLimitation( yAxisTransform, yAI, clampYMin, clampYMax, startYLocalAngle ); } } } void UpdateGravity(){ // Gravity if (xAxisCharacterController!=null && xAxisGravity>0){ xAxisCharacterController.Move( Vector3.down*xAxisGravity*Time.deltaTime); } if (yAxisCharacterController!=null && yAxisGravity>0){ yAxisCharacterController.Move( Vector3.down*yAxisGravity*Time.deltaTime); } } Vector3 GetInfluencedAxis(AxisInfluenced axisInfluenced){ Vector3 axis = Vector3.zero; switch(axisInfluenced){ case AxisInfluenced.X: axis = Vector3.right; break; case AxisInfluenced.Y: axis = Vector3.up; break; case AxisInfluenced.Z: axis = Vector3.forward; break; case AxisInfluenced.XYZ: axis = Vector3.one; break; } return axis; } void DoActionDirect(Transform axisTransform, PropertiesInfluenced inlfuencedProperty,Vector3 axis, float sensibility, CharacterController charact){ switch(inlfuencedProperty){ case PropertiesInfluenced.Rotate: axisTransform.Rotate( axis * sensibility * Time.deltaTime,Space.World); break; case PropertiesInfluenced.RotateLocal: axisTransform.Rotate( axis * sensibility * Time.deltaTime,Space.Self); break; case PropertiesInfluenced.Translate: if (charact==null){ axisTransform.Translate(axis * sensibility * Time.deltaTime,Space.World); } else{ charact.Move( axis * sensibility * Time.deltaTime ); } break; case PropertiesInfluenced.TranslateLocal: if (charact==null){ axisTransform.Translate(axis * sensibility * Time.deltaTime,Space.Self); } else{ charact.Move( charact.transform.TransformDirection(axis) * sensibility * Time.deltaTime ); } break; case PropertiesInfluenced.Scale: axisTransform.localScale += axis * sensibility * Time.deltaTime; break; } } void DoAngleLimitation(Transform axisTransform, AxisInfluenced axisInfluenced,float clampMin, float clampMax,float startAngle){ float angle=0; switch(axisInfluenced){ case AxisInfluenced.X: angle = axisTransform.localRotation.eulerAngles.x; break; case AxisInfluenced.Y: angle = axisTransform.localRotation.eulerAngles.y; break; case AxisInfluenced.Z: angle = axisTransform.localRotation.eulerAngles.z; break; } if (angle<=360 && angle>=180){ angle = angle -360; } //angle = Mathf.Clamp (angle, startAngle-clampMax, clampMin+startAngle); angle = Mathf.Clamp (angle, -clampMax, clampMin); switch(axisInfluenced){ case AxisInfluenced.X: axisTransform.localEulerAngles = new Vector3( angle,axisTransform.localEulerAngles.y, axisTransform.localEulerAngles.z); break; case AxisInfluenced.Y: axisTransform.localEulerAngles = new Vector3( axisTransform.localEulerAngles.x,angle, axisTransform.localEulerAngles.z); break; case AxisInfluenced.Z: axisTransform.localEulerAngles = new Vector3( axisTransform.localEulerAngles.x,axisTransform.localEulerAngles.y,angle); break; } } void DoAutoStabilisation(Transform axisTransform, AxisInfluenced axisInfluenced, float threshold, float speed,float startAngle){ float angle=0; switch(axisInfluenced){ case AxisInfluenced.X: angle = axisTransform.localRotation.eulerAngles.x; break; case AxisInfluenced.Y: angle = axisTransform.localRotation.eulerAngles.y; break; case AxisInfluenced.Z: angle = axisTransform.localRotation.eulerAngles.z; break; } if (angle<=360 && angle>=180){ angle = angle -360; } if (angle > startAngle - threshold || angle < startAngle + threshold){ float axis=0; Vector3 stabAngle = Vector3.zero; if (angle > startAngle - threshold){ axis = angle + speed/100f*Mathf.Abs (angle-startAngle) * Time.deltaTime*-1; } if (angle < startAngle + threshold){ axis = angle + speed/100f*Mathf.Abs (angle-startAngle) * Time.deltaTime; } switch(axisInfluenced){ case AxisInfluenced.X: stabAngle = new Vector3(axis,axisTransform.localRotation.eulerAngles.y,axisTransform.localRotation.eulerAngles.z); break; case AxisInfluenced.Y: stabAngle = new Vector3(axisTransform.localRotation.eulerAngles.x,axis,axisTransform.localRotation.eulerAngles.z); break; case AxisInfluenced.Z: stabAngle = new Vector3(axisTransform.localRotation.eulerAngles.x,axisTransform.localRotation.eulerAngles.y,axis); break; } axisTransform.localRotation = Quaternion.Euler( stabAngle); } } float GetStartAutoStabAngle(Transform axisTransform, AxisInfluenced axisInfluenced){ float angle=0; if (axisTransform!=null){ switch(axisInfluenced){ case AxisInfluenced.X: angle = axisTransform.localRotation.eulerAngles.x; break; case AxisInfluenced.Y: angle = axisTransform.localRotation.eulerAngles.y; break; case AxisInfluenced.Z: angle = axisTransform.localRotation.eulerAngles.z; break; } if (angle<=360 && angle>=180){ angle = angle -360; } } return angle; } float ComputeDeadZone(){ float dead = 0; float dist = Mathf.Max(joystickTouch.magnitude,0.1f); if (restrictArea){ dead = Mathf.Max(dist - deadZone, 0)/(zoneRadius-touchSize - deadZone)/dist; } else{ dead = Mathf.Max(dist - deadZone, 0)/(zoneRadius - deadZone)/dist; } return dead; } void ComputeJoystickAnchor(JoystickAnchor anchor){ float touch=0; if (!restrictArea){ touch = touchSize; } // Anchor position switch (anchor){ case JoystickAnchor.UpperLeft: anchorPosition = new Vector2( zoneRadius+touch, zoneRadius+touch); break; case JoystickAnchor.UpperCenter: anchorPosition = new Vector2( VirtualScreen.width/2, zoneRadius+touch); break; case JoystickAnchor.UpperRight: anchorPosition = new Vector2( VirtualScreen.width-zoneRadius-touch,zoneRadius+touch); break; case JoystickAnchor.MiddleLeft: anchorPosition = new Vector2( zoneRadius+touch, VirtualScreen.height/2); break; case JoystickAnchor.MiddleCenter: anchorPosition = new Vector2( VirtualScreen.width/2, VirtualScreen.height/2); break; case JoystickAnchor.MiddleRight: anchorPosition = new Vector2( VirtualScreen.width-zoneRadius-touch,VirtualScreen.height/2); break; case JoystickAnchor.LowerLeft: anchorPosition = new Vector2( zoneRadius+touch, VirtualScreen.height-zoneRadius-touch); break; case JoystickAnchor.LowerCenter: anchorPosition = new Vector2( VirtualScreen.width/2, VirtualScreen.height-zoneRadius-touch); break; case JoystickAnchor.LowerRight: anchorPosition = new Vector2( VirtualScreen.width-zoneRadius-touch,VirtualScreen.height-zoneRadius-touch); break; case JoystickAnchor.None: anchorPosition = Vector2.zero; break; } //joystick rect areaRect = new Rect(anchorPosition.x + joystickCenter.x -zoneRadius , anchorPosition.y+joystickCenter.y-zoneRadius,zoneRadius*2,zoneRadius*2); deadRect = new Rect(anchorPosition.x + joystickCenter.x -deadZone,anchorPosition.y + joystickCenter.y-deadZone,deadZone*2,deadZone*2); } #endregion #region EasyTouch events // Touch start void On_TouchStart(Gesture gesture){ if (!visible) return; if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){ if (isActivated){ if (!dynamicJoystick){ Vector2 center = new Vector2( (anchorPosition.x+joystickCenter.x) * VirtualScreen.xRatio , (VirtualScreen.height-anchorPosition.y - joystickCenter.y) * VirtualScreen.yRatio); if ((gesture.position - center).sqrMagnitude < (zoneRadius *VirtualScreen.xRatio )*(zoneRadius *VirtualScreen.xRatio )){ joystickIndex = gesture.fingerIndex; CreateEvent(MessageName.On_JoystickTouchStart); } } else{ if (!virtualJoystick){ #region area restriction switch (area){ // full case DynamicArea.FullScreen: virtualJoystick = true; ; break; // bottom case DynamicArea.Bottom: if (gesture.position.y< Screen.height/2){ virtualJoystick = true; } break; // top case DynamicArea.Top: if (gesture.position.y> Screen.height/2){ virtualJoystick = true; } break; // Right case DynamicArea.Right: if (gesture.position.x> Screen.width/2){ virtualJoystick = true; } break; // Left case DynamicArea.Left: if (gesture.position.x< Screen.width/2){ virtualJoystick = true; } break; // top Right case DynamicArea.TopRight: if (gesture.position.y> Screen.height/2 && gesture.position.x> Screen.width/2){ virtualJoystick = true; } break; // top Left case DynamicArea.TopLeft: if (gesture.position.y> Screen.height/2 && gesture.position.x< Screen.width/2){ virtualJoystick = true; } break; // bottom Right case DynamicArea.BottomRight: if (gesture.position.y< Screen.height/2 && gesture.position.x> Screen.width/2){ virtualJoystick = true; } break; // bottom left case DynamicArea.BottomLeft: if (gesture.position.y< Screen.height/2 && gesture.position.x< Screen.width/2){ virtualJoystick = true; } break; } #endregion if (virtualJoystick){ joystickCenter =new Vector2(gesture.position.x/VirtualScreen.xRatio, VirtualScreen.height - gesture.position.y/VirtualScreen.yRatio); JoyAnchor = JoystickAnchor.None; joystickIndex = gesture.fingerIndex; } } } } } } // Simple tap void On_SimpleTap(Gesture gesture){ if (!visible) return; if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){ if (isActivated){ if (gesture.fingerIndex == joystickIndex){ CreateEvent(MessageName.On_JoystickTap); } } } } // Double tap void On_DoubleTap(Gesture gesture){ if (!visible) return; if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){ if (isActivated){ if (gesture.fingerIndex == joystickIndex){ CreateEvent(MessageName.On_JoystickDoubleTap); } } } } // Joystick move void On_TouchDown(Gesture gesture){ if (!visible) return; if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){ if (isActivated){ Vector2 center = new Vector2( (anchorPosition.x+joystickCenter.x) * VirtualScreen.xRatio , (VirtualScreen.height-(anchorPosition.y +joystickCenter.y)) * VirtualScreen.yRatio); if (gesture.fingerIndex == joystickIndex){ if (((gesture.position - center).sqrMagnitude < (zoneRadius *VirtualScreen.xRatio )*(zoneRadius *VirtualScreen.xRatio) && resetFingerExit) || !resetFingerExit) { joystickTouch = new Vector2( gesture.position.x , gesture.position.y) - center; joystickTouch = new Vector2( joystickTouch.x / VirtualScreen.xRatio, joystickTouch.y / VirtualScreen.yRatio); if (!enableXaxis){ joystickTouch.x =0; } if (!enableYaxis){ joystickTouch.y=0; } if ((joystickTouch/(zoneRadius-touchSizeCoef)).sqrMagnitude > 1){ joystickTouch.Normalize(); joystickTouch *= zoneRadius-touchSizeCoef; } } else{ On_TouchUp( gesture); } } } } } // Touch end void On_TouchUp( Gesture gesture){ if (!visible) return; if ((!gesture.isHoverReservedArea && dynamicJoystick) || !dynamicJoystick){ if (isActivated){ if (gesture.fingerIndex == joystickIndex){ joystickIndex=-1; if (dynamicJoystick){ virtualJoystick=false; } CreateEvent(MessageName.On_JoystickTouchUp); } } } } #endregion #region ManualJoystick public void On_Manual(Vector2 movement) { if (isActivated) { if (movement != Vector2.zero) { if (!virtualJoystick) { virtualJoystick = true; CreateEvent(MessageName.On_JoystickTouchStart); } joystickIndex = 0; joystickTouch.x = movement.x * (areaRect.width / 2); joystickTouch.y = movement.y * (areaRect.height / 2); } else { if (virtualJoystick) { virtualJoystick = false; joystickIndex=-1; CreateEvent(MessageName.On_JoystickTouchUp); } } } } #endregion }
/* * MindTouch Dream - a distributed REST framework * Copyright (C) 2006-2014 MindTouch, Inc. * www.mindtouch.com oss@mindtouch.com * * For community documentation and downloads visit mindtouch.com; * please review the licensing section. * * 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.Generic; using System.Globalization; using System.Security.Cryptography; using System.Security.Principal; using System.Text; using Autofac; using MindTouch.Security.Cryptography; using MindTouch.Tasking; using MindTouch.Web; namespace MindTouch.Dream { /// <summary> /// Provides request context information for <see cref="DreamFeature"/> request processing. /// </summary> public class DreamContext : ITaskLifespan { //--- Class Fields --- private static log4net.ILog _log = LogUtils.CreateLog(); private static int _contextIdCounter = 0; //--- Class Properties --- /// <summary> /// Singleton accessor for the current request context. /// </summary> /// <remarks> Will throw an <see cref="DreamContextAccessException"/> if there is no context defined.</remarks> /// <exception cref="DreamContextAccessException">Thrown if no context is defined in the current environment or the context has been disposed.</exception> public static DreamContext Current { get { TaskEnv current = TaskEnv.CurrentOrNull; if(current == null) { throw new DreamContextAccessException("DreamContext.Current is not set because there is no task environment."); } DreamContext context = current.GetState<DreamContext>(); if(context == null) { throw new DreamContextAccessException("DreamContext.Current is not set because the current task environment does not contain a reference."); } if(context._isTaskDisposed) { throw new DreamContextAccessException("DreamContext.Current is not set because the current context is already disposed."); } return context; } } /// <summary> /// Singleton accessor to current request context or <see langword="null"/>, if none is defined. /// </summary> public static DreamContext CurrentOrNull { get { TaskEnv current = TaskEnv.CurrentOrNull; if(current == null) { return null; } DreamContext context = current.GetState<DreamContext>(); if(context == null) { return null; } if(context._isTaskDisposed) { _log.Warn("requested already disposed context via CurrentOrNull, returning null"); return null; } return context; } } //--- Fields --- /// <summary> /// Dream environment. /// </summary> public readonly IDreamEnvironment Env; /// <summary> /// Unique Identifier of the request. /// </summary> public readonly int ID; /// <summary> /// Request Http Verb. /// </summary> public readonly string Verb; /// <summary> /// Request Uri. /// </summary> public readonly XUri Uri; /// <summary> /// Dream feature responsible for handling the request. /// </summary> public readonly DreamFeature Feature; /// <summary> /// Incoming request message. /// </summary> public readonly DreamMessage Request; // TODO (arnec): StartTime should eventually be mirroed with EndTime and a Duration attribute on features // for now it's just the time the request started that should be used instead of GlobalClock.UtcNow /// <summary> /// Time the request started. /// </summary> public readonly DateTime StartTime; private readonly XUri _publicUri; private readonly string[] _suffixes; private readonly Dictionary<string, string[]> _pathParams; private readonly Dictionary<string, string> _license; private readonly Func<Action<ContainerBuilder>, ILifetimeScope> _requestContainerFactory; private XUri _publicUriOverride; private XUri _serverUri; private Hashtable _state; private System.Diagnostics.StackTrace _stackTrace = DebugUtil.GetStackTrace(); private CultureInfo _culture; private bool _isTaskDisposed; private ILifetimeScope _lifetimeScope; private TaskEnv _ownerEnv; //--- Constructors --- /// <summary> /// Create instance. /// </summary> /// <param name="env">Dream Environment.</param> /// <param name="verb">Http request verb.</param> /// <param name="uri">Request Uri.</param> /// <param name="feature">Request handling feature.</param> /// <param name="publicUri">Public Uri for incoming request.</param> /// <param name="serverUri">Server Uri for Dream Host.</param> /// <param name="request">Request message.</param> /// <param name="culture">Request Culture.</param> /// <param name="requestContainerFactory">Factory delegate to create a request container on demand.</param> public DreamContext(IDreamEnvironment env, string verb, XUri uri, DreamFeature feature, XUri publicUri, XUri serverUri, DreamMessage request, CultureInfo culture, Func<Action<ContainerBuilder>, ILifetimeScope> requestContainerFactory) { if(env == null) { throw new ArgumentNullException("env"); } if(verb == null) { throw new ArgumentNullException("verb"); } if(uri == null) { throw new ArgumentNullException("uri"); } if(feature == null) { throw new ArgumentNullException("feature"); } if(publicUri == null) { throw new ArgumentNullException("publicUri"); } if(request == null) { throw new ArgumentNullException("request"); } if(culture == null) { throw new ArgumentNullException("culture"); } if(requestContainerFactory == null) { throw new ArgumentNullException("requestContainerFactory"); } this.ID = System.Threading.Interlocked.Increment(ref _contextIdCounter); this.Env = env; this.Verb = verb; this.Uri = uri; this.Feature = feature; this.Feature.ExtractArguments(this.Uri, out _suffixes, out _pathParams); this.ServerUri = serverUri; this.Request = request; this.StartTime = GlobalClock.UtcNow; _publicUri = publicUri; _culture = culture; _requestContainerFactory = requestContainerFactory; // get service license _license = CheckServiceLicense(); } private DreamContext(IDreamEnvironment env, string verb, XUri uri, DreamFeature feature, XUri publicUri, XUri serverUri, DreamMessage request, CultureInfo culture, Func<Action<ContainerBuilder>, ILifetimeScope> requestContainerFactory, Dictionary<string, string> license) { if(env == null) { throw new ArgumentNullException("env"); } if(verb == null) { throw new ArgumentNullException("verb"); } if(uri == null) { throw new ArgumentNullException("uri"); } if(feature == null) { throw new ArgumentNullException("feature"); } if(publicUri == null) { throw new ArgumentNullException("publicUri"); } if(request == null) { throw new ArgumentNullException("request"); } if(culture == null) { throw new ArgumentNullException("culture"); } if(requestContainerFactory == null) { throw new ArgumentNullException("requestContainerFactory"); } this.ID = System.Threading.Interlocked.Increment(ref _contextIdCounter); this.Env = env; this.Verb = verb; this.Uri = uri; this.Feature = feature; this.Feature.ExtractArguments(this.Uri, out _suffixes, out _pathParams); this.ServerUri = serverUri; this.Request = request; this.StartTime = GlobalClock.UtcNow; _publicUri = publicUri; _culture = culture; _requestContainerFactory = requestContainerFactory; _license = license; } //--- Properties --- /// <summary> /// Dream Service handling the request. /// </summary> public IDreamService Service { get { return Feature.Service; } } /// <summary> /// <see langword="True"/> if the context has state attached to it. /// </summary> public bool HasState { get { return _state != null; } } /// <summary> /// Service license for this request. /// </summary> public Dictionary<string, string> ServiceLicense { get { return _license; } } /// <summary> /// <see langword="True"/> if the underlying Task environment has disposed this context. /// </summary> public bool IsTaskEnvDisposed { get { return _isTaskDisposed; } } /// <summary> /// Uri by which the host is known publicly in the context of this request. /// </summary> public XUri PublicUri { get { return _publicUriOverride ?? _publicUri; } } /// <summary> /// Culture of the request. /// </summary> public CultureInfo Culture { get { return _culture; } set { if(value == null) { throw new NullReferenceException("value"); } _culture = value; } } /// <summary> /// Uri the Dream Host is registered for. /// </summary> public XUri ServerUri { get { return _serverUri; } set { if(_serverUri != null) { throw new Exception("server uri already set"); } if(value == null) { throw new ArgumentNullException("value"); } _serverUri = value; } } /// <summary> /// User, if any, authenticated for this request. /// </summary> public IPrincipal User { get { return GetState<IPrincipal>(); } set { SetState(value); } } /// <summary> /// Request Inversion of Control container. /// </summary> public ILifetimeScope Container { get { if(_lifetimeScope == null ) { _lifetimeScope = _requestContainerFactory(builder => builder.RegisterInstance(this).ExternallyOwned()); } return _lifetimeScope; } } /// <summary> /// Request State. /// </summary> private Hashtable State { get { if(_state == null) { _state = new Hashtable(); } return _state; } } //--- Methods --- /// <summary> /// Attach the context to the current context. /// </summary> /// <remarks> /// Throws <see cref="DreamContextAccessException"/> if the context is already attached to /// a task environemnt of the task environment already has a context. /// </remarks> /// <exception cref="DreamContextAccessException">Context is either attached to a <see cref="TaskEnv"/> or the current <see cref="TaskEnv"/> /// already has a context attached.</exception> public void AttachToCurrentTaskEnv() { lock(this) { var env = TaskEnv.Current; if(env.GetState<DreamContext>() != null) { throw new DreamContextAccessException("tried to attach dreamcontext to env that already has a dreamcontext"); } if(_ownerEnv != null && _ownerEnv == env) { throw new DreamContextAccessException("tried to re-attach dreamcontext to env it is already attached to"); } if(_ownerEnv != null) { throw new DreamContextAccessException("tried to attach dreamcontext to an env, when it already is attached to another"); } _ownerEnv = env; env.SetState(this); } } /// <summary> /// Detach the context from the its task environment. /// </summary> /// <remarks> /// Must be done in the context's task environment. /// </remarks> public void DetachFromTaskEnv() { lock(this) { if(TaskEnv.CurrentOrNull != _ownerEnv) { _log.Warn("detaching context in env other than owning end"); } _ownerEnv.RemoveState(this); _ownerEnv = null; } } /// <summary> /// Override the <see cref="PublicUri"/> for this request. /// </summary> /// <param name="publicUri">Publicly accessible Uri.</param> public void SetPublicUriOverride(XUri publicUri) { _publicUriOverride = publicUri; } /// <summary> /// Remove any <see cref="PublicUri"/> override. /// </summary> public void ClearPublicUriOverride() { _publicUriOverride = null; } /// <summary> /// Number of suffixes for this feature path. /// </summary> /// <returns></returns> public int GetSuffixCount() { EnsureFeatureIsSet(); return _suffixes.Length; } /// <summary> /// Get a suffix. /// </summary> /// <param name="index">Index of path suffix.</param> /// <param name="format">Uri path format.</param> /// <returns>Suffix.</returns> public string GetSuffix(int index, UriPathFormat format) { EnsureFeatureIsSet(); string suffix = _suffixes[index]; switch(format) { case UriPathFormat.Original: return suffix; case UriPathFormat.Decoded: return XUri.Decode(suffix); case UriPathFormat.Normalized: return XUri.Decode(suffix).ToLowerInvariant(); default: throw new ArgumentException("format"); } } /// <summary> /// Get all suffixes. /// </summary> /// <param name="format">Uri path format for suffixes.</param> /// <returns>Array of suffixes.</returns> public string[] GetSuffixes(UriPathFormat format) { EnsureFeatureIsSet(); string[] result = new string[_suffixes.Length]; switch(format) { case UriPathFormat.Original: for(int i = 0; i < result.Length; ++i) { result[i] = _suffixes[i]; } break; case UriPathFormat.Decoded: for(int i = 0; i < result.Length; ++i) { result[i] = XUri.Decode(_suffixes[i]); } break; case UriPathFormat.Normalized: for(int i = 0; i < result.Length; ++i) { result[i] = XUri.Decode(_suffixes[i]).ToLowerInvariant(); } break; default: throw new ArgumentException("format"); } return result; } /// <summary> /// Request parameters. /// </summary> /// <remarks> /// Parameters refers to both query and path parameters. /// </remarks> /// <returns>Array parameter key/value pairs.</returns> public KeyValuePair<string, string>[] GetParams() { EnsureFeatureIsSet(); if(Uri.Params != null) { int count = _pathParams.Count + Uri.Params.Length; List<KeyValuePair<string, string>> result = new List<KeyValuePair<string, string>>(count); foreach(KeyValuePair<string, string[]> pair in _pathParams) { foreach(string value in pair.Value) { result.Add(new KeyValuePair<string, string>(pair.Key, value)); } } foreach(KeyValuePair<string, string> pair in Uri.Params) { result.Add(pair); } return result.ToArray(); } else { return new KeyValuePair<string, string>[0]; } } /// <summary> /// Get all values for a named parameter. /// </summary> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <returns>Text values of parameter.</returns> /// <exception cref="DreamAbortException">Throws if parameter does not exist.</exception> public string[] GetParams(string key) { EnsureFeatureIsSet(); if(key == null) { throw new ArgumentNullException("key"); } string[] values; if(!_pathParams.TryGetValue(key, out values) || (values == null)) { values = Uri.GetParams(key); } return values ?? new string[0]; } /// <summary> /// Get a named parameter. /// </summary> /// <remarks> /// Will throw <see cref="DreamAbortException"/> if the named parameter does not exist. /// </remarks> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <returns>Text value of parameter.</returns> /// <exception cref="DreamAbortException">Throws if parameter does not exist.</exception> public string GetParam(string key) { EnsureFeatureIsSet(); if(key == null) { throw new ArgumentNullException("key"); } string result; string[] values; _pathParams.TryGetValue(key, out values); if((values != null) && (values.Length > 0)) { result = values[0]; } else { result = Uri.GetParam(key, null); } if(result == null) { throw new DreamAbortException(DreamMessage.BadRequest(string.Format("missing feature parameter '{0}'", key))); } return result; } /// <summary> /// Get a named parameter. /// </summary> /// <typeparam name="T">Type to convert parameter to.</typeparam> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <returns>Parameter value converted to requested type.</returns> public T GetParam<T>(string key) { string result = GetParam(key); try { return (T)SysUtil.ChangeType(result, typeof(T)); } catch { throw new DreamAbortException(DreamMessage.BadRequest(string.Format("invalid value for feature parameter '{0}'", key))); } } /// <summary> /// Get a named parameter. /// </summary> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <param name="def">Default value to return in case parameter is not defined.</param> /// <returns>Text value of parameter</returns> public string GetParam(string key, string def) { EnsureFeatureIsSet(); if(key == null) { throw new ArgumentNullException("key"); } string result; string[] values; _pathParams.TryGetValue(key, out values); if((values != null) && (values.Length > 0)) { result = values[0]; } else { result = Uri.GetParam(key, null); } return result ?? def; } /// <summary> /// Get a named parameter. /// </summary> /// <typeparam name="T">Type to convert parameter to.</typeparam> /// <param name="key"><see cref="DreamFeatureParamAttribute"/> name.</param> /// <param name="def">Default value to return in case parameter is not defined.</param> /// <returns>Parameter value converted to requested type.</returns> public T GetParam<T>(string key, T def) where T : struct { string result = GetParam(key, null); if(result != null) { try { return (T)SysUtil.ChangeType<T>(result); } catch { throw new DreamAbortException(DreamMessage.BadRequest(string.Format("invalid value for feature parameter '{0}'", key))); } } return def; } /// <summary> /// Relay a request to another service using the current query parameters, service cookies and verb. /// </summary> /// <remarks> /// Must be yielded by a coroutine or invoked with <see cref="Coroutine.Invoke"/>. /// </remarks> /// <param name="plug">Location of relay recipient.</param> /// <param name="request">Request message to relay.</param> /// <param name="response">The <see cref="Result{DreamMessage}"/> instance this coroutine will use as a synchronization handle.</param> /// <returns>Iterator used by <see cref="Coroutine"/> execution environment.</returns> public IYield Relay(Plug plug, DreamMessage request, Result<DreamMessage> response) { return Relay(plug, Verb, request, response); } /// <summary> /// Relay a request to another service using the current query parameters and service cookies. /// </summary> /// <remarks> /// Must be yielded by a coroutine or invoked with <see cref="Coroutine.Invoke"/>. /// </remarks> /// <param name="plug">Location of relay recipient.</param> /// <param name="verb">Http verb to use for relay.</param> /// <param name="request">Request message to relay.</param> /// <param name="response">The <see cref="Result{DreamMessage}"/> instance this coroutine will use as a synchronization handle.</param> /// <returns>Iterator used by <see cref="Coroutine"/> execution environment.</returns> public IYield Relay(Plug plug, string verb, DreamMessage request, Result<DreamMessage> response) { // combine query parameters of current request with new target URI, then append suffix segments Result<DreamMessage> inner = new Result<DreamMessage>(response.Timeout); Result result = new Result(TimeSpan.MaxValue); Plug.New(plug.Uri.WithParamsFrom(Uri)).InvokeEx(verb, request, inner).WhenDone(_unused => { response.Return(inner); result.Return(); }); return result; } /// <summary> /// Get a typed state variable /// </summary> /// <remarks>Since the type is used as the state key, can only contain one instance for this type. This call is thread-safe.</remarks> /// <typeparam name="T">Type of state variable.</typeparam> /// <returns>Instance or default for type.</returns> public T GetState<T>() { lock(State) { return (T)(State.ContainsKey(typeof(T)) ? State[typeof(T)] : default(T)); } } /// <summary> /// Store a typed state variable. /// </summary> /// <remarks>Since the type is used as the state key, can only contain one instance for this type. This call is thread-safe.</remarks> /// <typeparam name="T">Type of state variable.</typeparam> /// <param name="value">Instance to store.</param> public void SetState<T>(T value) { lock(State) { State[typeof(T)] = value; } } /// <summary> /// Get a typed state variable by key. /// </summary> /// <remarks>This call is thread-safe.</remarks> /// <typeparam name="T">Type of state variable.</typeparam> /// <param name="key">State variable key.</param> /// <returns>Instance or default for type.</returns> public T GetState<T>(string key) { lock(State) { return (T)(State.ContainsKey(key) ? State[key] : default(T)); } } /// <summary> /// Store a typed state variable by key. /// </summary> /// <remarks>This call is thread-safe.</remarks> /// <typeparam name="T">Type of state variable.</typeparam> /// <param name="key">State variable key.</param> /// <param name="value">Instance to store.</param> public void SetState<T>(string key, T value) { lock(State) { State[key] = value; } } /// <summary> /// Convert a Uri to a host local Uri, if possible. /// </summary> /// <remarks> /// Will return the original Uri if there is no local equivalent. /// </remarks> /// <param name="uri">Uri to convert.</param> /// <returns>Local Uri.</returns> public XUri AsLocalUri(XUri uri) { XUri result = uri; if(uri.Similarity(PublicUri) == PublicUri.MaxSimilarity) { result = uri.ChangePrefix(PublicUri, Env.LocalMachineUri); } else if((ServerUri != null) && (uri.Similarity(ServerUri) == ServerUri.MaxSimilarity)) { result = uri.ChangePrefix(ServerUri, Env.LocalMachineUri); } return result; } /// <summary> /// Convert a Uri to uri relative to the requests public uri, if possible. /// </summary> /// <remarks> /// Will return the original Uri if there is no public equivalent. /// </remarks> /// <param name="uri">Uri to convert.</param> /// <returns>Public Uri.</returns> public XUri AsPublicUri(XUri uri) { XUri result = uri; if(uri.Similarity(Env.LocalMachineUri) == Env.LocalMachineUri.MaxSimilarity) { result = uri.ChangePrefix(Env.LocalMachineUri, PublicUri); } return result; } /// <summary> /// Convert a Uri to uri relative to the server's public uri, if possible. /// </summary> /// <remarks> /// Will return the original Uri if there is no public equivalent. /// </remarks> /// <param name="uri">Uri to convert.</param> /// <returns>Public Uri.</returns> public XUri AsServerUri(XUri uri) { XUri result = uri; if((ServerUri != null) && (uri.Similarity(Env.LocalMachineUri) == Env.LocalMachineUri.MaxSimilarity)) { result = uri.ChangePrefix(Env.LocalMachineUri, ServerUri); } return result; } /// <summary> /// Replace the context's own state with a clone of the state of another context. /// </summary> /// <param name="context"></param> public void CloneStateFromContext(DreamContext context) { if(context.HasState) { lock(context._state) { var state = State; foreach(DictionaryEntry entry in context._state) { var cloneable = entry.Value as ITaskLifespan; state[entry.Key] = (cloneable == null) ? entry.Value : cloneable.Clone(); } } } } internal DreamContext CreateContext(string verb, XUri uri, DreamFeature feature, DreamMessage message) { return new DreamContext(Env, verb, uri, feature, PublicUri, ServerUri, message, Culture, _requestContainerFactory, null); } private void EnsureFeatureIsSet() { if(Feature == null) { throw new InvalidOperationException("feature not set"); } } private Dictionary<string, string> CheckServiceLicense() { // check request validity (unless it's for the @config uri, which is a special case) Dictionary<string, string> result = null; if((Feature.Service.Self != null) && (Feature.Service is IDreamServiceLicense) && !(Uri.LastSegment ?? string.Empty).EqualsInvariant("@config")) { string service_license = ((IDreamServiceLicense)Feature.Service).ServiceLicense; if(string.IsNullOrEmpty(service_license)) { throw new DreamAbortException(DreamMessage.LicenseRequired("service-license missing")); } // extract public RSA key for validation RSACryptoServiceProvider public_key = RSAUtil.ProviderFrom(Feature.Service.GetType().Assembly); if(public_key == null) { throw new DreamAbortException(DreamMessage.InternalError("service assembly invalid")); } // validate the service-license try { // parse service-license result = HttpUtil.ParseNameValuePairs(service_license); if(!Encoding.UTF8.GetBytes(service_license.Substring(0, service_license.LastIndexOf(','))).VerifySignature(result["dsig"], public_key)) { throw new DreamAbortException(DreamMessage.InternalError("invalid service-license")); } } catch(Exception e) { // unexpected error, blame it on the license if(e is DreamAbortException) { throw; } else { throw new DreamAbortException(DreamMessage.InternalError("corrupt service-license")); } } // check license string text; if((!result.TryGetValue("licensee", out text) || string.IsNullOrEmpty(text)) && !result.ContainsKey("expire")) { // unexpected error, blame it on the license throw new DreamAbortException(DreamMessage.InternalError("corrupt service-license")); } // determine 'now' date-time DateTime now = GlobalClock.UtcNow; DateTime? request_date = Request.Headers.Date; if(request_date.HasValue) { now = (request_date.Value > now) ? request_date.Value : now; } // check expiration DateTime expire; if(result.TryGetValue("expire", out text) && (!DateTimeUtil.TryParseInvariant(text, out expire) || (expire.ToUniversalTime() < now))) { throw new DreamAbortException(DreamMessage.LicenseRequired("service-license has expired")); } } return result; } #region ITaskLifespan Members object ITaskLifespan.Clone() { var context = new DreamContext(Env, Verb, Uri, Feature, _publicUri, _serverUri, Request, _culture, _requestContainerFactory, _license); context.CloneStateFromContext(this); return context; } void ITaskLifespan.Dispose() { if(_isTaskDisposed) { _log.Warn("disposing already disposed context"); } _isTaskDisposed = true; if(_lifetimeScope != null) { _lifetimeScope.Dispose(); _lifetimeScope = null; } if(_state == null) { return; } lock(_state) { foreach(var item in _state.Values) { var disposable = item as ITaskLifespan; if(disposable == null) { continue; } disposable.Dispose(); } _state.Clear(); } } #endregion } }
//--------------------------------------------------------------------------- // // <copyright file="WindowsTooltip.cs" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: Tooltip Proxy // // History: // 07/01/2003 : a-jeanp Created //--------------------------------------------------------------------------- // PRESHARP: In order to avoid generating warnings about unkown message numbers and unknown pragmas. #pragma warning disable 1634, 1691 using System; using System.Globalization; using System.Text; using System.Windows.Automation; using System.Windows.Automation.Provider; using System.Windows; using System.Runtime.InteropServices; using System.ComponentModel; using MS.Win32; namespace MS.Internal.AutomationProxies { // Class definition for the WindowsTooltip proxy. class WindowsTooltip : ProxyHwnd { // ------------------------------------------------------ // // Constructors // // ------------------------------------------------------ #region Constructors // Contructor for the tooltip proxy class. WindowsTooltip (IntPtr hwnd, ProxyFragment parent, int item) : base( hwnd, parent, item) { // Set the control type string to return properly the properties. _cControlType = ControlType.ToolTip; // support for events _createOnEvent = new WinEventTracker.ProxyRaiseEvents (RaiseEvents); } #endregion #region Proxy Create // Static Create method called by UIAutomation to create this proxy. // returns null if unsuccessful internal static IRawElementProviderSimple Create(IntPtr hwnd, int idChild, int idObject) { return Create(hwnd, idChild); } private static IRawElementProviderSimple Create(IntPtr hwnd, int idChild) { // Something is wrong if idChild is not zero if (idChild != 0) { System.Diagnostics.Debug.Assert (idChild == 0, "Invalid Child Id, idChild != 0"); throw new ArgumentOutOfRangeException("idChild", idChild, SR.Get(SRID.ShouldBeZero)); } return new WindowsTooltip(hwnd, null, idChild); } // Static create method called by the event tracker system. // WinEvents are raised only when a notification has been set for a // specific item. internal static void RaiseEvents (IntPtr hwnd, int eventId, object idProp, int idObject, int idChild) { if (idObject != NativeMethods.OBJID_VSCROLL && idObject != NativeMethods.OBJID_HSCROLL) { WindowsTooltip wtv = new WindowsTooltip(hwnd, null, 0); wtv.DispatchEvents(eventId, idProp, idObject, idChild); } } #endregion Proxy Create #region ProxyHwnd Interface internal override void AdviseEventAdded( AutomationEvent eventId, AutomationProperty[] aidProps ) { base.AdviseEventAdded( eventId, aidProps ); // If the framework is advising for ToolTipOpenedEvent then go ahead and raise this event now // since the WinEvent we would listen to (usually EVENT_OBJECT_SHOW) has already occurrred // (it is why Advise is being called). No other action is necessary because when this ToolTip // goes away, AdviseEventRemoved is going to be called. In other words, this proxy gets // created when the ToolTip opens and thrown away when it closes so no need to keep state // that we want to listen for more SHOWS or CREATES - there's always one for any one instance. if( eventId == AutomationElement.ToolTipOpenedEvent ) { AutomationEventArgs e = new AutomationEventArgs(AutomationElement.ToolTipOpenedEvent); AutomationInteropProvider.RaiseAutomationEvent(AutomationElement.ToolTipOpenedEvent, this, e); } else if( eventId == AutomationElement.ToolTipClosedEvent ) { // subscribe to ToolTip specific events, keeping track of how many times the event has been added WinEventTracker.AddToNotificationList( IntPtr.Zero, new WinEventTracker.ProxyRaiseEvents( OnToolTipEvents ), _toolTipEventIds, _toolTipEventIds.Length ); _listenerCount++; } } internal override void AdviseEventRemoved( AutomationEvent eventId, AutomationProperty[] aidProps ) { base.AdviseEventRemoved(eventId, aidProps); // For now, ToolTips only raise ToolTip-specific events when they close if( eventId != AutomationElement.ToolTipClosedEvent ) return; if( _listenerCount > 0 ) { // decrement the event counter --_listenerCount; WinEventTracker.RemoveToNotificationList( IntPtr.Zero, _toolTipEventIds, new WinEventTracker.ProxyRaiseEvents( OnToolTipEvents ), _toolTipEventIds.Length ); } } #endregion ProxyHwnd Interface //------------------------------------------------------ // // Patterns Implementation // //------------------------------------------------------ #region ProxySimple Interface //Gets the localized name internal override string LocalizedName { get { return GetText(); } } #endregion //------------------------------------------------------ // // Private Methods // //------------------------------------------------------ #region Private Methods private static void OnToolTipEvents( IntPtr hwnd, int eventId, object idProp, int idObject, int idChild ) { if (idObject != NativeMethods.OBJID_WINDOW) { return; } if (!IsToolTip(hwnd)) { return; } // Raise ToolTipClosedEvent on OBJECT_HIDE WinEvents. Not raising the event for EVENT_OBJECT_DESTROY // because to do this means having to change code downstream from RaiseAutomationEvent to accept a // null src. PS #1007309 (Client-side proxies that raise events end up going through server-side // code) would be a good time to fix this issue (may then be able to pass null src). Most tool tips // currently get created, then shown and hidden, and are destroyed when the app exits so the impact // here should be minimal since the ToolTip is probaby not showing when the app exits. if( eventId == NativeMethods.EVENT_OBJECT_HIDE /*|| eventId == NativeMethods.EVENT_OBJECT_DESTROY*/ ) { WindowsTooltip wtv = new WindowsTooltip( hwnd, null, 0 ); AutomationEventArgs e = new AutomationEventArgs( AutomationElement.ToolTipClosedEvent ); AutomationInteropProvider.RaiseAutomationEvent( AutomationElement.ToolTipClosedEvent, wtv, e ); } } private static bool IsToolTip( IntPtr hwnd ) { // If we can't determine this is a ToolTip then just return false if (!UnsafeNativeMethods.IsWindow(hwnd)) { return false; } string className = Misc.ProxyGetClassName(hwnd); return String.Compare(className, "tooltips_class32", StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(className, CLASS_TITLEBAR_TOOLTIP, StringComparison.OrdinalIgnoreCase) == 0 || String.Compare(className, "VBBubble", StringComparison.OrdinalIgnoreCase) == 0; } private string GetText() { string className = Misc.ProxyGetClassName(_hwnd); if (String.Compare(className, CLASS_TITLEBAR_TOOLTIP, StringComparison.OrdinalIgnoreCase) == 0) { return GetTitleBarToolTipText(); } else if (String.Compare(className, "VBBubble", StringComparison.OrdinalIgnoreCase) == 0) { // The WM_GETTEXT should work for VBBubble. It seems that the string being returned is having // a problem with Unicode covertion and therefore trunk'ing the string after the first character. } // For tooltips_class32 WM_GETTEXT works fine at getting the text off of the tooltip. return Misc.ProxyGetText(_hwnd); } // Tooltips for titlebar parts requires figuring out what titlebar part the mouse is over and returning // a string defined in this dll that represents the part. The hittesting technique is sensitive to the // desktop theme and composition. The following method uses one technique for composition and another // for all other cases. Fix for WinOS Bug #1656292 (punted to Vienna) will allow using the technique // used in GetTitleBarToolTipTextForDWMEnabled on Vista regardless of themes. private string GetTitleBarToolTipText() { if (System.Environment.OSVersion.Version.Major >= 6) { int isDWMEnabled = 0; // DWM is not enabled try { #pragma warning suppress 56031 // No need to check return value; failure means it isn't enabled UnsafeNativeMethods.DwmIsCompositionEnabled(out isDWMEnabled); } catch (DllNotFoundException) { // The API is not available so we can't be under the DWM // simply ignore the exception } // Using new APIs in Vista to figure out where the cursor is give more // accurate results when composition is enabled. if (isDWMEnabled != 0) return GetTitleBarToolTipTextForDWMEnabled(); } // But until WinOS Bug #1656292 is fixed, hittesting where the cursor is works return GetTitleBarToolTipTextHitTest(); } // For Vista getting the part of the titlebar that a tooltip belongs to is more // reliable across themes private string GetTitleBarToolTipTextForDWMEnabled() { // The mouse is over the titlebar item so get that point on the screen NativeMethods.Win32Point pt = new NativeMethods.Win32Point(); if (!Misc.GetCursorPos(ref pt)) { return ""; } // Find the titlebar hwnd IntPtr hwnd = UnsafeNativeMethods.WindowFromPhysicalPoint(pt.x, pt.y); if (hwnd == IntPtr.Zero) { return ""; } // Get the rects for each titlbar part Rect[] rects = Misc.GetTitlebarRects(hwnd); // Look from back to front - front is entire titlebar rect int scan; for (scan = rects.Length - 1; scan >= 0; scan--) { // Not using Misc.PtInRect because including the bounding pixels all the way around gives // better results; tooltips may appear when the mouse is one or two pixels outside of the // bounding rect so even this technique may miss. if (pt.x >= rects[scan].Left && pt.x <= rects[scan].Right && pt.y >= rects[scan].Top && pt.y <= rects[scan].Bottom) { break; } } switch (scan) { case NativeMethods.INDEX_TITLEBAR_MINBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_MINIMIZE)) return ST.Get(STID.LocalizedNameWindowsTitleBarButtonRestore); else return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMinimize); case NativeMethods.INDEX_TITLEBAR_HELPBUTTON: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonContextHelp); case NativeMethods.INDEX_TITLEBAR_MAXBUTTON: if (Misc.IsBitSet(WindowStyle, NativeMethods.WS_MAXIMIZE)) return ST.Get(STID.LocalizedNameWindowsTitleBarButtonRestore); else return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMaximize); case NativeMethods.INDEX_TITLEBAR_CLOSEBUTTON: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonClose); case NativeMethods.INDEX_TITLEBAR_SELF: return Misc.ProxyGetText(hwnd); default: return ""; } } private string GetTitleBarToolTipTextHitTest() { NativeMethods.Win32Point pt = new NativeMethods.Win32Point(); if (!Misc.GetCursorPos(ref pt)) { return ""; } IntPtr hwnd = UnsafeNativeMethods.WindowFromPhysicalPoint(pt.x, pt.y); if (hwnd == IntPtr.Zero) { return ""; } int hit = Misc.ProxySendMessageInt(hwnd, NativeMethods.WM_NCHITTEST, IntPtr.Zero, NativeMethods.Util.MAKELPARAM(pt.x, pt.y)); switch (hit) { case NativeMethods.HTMINBUTTON: if (Misc.IsBitSet(Misc.GetWindowStyle(hwnd), NativeMethods.WS_MINIMIZE)) return ST.Get(STID.LocalizedNameWindowsTitleBarButtonRestore); else return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMinimize); case NativeMethods.HTMAXBUTTON: if (Misc.IsBitSet(Misc.GetWindowStyle(hwnd), NativeMethods.WS_MAXIMIZE)) return ST.Get(STID.LocalizedNameWindowsTitleBarButtonRestore); else return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMaximize); case NativeMethods.HTCLOSE: case NativeMethods.HTMDICLOSE: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonClose); case NativeMethods.HTHELP: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonContextHelp); case NativeMethods.HTMDIMINBUTTON: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMinimize); case NativeMethods.HTMDIMAXBUTTON: return ST.Get(STID.LocalizedNameWindowsTitleBarButtonMaximize); case NativeMethods.HTCAPTION: return Misc.ProxyGetText(hwnd); default: break; } return ""; } #endregion Private Methods // ------------------------------------------------------ // // Private Fields and Types Declaration // // ------------------------------------------------------ #region Private Fields private readonly static WinEventTracker.EvtIdProperty[] _toolTipEventIds = new WinEventTracker.EvtIdProperty[] { new WinEventTracker.EvtIdProperty(NativeMethods.EVENT_OBJECT_HIDE, 0), //see comment in OnToolTipEvents //new WinEventTracker.EvtIdProperty(NativeMethods.EVENT_OBJECT_DESTROY, 0) }; private static int _listenerCount; private const string CLASS_TITLEBAR_TOOLTIP = "#32774"; #endregion Private Fields } }
using Dynamsoft.Core; using Dynamsoft.Core.Annotation; using Dynamsoft.Core.Enums; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Dynamsoft.PDF; using System.Drawing.Printing; using System.IO; using System.Runtime.InteropServices; namespace Annotation_Samples { public partial class Form1 : Form,IConvertCallback,ISave { private ImageCore m_ImageCore = null; private PDFRasterizer m_Rasterizer = null; private PDFCreator m_Creator = null; private string m_StrProductKey = "t0068UwAAAEQABDxqjGfgEzhVYureL0kGxugcsvIqCDGTPTsR5nLaQsNupIc17Y5vpMZAWBDsd6Xw3NMYzdHlHwiKUrfe/cU="; private List<AnnotationData> m_SeletedAnnotation = new List<AnnotationData>(); public Form1() { InitializeComponent(); m_ImageCore = new ImageCore(); dsViewer1.Bind(m_ImageCore); m_Rasterizer = new PDFRasterizer(m_StrProductKey); m_Creator = new PDFCreator(m_StrProductKey); toolStripCbxPen.SelectedIndex = 0; toolStripCbxFont.SelectedIndex = 0; dsViewer1.Annotation.Type = Dynamsoft.Forms.Enums.EnumAnnotationType.enumPointer; dsViewer1.SetViewMode(1,1); string imagePath = Application.ExecutablePath; imagePath = imagePath.Replace("/", "\\"); string strDllFolder = imagePath; int pos = imagePath.LastIndexOf("\\Samples\\"); if (pos != -1) { imagePath = imagePath.Substring(0, imagePath.IndexOf(@"\", pos)) + @"\Samples\Bin\Images\AnnotationImage\Annotation Sample Image.png"; } else { imagePath = Application.StartupPath + @"\Bin\Images\AnnotationImage\Annotation Sample Image.png"; } m_ImageCore.IO.LoadImage(imagePath); dsViewer1.Annotation.OnAnnotationTextChanged += Annotation_OnAnnotationTextChanged; dsViewer1.Annotation.OnAnnotationSelected += Annotation_OnAnnotationSelected; dsViewer1.Annotation.OnAnnotationDeselected += Annotation_OnAnnotationDeselected; } private void UpdateSelectedAnnotation() { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); if(m_SeletedAnnotation!=null&&m_SeletedAnnotation.Count>0) { m_SeletedAnnotation.Clear(); } foreach (AnnotationData temp in tempAllAnnotation) { if (temp.Selected == true) { if (m_SeletedAnnotation == null) m_SeletedAnnotation = new List<AnnotationData>(); m_SeletedAnnotation.Add(temp); } } if (m_SeletedAnnotation != null) { if (m_SeletedAnnotation.Count > 0) { propertyGrid1.SelectedObject = m_SeletedAnnotation[0]; } } } void Annotation_OnAnnotationDeselected(List<Guid> annotationGuids) { UpdateSelectedAnnotation(); if(m_SeletedAnnotation!=null) if (m_SeletedAnnotation.Count == 0) propertyGrid1.SelectedObject = null; } void Annotation_OnAnnotationSelected(List<Guid> annotationGuids) { UpdateSelectedAnnotation(); } void Annotation_OnAnnotationTextChanged(Guid annotationGuids) { UpdateSelectedAnnotation(); } private void delToolStripMenuItem_Click(object sender, EventArgs e) { DeleteAnnotation(m_SeletedAnnotation); m_SeletedAnnotation = null; } private void DeleteAnnotation(List<AnnotationData> listAnnotation) { if (listAnnotation != null) { if (listAnnotation.Count > 0) { List<AnnotationData> tempAllAnnotation = new List<AnnotationData>(); tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); foreach (AnnotationData temp1 in listAnnotation) { for (short sIndex = 0; sIndex < tempAllAnnotation.Count; sIndex++) { if (temp1.GUID == tempAllAnnotation[sIndex].GUID) { tempAllAnnotation.RemoveAt(sIndex); } } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } propertyGrid1.SelectedObject = null; } } private void openToolStripMenuItem_Click(object sender, EventArgs e) { OpenFileDialog filedlg = new OpenFileDialog(); filedlg.Filter = "All Support Files|*.JPG;*.JPEG;*.JPE;*.JFIF;*.BMP;*.PNG;*.TIF;*.TIFF;*.PDF;*.GIF|JPEG|*.JPG;*.JPEG;*.JPE;*.Jfif|BMP|*.BMP|PNG|*.PNG|TIFF|*.TIF;*.TIFF|PDF|*.PDF|GIF|*.GIF"; filedlg.Multiselect = true; if (filedlg.ShowDialog() == DialogResult.OK) { foreach (string strfilename in filedlg.FileNames) { int pos = strfilename.LastIndexOf("."); if (pos != -1) { string strSuffix = strfilename.Substring(pos, strfilename.Length - pos).ToLower(); if (strSuffix.CompareTo(".pdf") == 0) { m_Rasterizer.ConvertMode = Dynamsoft.PDF.Enums.EnumConvertMode.enumCM_RENDERALL; m_Rasterizer.ConvertToImage(strfilename,"",200,this as IConvertCallback); continue; } } m_ImageCore.IO.LoadImage(strfilename); } } } private void saveToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ImageCore.ImageBuffer.HowManyImagesInBuffer > 0) { SaveFileDialog filedlg = new SaveFileDialog(); filedlg.Filter = "PDF File(*.pdf)| *.pdf"; if (filedlg.ShowDialog() == DialogResult.OK) { m_Creator.Save(this as ISave,filedlg.FileName); } } } private void printToolStripMenuItem_Click(object sender, EventArgs e) { dsViewer1.IfPrintAnnotations = true; PrinterSettings temp = new PrinterSettings(); temp.DefaultPageSettings.Margins = new Margins(0,0,0,0); this.dsViewer1.Print(); } private void closeToolStripMenuItem_Click(object sender, EventArgs e) { this.Close(); } private void lineToolStripMenuItem_Click(object sender, EventArgs e) { AnnotationData tempLineAnnotation = new AnnotationData(); tempLineAnnotation.AnnotationType = AnnotationType.enumLine; tempLineAnnotation.StartPoint = new Point(200, 200); tempLineAnnotation.EndPoint = new Point(260, 280); tempLineAnnotation.PenColor = Color.Black.ToArgb(); tempLineAnnotation.PenWidth = 5; tempLineAnnotation.Description = "Create a line annotation."; tempLineAnnotation.Selected = false; tempLineAnnotation.GUID = Guid.NewGuid(); AddAnnotation(tempLineAnnotation); } private void AddAnnotation(AnnotationData anno) { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); tempAllAnnotation.Add(anno); m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer,EnumMetaDataType.enumAnnotation,tempAllAnnotation,true); } private void ellipseToolStripMenuItem_Click(object sender, EventArgs e) { AnnotationData tempEllipseAnnotation = new AnnotationData(); tempEllipseAnnotation.AnnotationType = AnnotationType.enumEllipse; tempEllipseAnnotation.StartPoint= new Point(300, 300); tempEllipseAnnotation.EndPoint = new Point(380,440); tempEllipseAnnotation.FillColor = Color.Blue.ToArgb(); tempEllipseAnnotation.PenColor = Color.Black.ToArgb(); tempEllipseAnnotation.PenWidth = 2; tempEllipseAnnotation.Description = "Create an ellipse annotation."; tempEllipseAnnotation.Selected = false; tempEllipseAnnotation.GUID = Guid.NewGuid(); AddAnnotation(tempEllipseAnnotation); } private void rectangleToolStripMenuItem_Click(object sender, EventArgs e) { AnnotationData tempRectAnnotation = new AnnotationData(); tempRectAnnotation.AnnotationType = AnnotationType.enumRectangle; tempRectAnnotation.StartPoint = new Point(400, 400); tempRectAnnotation.EndPoint= new Point(490, 520); tempRectAnnotation.FillColor = Color.Green.ToArgb(); tempRectAnnotation.PenColor = Color.Black.ToArgb(); tempRectAnnotation.PenWidth = 2; tempRectAnnotation.Description = "Create a rectangle annotation."; tempRectAnnotation.Selected = false; tempRectAnnotation.GUID = Guid.NewGuid(); AddAnnotation(tempRectAnnotation); } private void textToolStripMenuItem_Click(object sender, EventArgs e) { AnnotationData tempTextAnnotation = new AnnotationData(); tempTextAnnotation.AnnotationType = AnnotationType.enumText; tempTextAnnotation.GUID = Guid.NewGuid(); tempTextAnnotation.StartPoint= new Point(80, 80); tempTextAnnotation.EndPoint = new Point(280, 280); tempTextAnnotation.FontType = new AnnoTextFont(); tempTextAnnotation.FontType.Name = "Microsoft Sans Serif"; tempTextAnnotation.FontType.Size = 30; tempTextAnnotation.FontType.TextColor = Color.Black.ToArgb(); tempTextAnnotation.TextContent = "Dynamsoft"; tempTextAnnotation.Description = "Create a text annotation"; tempTextAnnotation.Selected = false; tempTextAnnotation.GUID = Guid.NewGuid(); AddAnnotation(tempTextAnnotation); } private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e) { List<AnnotationData> temp = new List<AnnotationData>(); m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, temp, true); propertyGrid1.SelectedObject = null; } private List<AnnotationData> m_CopyAnnotation = new List<AnnotationData>(); private void copySelectedToolStripMenuItem_Click(object sender, EventArgs e) { if (m_SeletedAnnotation != null) { if (m_CopyAnnotation != null) m_CopyAnnotation.Clear(); foreach (AnnotationData tempAnnotation in m_SeletedAnnotation) { AnnotationData tempCopyAnnotation = new AnnotationData(); tempCopyAnnotation.GUID = Guid.NewGuid(); tempCopyAnnotation.AnnotationType = tempAnnotation.AnnotationType; tempCopyAnnotation.StartPoint = tempAnnotation.StartPoint; tempCopyAnnotation.EndPoint = tempAnnotation.EndPoint; tempCopyAnnotation.FillColor = tempAnnotation.FillColor; tempCopyAnnotation.Description = tempAnnotation.Description; if (tempAnnotation.FontType != null) { tempCopyAnnotation.FontType = new AnnoTextFont(); tempCopyAnnotation.FontType.Name = tempAnnotation.FontType.Name; tempCopyAnnotation.FontType.Size = tempAnnotation.FontType.Size; tempCopyAnnotation.FontType.TextColor = tempAnnotation.FontType.TextColor; } tempCopyAnnotation.Name = tempAnnotation.Name; tempCopyAnnotation.PenColor = tempAnnotation.PenColor; tempCopyAnnotation.PenWidth = tempAnnotation.PenWidth; tempCopyAnnotation.Selected = false; tempCopyAnnotation.TextContent = tempAnnotation.TextContent; tempCopyAnnotation.TextRotateType = tempAnnotation.TextRotateType; m_CopyAnnotation.Add(tempCopyAnnotation); } } } private void pasteToolStripMenuItem_Click(object sender, EventArgs e) { if (m_CopyAnnotation != null) { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); if (m_CopyAnnotation.Count > 0) { foreach (AnnotationData temp in m_CopyAnnotation) { AnnotationData tempCopyAnnotation = new AnnotationData(); tempCopyAnnotation.GUID = Guid.NewGuid(); tempCopyAnnotation.AnnotationType = temp.AnnotationType; tempCopyAnnotation.StartPoint = temp.StartPoint; tempCopyAnnotation.EndPoint = temp.EndPoint; tempCopyAnnotation.FillColor = temp.FillColor; tempCopyAnnotation.Description = temp.Description; if (temp.FontType != null) { tempCopyAnnotation.FontType = new AnnoTextFont(); tempCopyAnnotation.FontType.Name = temp.FontType.Name; tempCopyAnnotation.FontType.Size = temp.FontType.Size; tempCopyAnnotation.FontType.TextColor = temp.FontType.TextColor; } tempCopyAnnotation.Name = temp.Name; tempCopyAnnotation.PenColor = temp.PenColor; tempCopyAnnotation.PenWidth = temp.PenWidth; tempCopyAnnotation.Selected = false; tempCopyAnnotation.TextContent = temp.TextContent; tempCopyAnnotation.TextRotateType = temp.TextRotateType; tempAllAnnotation.Add(tempCopyAnnotation); } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } } private void bringToFrontToolStripMenuItem_Click(object sender, EventArgs e) { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); if (tempAllAnnotation.Count >= 2) { if (m_SeletedAnnotation.Count == 1) { for (short sIndex = 0; sIndex < tempAllAnnotation.Count; sIndex++) { AnnotationData tempAnnotation = tempAllAnnotation[sIndex]; if (tempAllAnnotation[sIndex].GUID == m_SeletedAnnotation[0].GUID) { { tempAllAnnotation.RemoveAt(sIndex); tempAllAnnotation.Add(tempAnnotation); } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } } } } } private void sendToBackToolStripMenuItem_Click(object sender, EventArgs e) { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); if (tempAllAnnotation.Count >= 2) { if (m_SeletedAnnotation.Count == 1) { for (short sIndex = 0; sIndex < tempAllAnnotation.Count; sIndex++) { AnnotationData tempAnnotation = tempAllAnnotation[sIndex]; if (tempAllAnnotation[sIndex].GUID == m_SeletedAnnotation[0].GUID) { { tempAllAnnotation.RemoveAt(sIndex); tempAllAnnotation.Insert(0,tempAnnotation); } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } } } } } private void toolStripBtnLannotation_Click(object sender, EventArgs e) { dsViewer1.Annotation.Pen = new Pen(toolStripBtnPen.BackColor, int.Parse(toolStripCbxPen.Text)); dsViewer1.Annotation.Type = Dynamsoft.Forms.Enums.EnumAnnotationType.enumLine; } private void toolStripBtnEannotation_Click(object sender, EventArgs e) { dsViewer1.Annotation.Pen = new Pen(toolStripBtnPen.BackColor, int.Parse(toolStripCbxPen.Text)); dsViewer1.Annotation.Type = Dynamsoft.Forms.Enums.EnumAnnotationType.enumEllipse; dsViewer1.Annotation.FillColor = toolStripBtnFill.BackColor; } private void toolStripBtnRannotation_Click(object sender, EventArgs e) { dsViewer1.Annotation.Pen = new Pen(toolStripBtnPen.BackColor, int.Parse(toolStripCbxPen.Text)); dsViewer1.Annotation.Type = Dynamsoft.Forms.Enums.EnumAnnotationType.enumRectangle; dsViewer1.Annotation.FillColor = toolStripBtnFill.BackColor; } private void toolStripBtnTannotation_Click(object sender, EventArgs e) { dsViewer1.Annotation.Pen = new Pen(toolStripBtnPen.BackColor, int.Parse(toolStripCbxPen.Text)); dsViewer1.Annotation.Type = Dynamsoft.Forms.Enums.EnumAnnotationType.enumText; dsViewer1.Annotation.TextColor = toolStripBtnFont.BackColor; dsViewer1.Annotation.TextFont = new Font("", int.Parse(toolStripCbxFont.Text)); } private void toolStripBtnFill_Click(object sender, EventArgs e) { Color color = SelectColor(); if (color != Color.Transparent) { toolStripBtnFill.BackColor = color; List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); if (m_SeletedAnnotation == null) return; foreach (AnnotationData annotation in m_SeletedAnnotation) { AnnotationType type = annotation.AnnotationType; if (type == AnnotationType.enumRectangle||type ==AnnotationType.enumEllipse) { foreach(AnnotationData temp in tempAllAnnotation) { if (annotation.GUID == temp.GUID) annotation.FillColor = color.ToArgb(); } } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer,EnumMetaDataType.enumAnnotation,tempAllAnnotation,true); } } private Color SelectColor() { if (dlgColor.ShowDialog() == DialogResult.OK) { return dlgColor.Color; } return Color.Transparent; } private void toolStripBtnPen_Click(object sender, EventArgs e) { Color color = SelectColor(); if (color != Color.Transparent) { toolStripBtnPen.BackColor = color; List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); if (m_SeletedAnnotation == null) return; foreach (AnnotationData annotation in m_SeletedAnnotation) { AnnotationType type = annotation.AnnotationType; if (type == AnnotationType.enumRectangle || type == AnnotationType.enumEllipse || type == AnnotationType.enumLine) { foreach (AnnotationData temp in tempAllAnnotation) { if (annotation.GUID == temp.GUID) annotation.PenColor = color.ToArgb(); } } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } } private void toolStripBtnFont_Click(object sender, EventArgs e) { Color color = SelectColor(); if (color != Color.Transparent) { toolStripBtnFont.BackColor = color; List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); if (m_SeletedAnnotation == null) return; foreach (AnnotationData annotation in m_SeletedAnnotation) { AnnotationType type = annotation.AnnotationType; if (type == AnnotationType.enumText) { foreach (AnnotationData temp in tempAllAnnotation) { if (annotation.GUID == temp.GUID) annotation.FontType.TextColor = color.ToArgb(); } } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } } private void toolStripCbxPen_TextChanged(object sender, EventArgs e) { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); foreach (AnnotationData annotation in m_SeletedAnnotation) { AnnotationType type = annotation.AnnotationType; { foreach (AnnotationData temp in tempAllAnnotation) { if (annotation.GUID == temp.GUID) annotation.PenWidth = int.Parse(toolStripCbxPen.Text); } } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } private void toolStripCbxFont_TextChanged(object sender, EventArgs e) { if (m_ImageCore != null && m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer != -1) { List<AnnotationData> tempAllAnnotation = (List<AnnotationData>)m_ImageCore.ImageBuffer.GetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation); foreach (AnnotationData annotation in m_SeletedAnnotation) { AnnotationType type = annotation.AnnotationType; if (type == AnnotationType.enumText) { for (short sIndex = 0; sIndex < tempAllAnnotation.Count; sIndex++) { if(tempAllAnnotation[sIndex].GUID == annotation.GUID) { AnnotationData temp = tempAllAnnotation[sIndex]; AnnotationData annoNew = new AnnotationData(); AnnotationData tempCopyAnnotation = new AnnotationData(); annoNew.GUID = Guid.NewGuid(); annoNew.AnnotationType = temp.AnnotationType; Point startPoint = temp.StartPoint; Point endPoint = temp.EndPoint; if (startPoint.X > endPoint.X) { int x = startPoint.X; startPoint.X = endPoint.X; endPoint.X = x; } if (startPoint.Y > endPoint.Y) { int y = startPoint.Y; startPoint.Y = endPoint.Y; endPoint.Y = y; } annoNew.StartPoint = startPoint; annoNew.EndPoint = endPoint; annoNew.FillColor = temp.FillColor; annoNew.Description = temp.Description; if (temp.FontType != null) { annoNew.FontType = new AnnoTextFont(); annoNew.FontType.Name = temp.FontType.Name; annoNew.FontType.Size = int.Parse(toolStripCbxFont.Text); annoNew.FontType.TextColor = temp.FontType.TextColor; } annoNew.Name = temp.Name; annoNew.PenColor = temp.PenColor; annoNew.PenWidth = temp.PenWidth; annoNew.Selected = temp.Selected; annoNew.TextContent = temp.TextContent; annoNew.TextRotateType = temp.TextRotateType; tempAllAnnotation.RemoveAt(sIndex); tempAllAnnotation.Insert(sIndex, annoNew); } } } } m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer, EnumMetaDataType.enumAnnotation, tempAllAnnotation, true); } } private void toolStripBtnDelete_Click(object sender, EventArgs e) { delToolStripMenuItem_Click(null, null); } private void toolStripBtnDeleteAll_Click(object sender, EventArgs e) { deleteAllToolStripMenuItem_Click(null, null); } private void toolStripBtnBringToBack_Click(object sender, EventArgs e) { sendToBackToolStripMenuItem_Click(null, null); } private void toolStripBtnBringToFront_Click(object sender, EventArgs e) { bringToFrontToolStripMenuItem_Click(null, null); } private void toolStripCbxPen_KeyPress(object sender, KeyPressEventArgs e) { byte[] array = System.Text.Encoding.Default.GetBytes(e.KeyChar.ToString()); if (!char.IsDigit(e.KeyChar) || array.LongLength == 2) e.Handled = true; if (e.KeyChar == '\b') e.Handled = false; } private void toolStripCbxFont_KeyPress(object sender, KeyPressEventArgs e) { byte[] array = System.Text.Encoding.Default.GetBytes(e.KeyChar.ToString()); if (!char.IsDigit(e.KeyChar) || array.LongLength == 2) e.Handled = true; if (e.KeyChar == '\b' || (!toolStripCbxFont.Text.Contains(".") && e.KeyChar == '.')) e.Handled = false; } private bool bIfSaveAll = false; private void saveAllToolStripMenuItem_Click(object sender, EventArgs e) { if (m_ImageCore.ImageBuffer.HowManyImagesInBuffer > 0) { SaveFileDialog filedlg = new SaveFileDialog(); filedlg.Filter = "PDF File(*.pdf)| *.pdf"; if (filedlg.ShowDialog() == DialogResult.OK) { bIfSaveAll = true; m_Creator.Save(this as ISave,filedlg.FileName); bIfSaveAll = false; } } } public object GetAnnotations(int iPageNumber) { if (!bIfSaveAll) { return m_ImageCore.ImageBuffer.GetMetaData(dsViewer1.CurrentSelectedImageIndicesInBuffer[iPageNumber], EnumMetaDataType.enumAnnotation); } else { return m_ImageCore.ImageBuffer.GetMetaData((short)iPageNumber,EnumMetaDataType.enumAnnotation); } } public Bitmap GetImage(int iPageNumber) { if (!bIfSaveAll) { return m_ImageCore.ImageBuffer.GetBitmap(dsViewer1.CurrentSelectedImageIndicesInBuffer[iPageNumber]); } else { return m_ImageCore.ImageBuffer.GetBitmap((short)iPageNumber); } } public int GetPageCount() { if (!bIfSaveAll) { return dsViewer1.CurrentSelectedImageIndicesInBuffer.Count; } else { return m_ImageCore.ImageBuffer.HowManyImagesInBuffer; } } public void LoadConvertResult(ConvertResult result) { m_ImageCore.IO.LoadImage(result.Image); if(result.Annotations!=null) m_ImageCore.ImageBuffer.SetMetaData(m_ImageCore.ImageBuffer.CurrentImageIndexInBuffer,EnumMetaDataType.enumAnnotation,result.Annotations,true); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsValidation { using Microsoft.Rest; using Microsoft.Rest.Serialization; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Test Infrastructure for AutoRest. No server backend exists for these /// tests. /// </summary> public partial class AutoRestValidationTest : ServiceClient<AutoRestValidationTest>, IAutoRestValidationTest { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Subscription ID. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Required string following pattern \d{2}-\d{2}-\d{4} /// </summary> public string ApiVersion { get; set; } /// <summary> /// Initializes a new instance of the AutoRestValidationTest class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestValidationTest(params DelegatingHandler[] handlers) : base(handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestValidationTest class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public AutoRestValidationTest(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { Initialize(); } /// <summary> /// Initializes a new instance of the AutoRestValidationTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestValidationTest(System.Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the AutoRestValidationTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public AutoRestValidationTest(System.Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { BaseUri = new System.Uri("http://localhost"); SerializationSettings = new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// Validates input parameters on the method. See swagger for details. /// </summary> /// <param name='resourceGroupName'> /// Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+. /// </param> /// <param name='id'> /// Required int multiple of 10 from 100 to 1000. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> ValidationOfMethodParametersWithHttpMessagesAsync(string resourceGroupName, int id, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 10) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 10); } if (resourceGroupName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+"); } } if (id > 1000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "id", 1000); } if (id < 100) { throw new ValidationException(ValidationRules.InclusiveMinimum, "id", 100); } if (id % 10 != 0) { throw new ValidationException(ValidationRules.MultipleOf, "id", 10); } if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } if (ApiVersion != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(ApiVersion, "\\d{2}-\\d{2}-\\d{4}")) { throw new ValidationException(ValidationRules.Pattern, "ApiVersion", "\\d{2}-\\d{2}-\\d{4}"); } } // 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("id", id); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ValidationOfMethodParameters", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "fakepath/{subscriptionId}/{resourceGroupName}/{id}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("apiVersion={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, 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> /// Validates body parameters on the method. See swagger for details. /// </summary> /// <param name='resourceGroupName'> /// Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+. /// </param> /// <param name='id'> /// Required int multiple of 10 from 100 to 1000. /// </param> /// <param name='body'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> ValidationOfBodyWithHttpMessagesAsync(string resourceGroupName, int id, Product body = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 10) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 10); } if (resourceGroupName.Length < 3) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 3); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "[a-zA-Z0-9]+")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "[a-zA-Z0-9]+"); } } if (id > 1000) { throw new ValidationException(ValidationRules.InclusiveMaximum, "id", 1000); } if (id < 100) { throw new ValidationException(ValidationRules.InclusiveMinimum, "id", 100); } if (id % 10 != 0) { throw new ValidationException(ValidationRules.MultipleOf, "id", 10); } if (body != null) { body.Validate(); } if (ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.ApiVersion"); } if (ApiVersion != null) { if (!System.Text.RegularExpressions.Regex.IsMatch(ApiVersion, "\\d{2}-\\d{2}-\\d{4}")) { throw new ValidationException(ValidationRules.Pattern, "ApiVersion", "\\d{2}-\\d{2}-\\d{4}"); } } // 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("id", id); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ValidationOfBody", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "fakepath/{subscriptionId}/{resourceGroupName}/{id}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{id}", System.Uri.EscapeDataString(SafeJsonConvert.SerializeObject(id, SerializationSettings).Trim('"'))); List<string> _queryParameters = new List<string>(); if (ApiVersion != null) { _queryParameters.Add(string.Format("apiVersion={0}", System.Uri.EscapeDataString(ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = SafeJsonConvert.DeserializeObject<Error>(_responseContent, DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, 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; } /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse> GetWithConstantInPathWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string constantParam = "constant"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("constantParam", constantParam); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetWithConstantInPath", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "validation/constantsInPath/{constantParam}/value").ToString(); _url = _url.Replace("{constantParam}", System.Uri.EscapeDataString(constantParam)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <param name='body'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<Product>> PostWithConstantInBodyWithHttpMessagesAsync(Product body = default(Product), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (body != null) { body.Validate(); } string constantParam = "constant"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("constantParam", constantParam); tracingParameters.Add("body", body); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "PostWithConstantInBody", tracingParameters); } // Construct URL var _baseUrl = BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "validation/constantsInPath/{constantParam}/value").ToString(); _url = _url.Replace("{constantParam}", System.Uri.EscapeDataString(constantParam)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(body != null) { _requestContent = SafeJsonConvert.SerializeObject(body, SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await 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 HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<Product>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<Product>(_responseContent, DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using Moq; using NuGet.Test.Mocks; using Xunit; using Xunit.Extensions; namespace NuGet.Test { public class PackageSourceProviderTest { [Fact] public void LoadPackageSourcesWhereAMigratedSourceIsAlsoADefaultSource() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("AOld", "urlA", false), new SettingValue("userDefinedSource", "userDefinedSourceUrl", false) }); settings.Setup(s => s.GetSettingValues("disabledPackageSources", false)).Returns( new SettingValue[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var defaultPackageSourceA = new PackageSource("urlA", "ANew"); var defaultPackageSourceB = new PackageSource("urlB", "B"); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new[] { defaultPackageSourceA, defaultPackageSourceB }, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("urlA", "AOld"), defaultPackageSourceA }, }); // Act var values = provider.LoadPackageSources().ToList(); // Assert // Package Source AOld will be migrated to ANew. B will simply get added // Since default source B got added when there are other package sources it will be disabled // However, package source ANew must stay enabled // PackageSource userDefinedSource is a user package source and is untouched Assert.Equal(3, values.Count); Assert.Equal("urlA", values[0].Source); Assert.Equal("ANew", values[0].Name); Assert.True(values[0].IsEnabled); Assert.Equal("userDefinedSourceUrl", values[1].Source); Assert.Equal("userDefinedSource", values[1].Name); Assert.True(values[1].IsEnabled); Assert.Equal("urlB", values[2].Source); Assert.Equal("B", values[2].Name); Assert.False(values[2].IsEnabled); } [Fact] public void TestNoPackageSourcesAreReturnedIfUserSettingsIsEmpty() { // Arrange var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", false), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }) .Verifiable(); settings.Setup(s => s.GetSettingValues("disabledPackageSources", false)).Returns(new SettingValue[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); // Arrange var provider = CreatePackageSourceProvider(); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(0, values.Count); } [Fact] public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsNull() { // Arrange var settings = new Mock<ISettings>(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null); // Act var values = provider.LoadPackageSources(); // Assert Assert.False(values.Any()); } [Fact] public void LoadPackageSourcesReturnsEmptySequenceIfDefaultPackageSourceIsEmpty() { // Arrange var settings = new Mock<ISettings>(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: new PackageSource[] { }); // Act var values = provider.LoadPackageSources(); // Assert Assert.False(values.Any()); } [Fact] public void LoadPackageSourcesReturnsDefaultSourcesIfSpecified() { // Arrange var settings = new Mock<ISettings>().Object; var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("A"), new PackageSource("B") }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); Assert.Equal("A", values.First().Source); Assert.Equal("B", values.Last().Source); } [Fact] public void LoadPackageSourcesPerformMigrationIfSpecified() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)).Returns( new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false), } ); // disable package "three" settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("three", "true" ) }); IList<KeyValuePair<string, string>> savedSettingValues = null; settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback<string, IList<KeyValuePair<string, string>>>((_, savedVals) => { savedSettingValues = savedVals; }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object, null, new Dictionary<PackageSource, PackageSource> { { new PackageSource("onesource", "one"), new PackageSource("goodsource", "good") }, { new PackageSource("foo", "bar"), new PackageSource("foo", "bar") }, { new PackageSource("threesource", "three"), new PackageSource("awesomesource", "awesome") } } ); // Act var values = provider.LoadPackageSources().ToList(); savedSettingValues = savedSettingValues.ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "good", "goodsource", true); AssertPackageSource(values[1], "two", "twosource", true); AssertPackageSource(values[2], "awesome", "awesomesource", false); Assert.Equal(3, savedSettingValues.Count); Assert.Equal("good", savedSettingValues[0].Key); Assert.Equal("goodsource", savedSettingValues[0].Value); Assert.Equal("two", savedSettingValues[1].Key); Assert.Equal("twosource", savedSettingValues[1].Value); Assert.Equal("awesome", savedSettingValues[2].Key); Assert.Equal("awesomesource", savedSettingValues[2].Value); } [Fact] public void CallSaveMethodAndLoadMethodShouldReturnTheSamePackageSet() { // Arrange var expectedSources = new[] { new PackageSource("one", "one"), new PackageSource("two", "two"), new PackageSource("three", "three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", false), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Empty(values); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act var sources = provider.LoadPackageSources().ToList(); provider.SavePackageSources(sources); // Assert settings.Verify(); Assert.Equal(3, sources.Count); for (int i = 0; i < sources.Count; i++) { AssertPackageSource(expectedSources[i], sources[i].Name, sources[i].Source, true); } } [Fact] public void WithMachineWideSources() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "one", true), new SettingValue("two", "two", false), new SettingValue("three", "three", false) }); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { // verifies that only sources "two" and "three" are passed. // the machine wide source "one" is not. Assert.Equal(2, values.Count); Assert.Equal("two", values[0].Key); Assert.Equal("two", values[0].Value); Assert.Equal("three", values[1].Key); Assert.Equal("three", values[1].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { // verifies that the machine wide source "one" is passed here // since it is disabled. Assert.Equal(1, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("true", values[0].Value); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act var sources = provider.LoadPackageSources().ToList(); // disable the machine wide source "one", and save the result in provider. Assert.Equal("one", sources[2].Name); sources[2].IsEnabled = false; provider.SavePackageSources(sources); // Assert // all assertions are done inside Callback()'s } [Fact] public void LoadPackageSourcesReturnCorrectDataFromSettings() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", true), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }) .Verifiable(); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "two", "twosource", true); AssertPackageSource(values[1], "three", "threesource", true); AssertPackageSource(values[2], "one", "onesource", true, true); } [Fact] public void LoadPackageSourcesReturnCorrectDataFromSettingsWhenSomePackageSourceIsDisabled() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("two", "true") }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[0], "one", "onesource", true); AssertPackageSource(values[1], "two", "twosource", false); AssertPackageSource(values[2], "three", "threesource", true); } /// <summary> /// The following test tests case 1 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 1. Default Package Source is already present matching both feed source and the feed name /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameAndSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false)}); // Disable package source one settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new[] { new KeyValuePair<string, string>("one", "true") }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='one' value='onesource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'one' represents case 1. No real change takes place. IsOfficial will become true though. IsEnabled remains false as it is ISettings AssertPackageSource(values.First(), "one", "onesource", false, false, true); } /// <summary> /// The following test tests case 2 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 2. Default Package Source is already present matching feed source but with a different feed name. DO NOTHING /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInSourceButNotInName() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("two", "twosource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='twodefault' value='twosource' /> </packageSources> <disabledPackageSources> <add key='twodefault' value='true' /> </disabledPackageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'two' represents case 2. No Change effected. The existing feed will not be official AssertPackageSource(values.First(), "two", "twosource", true, false, false); } /// <summary> /// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 3. Default Package Source is not present, but there is another feed source with the same feed name. Override that feed entirely /// </summary> [Fact] public void LoadPackageSourcesWhereALoadedSourceMatchesDefaultSourceInNameButNotInSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='three' value='threedefaultsource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'three' represents case 3. Completely overwritten. Noticeably, Feed Source will match Configuration Default settings AssertPackageSource(values.First(), "three", "threedefaultsource", true, false, true); } /// <summary> /// The following test tests case 3 listed in PackageSourceProvider.SetDefaultPackageSources(...) /// Case 4. Default Package Source is not present, simply, add it /// </summary> [Fact] public void LoadPackageSourcesWhereNoLoadedSourceMatchesADefaultSource() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>()); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='four' value='foursource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(1, values.Count()); // Package source 'four' represents case 4. Simply Added to the list increasing the count by 1. ISettings only has 3 package sources. But, LoadPackageSources returns 4 AssertPackageSource(values.First(), "four", "foursource", true, false, true); } [Fact] public void LoadPackageSourcesDoesNotReturnProviderDefaultsWhenConfigurationDefaultPackageSourcesIsNotEmpty() { // Arrange var settings = new Mock<ISettings>().Object; string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='configurationDefaultOne' value='configurationDefaultOneSource' /> <add key='configurationDefaultTwo' value='configurationDefaultTwoSource' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings, providerDefaultSources: new[] { new PackageSource("providerDefaultA"), new PackageSource("providerDefaultB") }, migratePackageSources: null, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources(); // Assert Assert.Equal(2, values.Count()); Assert.Equal("configurationDefaultOneSource", values.First().Source); Assert.Equal("configurationDefaultTwoSource", values.Last().Source); } [Fact] public void LoadPackageSourcesAddsAConfigurationDefaultBackEvenAfterMigration() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); string configurationDefaultsFileContent = @" <configuration> <packageSources> <add key='NuGet official package source' value='https://nuget.org/api/v2' /> </packageSources> </configuration>"; var mockFileSystem = new MockFileSystem(); var configurationDefaultsPath = "NuGetDefaults.config"; mockFileSystem.AddFile(configurationDefaultsPath, configurationDefaultsFileContent); ConfigurationDefaults configurationDefaults = new ConfigurationDefaults(mockFileSystem, configurationDefaultsPath); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }, configurationDefaultSources: configurationDefaults.DefaultPackageSources); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); Assert.Equal("NuGet official package source", values[1].Name); Assert.Equal("https://nuget.org/api/v2", values[1].Source); } [Fact] public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigration() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false), new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(1, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); } [Fact] public void LoadPackageSourcesDoesNotDuplicateFeedsOnMigrationAndSavesIt() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new List<SettingValue>() { new SettingValue("NuGet official package source", "https://nuget.org/api/v2", false), new SettingValue("nuget.org", "https://www.nuget.org/api/v2", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", It.IsAny<string>())).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.GetValues("disabledPackageSources")).Returns(new KeyValuePair<string, string>[0]); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> valuePairs) => { Assert.Equal(1, valuePairs.Count); Assert.Equal("nuget.org", valuePairs[0].Key); Assert.Equal("https://www.nuget.org/api/v2", valuePairs[0].Value); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object, providerDefaultSources: null, migratePackageSources: new Dictionary<PackageSource, PackageSource> { { new PackageSource("https://nuget.org/api/v2", "NuGet official package source"), new PackageSource("https://www.nuget.org/api/v2", "nuget.org") } }); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(1, values.Count); Assert.Equal("nuget.org", values[0].Name); Assert.Equal("https://www.nuget.org/api/v2", values[0].Source); settings.Verify(); } [Fact] public void DisablePackageSourceAddEntryToSettings() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.SetValue("disabledPackageSources", "A", "true")).Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.DisablePackageSource(new PackageSource("source", "A")); // Assert settings.Verify(); } [Fact] public void IsPackageSourceEnabledReturnsFalseIfTheSourceIsDisabled() { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns("sdfds"); var provider = CreatePackageSourceProvider(settings.Object); // Act bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A")); // Assert Assert.False(isEnabled); } [Theory] [InlineData((string)null)] [InlineData("")] public void IsPackageSourceEnabledReturnsTrueIfTheSourceIsNotDisabled(string returnValue) { // Arrange var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.GetValue("disabledPackageSources", "A")).Returns(returnValue); var provider = CreatePackageSourceProvider(settings.Object); // Act bool isEnabled = provider.IsPackageSourceEnabled(new PackageSource("source", "A")); // Assert Assert.True(isEnabled); } [Theory] [InlineData(new object[] { null, "abcd" })] [InlineData(new object[] { "", "abcd" })] [InlineData(new object[] { "abcd", null })] [InlineData(new object[] { "abcd", "" })] public void LoadPackageSourcesIgnoresInvalidCredentialPairsFromSettings(string userName, string password) { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new [] { new KeyValuePair<string, string>("Username", userName), new KeyValuePair<string, string>("Password", password) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Null(values[1].UserName); Assert.Null(values[1].Password); } [Fact] public void LoadPackageSourcesReadsCredentialPairsFromSettings() { // Arrange string encryptedPassword = EncryptionUtility.EncryptString("topsecret"); var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("Password", encryptedPassword) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("user1", values[1].UserName); Assert.Equal("topsecret", values[1].Password); Assert.False(values[1].IsPasswordClearText); } [Fact] public void LoadPackageSourcesReadsClearTextCredentialPairsFromSettings() { // Arrange const string clearTextPassword = "topsecret"; var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "user1"), new KeyValuePair<string, string>("ClearTextPassword", clearTextPassword) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("user1", values[1].UserName); Assert.True(values[1].IsPasswordClearText); Assert.Equal("topsecret", values[1].Password); } [Theory] [InlineData("Username=john;Password=johnspassword")] [InlineData("uSerName=john;PASSWOrD=johnspassword")] [InlineData(" Username=john; Password=johnspassword ")] public void LoadPackageSourcesLoadsCredentialPairsFromEnvironmentVariables(string rawCredentials) { // Arrange const string userName = "john"; const string password = "johnspassword"; var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns(rawCredentials); var provider = CreatePackageSourceProvider(settings.Object, environment:environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal(userName, values[1].UserName); Assert.Equal(password, values[1].Password); } [Theory] [InlineData("uername=john;Password=johnspassword")] [InlineData(".Username=john;Password=johnspasswordf")] [InlineData("What is this I don't even")] public void LoadPackageSourcesIgnoresMalformedCredentialPairsFromEnvironmentVariables(string rawCredentials) { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns(rawCredentials); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Null(values[1].UserName); Assert.Null(values[1].Password); } [Fact] public void LoadPackageSourcesEnvironmentCredentialsTakePrecedenceOverSettingsCredentials() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns("Username=envirouser;Password=enviropassword"); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("envirouser", values[1].UserName); Assert.Equal("enviropassword", values[1].Password); } [Fact] public void LoadPackageSourcesWhenEnvironmentCredentialsAreMalformedFallsbackToSettingsCredentials() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("three", "threesource", false) }); settings.Setup(s => s.GetNestedValues("packageSourceCredentials", "two")) .Returns(new[] { new KeyValuePair<string, string>("Username", "settinguser"), new KeyValuePair<string, string>("ClearTextPassword", "settingpassword") }); var environment = new Mock<IEnvironmentVariableReader>(); environment.Setup(e => e.GetEnvironmentVariable("NuGetPackageSourceCredentials_two")) .Returns("I for one don't understand environment variables"); var provider = CreatePackageSourceProvider(settings.Object, environment: environment.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(3, values.Count); AssertPackageSource(values[1], "two", "twosource", true); Assert.Equal("settinguser", values[1].UserName); Assert.Equal("settingpassword", values[1].Password); } // Test that when there are duplicate sources, i.e. sources with the same name, // then the source specified in one Settings with the highest priority is used. [Fact] public void DuplicatePackageSources() { // Arrange var settings = new Mock<ISettings>(); settings.Setup(s => s.GetSettingValues("packageSources", true)) .Returns(new[] { new SettingValue("one", "onesource", false), new SettingValue("two", "twosource", false), new SettingValue("one", "threesource", false) }); var provider = CreatePackageSourceProvider(settings.Object); // Act var values = provider.LoadPackageSources().ToList(); // Assert Assert.Equal(2, values.Count); AssertPackageSource(values[0], "two", "twosource", true); AssertPackageSource(values[1], "one", "threesource", true); } [Fact] public void SavePackageSourcesSaveCorrectDataToSettings() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("two"), new PackageSource("three") }; var settings = new Mock<ISettings>(MockBehavior.Strict); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("packageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(3, values.Count); Assert.Equal("one", values[0].Key); Assert.Equal("one", values[0].Value); Assert.Equal("two", values[1].Key); Assert.Equal("two", values[1].Value); Assert.Equal("three", values[2].Key); Assert.Equal("three", values[2].Value); }) .Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Empty(values); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSaveCorrectDataToSettingsWhenSomePackageSourceIsDisabled() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("two", "two", isEnabled: false), new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("disabledPackageSources")).Returns(true).Verifiable(); settings.Setup(s => s.SetValues("disabledPackageSources", It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, IList<KeyValuePair<string, string>> values) => { Assert.Equal(1, values.Count); Assert.Equal("two", values[0].Key); Assert.Equal("true", values[0].Value, StringComparer.OrdinalIgnoreCase); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSavesCredentials() { // Arrange var entropyBytes = Encoding.UTF8.GetBytes("NuGet"); var sources = new[] { new PackageSource("one"), new PackageSource("twosource", "twoname") { UserName = "User", Password = "password" }, new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, string key, IList<KeyValuePair<string, string>> values) => { Assert.Equal("twoname", key); Assert.Equal(2, values.Count); AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]); Assert.Equal("Password", values[1].Key); string decryptedPassword = Encoding.UTF8.GetString( ProtectedData.Unprotect(Convert.FromBase64String(values[1].Value), entropyBytes, DataProtectionScope.CurrentUser)); Assert.Equal("Password", values[1].Key); Assert.Equal("password", decryptedPassword); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void SavePackageSourcesSavesClearTextCredentials() { // Arrange var sources = new[] { new PackageSource("one"), new PackageSource("twosource", "twoname") { UserName = "User", Password = "password", IsPasswordClearText = true}, new PackageSource("three") }; var settings = new Mock<ISettings>(); settings.Setup(s => s.DeleteSection("packageSources")).Returns(true).Verifiable(); settings.Setup(s => s.DeleteSection("packageSourceCredentials")).Returns(true).Verifiable(); settings.Setup(s => s.SetNestedValues("packageSourceCredentials", It.IsAny<string>(), It.IsAny<IList<KeyValuePair<string, string>>>())) .Callback((string section, string key, IList<KeyValuePair<string, string>> values) => { Assert.Equal("twoname", key); Assert.Equal(2, values.Count); AssertKVP(new KeyValuePair<string, string>("Username", "User"), values[0]); AssertKVP(new KeyValuePair<string, string>("ClearTextPassword", "password"), values[1]); }) .Verifiable(); var provider = CreatePackageSourceProvider(settings.Object); // Act provider.SavePackageSources(sources); // Assert settings.Verify(); } [Fact] public void GetAggregateReturnsAggregateRepositoryForAllSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryB = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false); // Assert Assert.Equal(2, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); Assert.Equal(repositoryB.Object, repo.Repositories.Last()); } [Fact] public void GetAggregateSkipsInvalidSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryC = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException()); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: true); // Assert Assert.Equal(2, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); Assert.Equal(repositoryC.Object, repo.Repositories.Last()); } [Fact] public void GetAggregateSkipsDisabledSources() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryB = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Returns(repositoryB.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Throws(new Exception()); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B", "B", isEnabled: false), new PackageSource("C", "C", isEnabled: false) }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false); // Assert Assert.Equal(1, repo.Repositories.Count()); Assert.Equal(repositoryA.Object, repo.Repositories.First()); } [Fact] public void GetAggregateHandlesInvalidUriSources() { // Arrange var factory = PackageRepositoryFactory.Default; var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("Bad 1"), new PackageSource(@"x:sjdkfjhsdjhfgjdsgjglhjk"), new PackageSource(@"http:\\//") }); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory, ignoreFailingRepositories: true); // Assert Assert.False(repo.Repositories.Any()); } [Fact] public void GetAggregateSetsIgnoreInvalidRepositoryProperty() { // Arrange var factory = new Mock<IPackageRepositoryFactory>(); bool ignoreRepository = true; var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(Enumerable.Empty<PackageSource>()); // Act var repo = (AggregateRepository)sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: ignoreRepository); // Assert Assert.True(repo.IgnoreFailingRepositories); } [Fact] public void GetAggregateWithInvalidSourcesThrows() { // Arrange var repositoryA = new Mock<IPackageRepository>(); var repositoryC = new Mock<IPackageRepository>(); var factory = new Mock<IPackageRepositoryFactory>(); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("A")))).Returns(repositoryA.Object); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("B")))).Throws(new InvalidOperationException()); factory.Setup(c => c.CreateRepository(It.Is<string>(a => a.Equals("C")))).Returns(repositoryC.Object); var sources = new Mock<IPackageSourceProvider>(); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { new PackageSource("A"), new PackageSource("B"), new PackageSource("C") }); // Act and Assert ExceptionAssert.Throws<InvalidOperationException>(() => sources.Object.CreateAggregateRepository(factory.Object, ignoreFailingRepositories: false)); } [Fact] public void ResolveSourceLooksUpNameAndSource() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz"); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 }); // Act var result1 = sources.Object.ResolveSource("http://www.test.com"); var result2 = sources.Object.ResolveSource("Baz"); var result3 = sources.Object.ResolveSource("SourceName"); // Assert Assert.Equal(source2.Source, result1); Assert.Equal(source2.Source, result2); Assert.Equal(source1.Source, result3); } [Fact] public void ResolveSourceIgnoreDisabledSources() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"); PackageSource source2 = new PackageSource("http://www.test.com", "Baz", isEnabled: false); PackageSource source3 = new PackageSource("http://www.bing.com", "Foo", isEnabled: false); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2, source3 }); // Act var result1 = sources.Object.ResolveSource("http://www.test.com"); var result2 = sources.Object.ResolveSource("Baz"); var result3 = sources.Object.ResolveSource("Foo"); var result4 = sources.Object.ResolveSource("SourceName"); // Assert Assert.Equal("http://www.test.com", result1); Assert.Equal("Baz", result2); Assert.Equal("Foo", result3); Assert.Equal("Source", result4); } [Fact] public void ResolveSourceReturnsOriginalValueIfNotFoundInSources() { // Arrange var sources = new Mock<IPackageSourceProvider>(); PackageSource source1 = new PackageSource("Source", "SourceName"), source2 = new PackageSource("http://www.test.com", "Baz"); sources.Setup(c => c.LoadPackageSources()).Returns(new[] { source1, source2 }); var source = "http://www.does-not-exist.com"; // Act var result = sources.Object.ResolveSource(source); // Assert Assert.Equal(source, result); } private void AssertPackageSource(PackageSource ps, string name, string source, bool isEnabled, bool isMachineWide = false, bool isOfficial = false) { Assert.Equal(name, ps.Name); Assert.Equal(source, ps.Source); Assert.True(ps.IsEnabled == isEnabled); Assert.True(ps.IsMachineWide == isMachineWide); Assert.True(ps.IsOfficial == isOfficial); } private IPackageSourceProvider CreatePackageSourceProvider( ISettings settings = null, IEnumerable<PackageSource> providerDefaultSources = null, IDictionary<PackageSource, PackageSource> migratePackageSources = null, IEnumerable<PackageSource> configurationDefaultSources = null, IEnvironmentVariableReader environment = null) { settings = settings ?? new Mock<ISettings>().Object; environment = environment ?? new Mock<IEnvironmentVariableReader>().Object; return new PackageSourceProvider(settings, providerDefaultSources, migratePackageSources, configurationDefaultSources, environment); } private static void AssertKVP(KeyValuePair<string, string> expected, KeyValuePair<string, string> actual) { Assert.Equal(expected.Key, actual.Key); Assert.Equal(expected.Value, actual.Value); } } }
/* Solar Recharge Platform (SRP) Copyright 2015 Nick West Released under CC0 1.0 Universal (Public Domain) ^ This licenses lets you do pretty much whatever you want with the below code without credit or anything Purpose: Automated alignment of Solar Recharge Platform (SRP for short, which is basically any ship with solar panels) with sun for optimal power production. Also includes battery management with automated charging of batteries that are docked to the SRP. Works on both large and small ships, can be used on satelites/antenna relays/probes/etc. Solar Alignment Ship self aligns to point solar panels toward the sun Averages the power across multiple solar panels when aligning for optimization Uses all Gyros on the ship to make the alignment (Requires Gyros set to "overide" for auto-alignment to work) Adjustable minimum value for power (Large solar panel max of 120 kW, default set to 118 kW, small solar panel max out of 22 kW, default is set to 20.5). Adjustable turn speed (higher numbers mean faster turns but also lower accuracy for alignment, if speed is high keep min val lower). Battery management: Batteries that are attached to the SRP will be used to suppliment solar power when charging docked Batteries for maximum charging speed Any battery on a ship that docks with the SRP will be set to recharge or off upon docking (optional with config below) All docked batteries will fully charge and have charging priority over SRP batteries When all docked batteries are charged, or there is extra solar power, SRP batteries will be set to recharge automatically (but only if the solar array is optimal) Battery management can be turned off with a config option below Required for alignment: 1 or more Gyroscopes (TODO??if multiple gyros they all have to be facing the same way??) 1 or more Solar Panels 1 Programmable Block 1 Timer Block * Set for 2 seconds (you can play with different interval speeds, 2 works well though) * Have it run the Programmable Block and start its own timer. (to make the program loop) Optional: 1 or more batteries on the station 1 or more batteries docked to the station (via a connector, piston, or rotor) * Merged blocks show up as being owned by the main grid, whereas docked blocks show as being seperate * Blocks attached via landing gear only will not show on the grid and cannot have their batteries charged Instructions for use: 1. You must own all parts (solar panels, gyros, batteries, programmable block, timer, etc). 2. Install the script onto your programmable block 3. Customize the Custom Variables below (read notes next to them for more info) 4. Set the following actions to the timer block a. Run programmable block b. start timer on this timer block 5. (optional, but recommended) Position your array so it's pointed toward the sun rather than away it depending on ship config, it could get stuck faced away from the sun if it doesn't start facing it 6. Set all gyros to "overide" (unless you changed automaticGyroControl to true, then this step is not necessary) 7. Bask in the glory as your Solar Recharge Platform moves to face the sun, and your power generation reaches peak values and sustains them. Notes: I recommend leaving the autoGyroOverride set to false and then manually toggling your gyros from override to not. This leaves you in control of when the ship will be controllable and not. Otherwise you have to stop the timer to take contorl of the ship All solar panels should point the same way OR adjust the minPwr variable lower to compensate since it's impossible to get all panels at 98% if they can't all face the sun at once No custom names for blocks are needed, and this script will not rename any of your blocks :) If you're not running the game in English, locate the regex strings (not far below) and adjust them to match your language (I'll look for a better way to do this) Credit: This script was inspired by Kir's "Self-Aligning Solar Panels For Ships With Gyros" script Found here: http://steamcommunity.com/sharedfiles/filedetails/?id=369286464 Thanks to Me 10 Jin's regex example for extracting detailed data from solar panels and batteries Found here: http://forum.keenswh.com/threads/regular-expressions-example-reactor-usage.7226038/ */ //*********************************************************************************************************************************** //**************************************************** Custom Variables ************************************************************* //*********************************************************************************************************************************** // TODO: Auto detect if possible const string shipType = "large"; // Can be "large" or "small", used to calculate solar power efficiency (small panels have a different max output) const double minPwrPercent = 98; // Minimum power percentage [Note: going over 100% will make the SRP constantly seek the sun. Similarly any percent close to 100 could result in constant seeking if percentage is not achievable with Solar Panel Configuration] const float turnSpeed = 2.5f; // Turn speed of craft, slower means more precision, you can adjust timer block to faster tick if you set this to be faster /******************************** * INFO ABOUT SELECTING CONTROLS: * - For optimal alignment speed you don't want your solar panels to spin flat * For bottom/top facing solar panels - Roll + Pitch should be used * For front/back facing solar panels - Pitch + Yaw should be used * Fot right/left facing solar panels - Roll + Yaw should be used ********************************/ const string control1 = "Roll"; // First control to use on the Gyro to position const string control2 = "Pitch"; // Second control to use on the Gyro to position const bool autoGyroOverride = false; // When set to true, the script will turn all gyros to override automatically while aligning to the sun // It will also then release the override when alignment is optimal (restoring pilot control of gyros) // The alternate to this is to manually control the overide (leave it on, except when you want to "drive") <- I prefer this way const bool batteryManagement = true; // If this is set to false, battery management won't happen, but Gyro positioning still will const bool chargeDockedBatteries = true; // If batteryManagement is set to false, this does nothing. Otherwise it allows this script to manage docked batteries as well (useful for SRPs) const bool keepBatteriesOn = true; // Keep batteries on and discharging except when solar is full power [Note: recommended to prevent complete power failures] //*********************************************************************************************************************************** //********************************************** Shouldn't need to edit below here but might **************************************** //*********************************************************************************************************************************** //-- Constants & Debug flags // Don't change these unless a game update changes them (Watts) //TODO: Verify these values and/or get them automatically const int smallBatteryMax = 4320000; const int largeBatteryMax = 12000000; const int smallSolarPanelMax = 30000; const int largeSolarPanelMax = 120000; // Flipping these to true will Echo out various debug info (I didn't bother to pull this out, but you'll have to look at code to see what it's echoing exactly) bool debugMain = false; bool debugAlignment = false; bool debugBat = false; //-- These probably need to be adjusted based on localization (just change the English words to whatever matches the language you're using) // TODO: Fix localization issues with these Regex patterns. Instead, assume positions based on line // Example: someBlock.DetailedInfo.Split(new string[] { "\r\n", "\n", "\r" }, StringSplitOptions.None); // regex to get max and current output from solar panel details System.Text.RegularExpressions.Regex solarPwrRegex = new System.Text.RegularExpressions.Regex( "Max Output: (\\d+\\.?\\d*) (\\w?)W.*Current Output: (\\d+\\.?\\d*) (\\w?)W", System.Text.RegularExpressions.RegexOptions.Singleline ); // regex to get power data from battery details. System.Text.RegularExpressions.Regex batteryRegex = new System.Text.RegularExpressions.Regex( "Max Output: (\\d+\\.?\\d*) (\\w?)W.*Max Required Input: (\\d+\\.?\\d*) (\\w?)W.*Max Stored Power: (\\d+\\.?\\d*) (\\w?)Wh.*Current Input: (\\d+\\.?\\d*) (\\w?)W.*Current Output: (\\d+\\.?\\d*) (\\w?)W.*Stored power: (\\d+\\.?\\d*) (\\w?)Wh", System.Text.RegularExpressions.RegexOptions.Singleline ); // Global variables until this all becomes a class List<IMyTerminalBlock> srpSolarBlocks = null; // Local grid only List<IMyTerminalBlock> srpGyroBlocks = null; // Local grid only List<IMyTerminalBlock> srpBatteryBlocks = null; // Local grid only List<IMyTerminalBlock> dockedBatteryBlocks = null; // Non-Local grid only IMyProgrammableBlock thisProgrammableBlock = null; // This programmable block (used for identifying local grid) double currentPwr; // Stores the current power generated by the solar panel double lastPwr; // Stores the power generated by the solar panel at the previous alignment double highestPwr = 0; // Stores highest power value double minPwr; // Minimum acceptable power (based on percentage & ship type defined above) /** * Entry point of script * * @return void */ void Main() { // Get the ProgrammableBlock this is running on thisProgrammableBlock = getSelf(); // Instantiate Lists srpSolarBlocks = new List<IMyTerminalBlock>(); srpGyroBlocks = new List<IMyTerminalBlock>(); srpBatteryBlocks = new List<IMyTerminalBlock>(); dockedBatteryBlocks = new List<IMyTerminalBlock>(); // Populate Lists GridTerminalSystem.GetBlocksOfType<IMySolarPanel>(srpSolarBlocks, filterSRPSolarPanels); // Find all the SRP solar panels GridTerminalSystem.GetBlocksOfType<IMyGyro>(srpGyroBlocks, filterSRPGyros); // Find all the SRP gyros GridTerminalSystem.GetBlocksOfType<IMyBatteryBlock>(srpBatteryBlocks, filterSRPBatteries); // Find all the SRP batteries GridTerminalSystem.GetBlocksOfType<IMyBatteryBlock>(dockedBatteryBlocks, filterDockedBatteries);// Find all the docked batteries // If there aren't Gyros, we can't position, so throw an exception if(srpGyroBlocks.Count <= 0){ throw new System.ArgumentException("No Gyros Found, Cannot Position!", "CAT"); } // Calculate the minimum solar panel output we'll accept minPwr = minPwrPercent / 100 * (shipType == "large" ? largeSolarPanelMax : smallSolarPanelMax) / 1000; // KW // Check if Solar panels exist (if not, we can't align them) if (srpSolarBlocks.Count > 0) { // Get current average power across all solar panels double totalPanelPwr = 0; double countPanels = 0; for (int i = 0; i < srpSolarBlocks.Count ; i++ ){ countPanels++; System.Text.RegularExpressions.Match match = solarPwrRegex.Match(srpSolarBlocks[i].DetailedInfo); double n; if(match.Success ){ // Max output of the solar panel if(double.TryParse( match.Groups[1].Value, out n )){ totalPanelPwr += n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf( match.Groups[2].Value)); } } } // Set the current average power generated by the panels currentPwr = totalPanelPwr / countPanels / 1000; // KW myDebug("Min="+minPwr.ToString(), debugAlignment); myDebug("Curr="+currentPwr.ToString(), debugMain); // Align the solar array AlignSolar(); }else{ throw new System.ArgumentException("No Solar Panels Found", "CAT"); } // Manage the batteries if that option is seleted if(batteryManagement){ manageBatteries(); } } /** * Align the solar array using gyros * TODO: Make it so this can flip 180 when it's stuck with the wrong side facing the sun * * @return void */ void AlignSolar(){ // Set the GyroState variables setGyroState(control1); setGyroState(control2); // Get the last and highest power from storage lastPwr = getVar("currentPower"); highestPwr = getVar("highestPower"); myDebug("Last="+lastPwr.ToString(), debugAlignment); myDebug("High="+highestPwr.ToString(), debugAlignment); // Make sure only one Gyro control is set to move and that all gyros are functioning the same way if(!verifyGyros()){ myDebug("Reset Gyros", debugAlignment); // Stop moving zeroGyros(); // Clear last and highest vars saveVars(0,0); return; } // If we hit optimal power then just stay put. if(currentPwr >= minPwr){ myDebug("SUCCESS", debugAlignment); // Stop moving zeroGyros(); // Clear last and highest vars saveVars(0,0); // Return Gyro control (if we're doing that sort of thing) if(autoGyroOverride){ overrideGyros(false); } return; }else{ // Always set the currentPower to Storage (this will be lastPwr next tick) saveVar("currentPower", currentPwr); // Take control of Gyros (if we're doing that) if(autoGyroOverride){ overrideGyros(true); } // Not moving, power is not optimal if(getGyroState(control1) == 0 & getGyroState(control2) == 0){ myDebug("Just Starting (0)", debugAlignment); // Zero out highest Power saveVar("highestPower", 0); // Make sure the gyros reflect the known state zeroGyros(); // Start moving in the first direction GyroRotation(control1, 1); return; } // Control 1 was active else if(getGyroState(control1) != 0){ if(highestPwr == 0 & lastPwr == 0){ // This condition shouldn't really ever be met myDebug("Start Going (1)", debugAlignment); return; } else if(highestPwr == 0 & currentPwr < lastPwr){ myDebug("Reverse direction (1)", debugAlignment); GyroRotation(control1, -1 * getGyroState(control1)); return; } else if(currentPwr >= lastPwr){ myDebug("Keep Going (1)", debugAlignment); // Save highest power highestPwr = currentPwr; saveVar("highestPower", highestPwr); return; } else{ myDebug("Switch to (2)", debugAlignment); GyroRotation(control1, 0); GyroRotation(control2, 1); // Clear last and highest vars saveVars(0,0); return; } } // Control 2 was active else if(getGyroState(control2) != 0){ if(highestPwr == 0 & lastPwr == 0){ myDebug("Start Going (2)", debugAlignment); return; } else if(highestPwr == 0 & currentPwr < lastPwr){ myDebug("Reverse direction (2)", debugAlignment); GyroRotation(control2, -1 * getGyroState(control2)); return; } else if(currentPwr >= lastPwr){ myDebug("Keep Going (2)", debugAlignment); // Save highest power highestPwr = currentPwr; saveVar("highestPower", highestPwr); return; } else{ myDebug("Switch to (1)", debugAlignment); GyroRotation(control2, 0); GyroRotation(control1, 1); // Clear last and highest vars saveVars(0,0); return; } } } } /** * Set the gyro state based on the values in the first gyro found in gyroBlocks * * control = ["Yaw" | "Pitch | "Roll"] * * @param string control * @return void */ void setGyroState(string control){ // Pick one of the gyros to look at IMyGyro gyroBlock = srpGyroBlocks[0] as IMyGyro; switch(control){ case "Yaw": yaw_state = gyroBlock.Yaw == 0 ? 0 : gyroBlock.Yaw > 0 ? 1 : -1; break; case "Roll": roll_state = gyroBlock.Roll == 0 ? 0 : gyroBlock.Roll > 0 ? 1 : -1; break; case "Pitch": pitch_state = gyroBlock.Pitch == 0 ? 0 : gyroBlock.Pitch > 0 ? 1 : -1; break; } } /** * Set all the gyro controls to 0 so we start fresh * * @return void */ void zeroGyros(){ GyroRotation("Yaw", 0); GyroRotation("Roll", 0); GyroRotation("Pitch", 0); } /** * Check all gyros, if there are conflicting controls set, or more than 1 return false * * @return bool */ bool verifyGyros(){ IMyGyro tmpGyro; string type = ""; float val = 0; for ( int i = 0; i < srpGyroBlocks.Count ; i++ ){ tmpGyro = srpGyroBlocks[i] as IMyGyro; if(tmpGyro.Yaw != 0){ if(type != "" & type != "Yaw"){ return false; }else{ if(val != 0 & tmpGyro.Yaw != val){ return false; } type = "Yaw"; val = tmpGyro.Yaw; } } if(tmpGyro.Pitch != 0){ if(type != "" & type != "Pitch"){ return false; }else{ if(val != 0 & tmpGyro.Pitch != val){ return false; } type = "Pitch"; val = tmpGyro.Pitch; } } if(tmpGyro.Roll != 0){ if(type != "" & type != "Roll"){ return false; }else{ if(val != 0 & tmpGyro.Roll != val){ return false; } type = "Roll"; val = tmpGyro.Roll; } } } return true; } /** * Set override on all gyros * * @param bool setOverride * @return void */ void overrideGyros(bool setOverride){ IMyGyro tmpGyro; for ( int i = 0; i < srpGyroBlocks.Count ; i++ ){ tmpGyro = srpGyroBlocks[i] as IMyGyro; if((!tmpGyro.GyroOverride & setOverride) | (tmpGyro.GyroOverride & !setOverride)){ tmpGyro.GetActionWithName("Override").Apply(tmpGyro); } } } /** * Get the gyro state based on the state variables * * control = ["Yaw" | "Pitch | "Roll"] * * @param string control * @return int */ int getGyroState(string control){ switch(control){ case "Yaw": return yaw_state; break; case "Roll": return roll_state; break; case "Pitch": return pitch_state; break; default: throw new System.ArgumentException("Invalid control in config (must be proper case)", "CAT"); break; } return 0; } // More globals because this isn't encapsulated int yaw_state = 0; int pitch_state = 0; int roll_state = 0; /** * Set all gyros to on the given rotation control (rotation) at the given speed (val) * * rotation = ["Yaw" | "Pitch | "Roll"] * val = negative or positive int * * @param string rotation * @param int val * @return int */ void GyroRotation(string rotation, int val){ switch(rotation){ case "Pitch": pitch_state = val; break; case "Yaw": yaw_state = val; break; case "Roll": roll_state = val; break; } float speed = 0.01f * turnSpeed * val; for (int i = 0; i < srpGyroBlocks.Count ; i++ ){ (srpGyroBlocks[i] as IMyGyro).SetValueFloat(rotation, speed); } } // Temp global variables double temp_output_max = 0.0; double temp_output_cur = 0.0; double temp_input_max = 0.0; double temp_input_cur = 0.0; double temp_storage_max = 0.0; double temp_storage_cur = 0.0; /** * Set battery variables from the Details tring to the temp vars * * tempBlock = any powered IMyTerminalBlock * * @param IMyTerminalBlock tempBlock * @return bool */ bool setTempBatteryData(IMyTerminalBlock tempBlock){ // If it's not a battery, get out of here if(!(tempBlock is IMyBatteryBlock)){ return false; } // Get all the juicy info about the battery (yes this comment is a play on the word juicy) System.Text.RegularExpressions.Match match = batteryRegex.Match(tempBlock.DetailedInfo); if(match.Success){ Double n; if(Double.TryParse(match.Groups[1].Value, out n)){ // max output temp_output_max = n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf(match.Groups[2].Value)); } if(Double.TryParse(match.Groups[3].Value, out n)){ // max input temp_input_max = n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf(match.Groups[4].Value)); } if(Double.TryParse(match.Groups[5].Value, out n)){ // max output temp_storage_max = n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf(match.Groups[6].Value)); } if(Double.TryParse(match.Groups[7].Value, out n)){ // current input temp_input_cur = n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf(match.Groups[8].Value)); } if(Double.TryParse(match.Groups[9].Value, out n)){ // current output temp_output_cur = n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf(match.Groups[10].Value)); } if(Double.TryParse(match.Groups[11].Value, out n)){ // current output temp_storage_cur = n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf(match.Groups[12].Value)); } return true; } return false; } /** * Run the battery management routine * * @return void */ void manageBatteries(){ if(srpSolarBlocks.Count > 0 & (srpBatteryBlocks.Count > 0 | dockedBatteryBlocks.Count > 0)){ // Solar array output info double solarr_output_cur = 0.0; double solarr_output_max = 0.0; double solarr_output_avail = 0.0; // Solar Batteries output info double solbat_output_cur = 0.0; double solbat_output_max = 0.0; double solbat_output_avail = 0.0; double solbat_output_avail_idle = 0.0; // Solar Batteries input info double solbat_input_cur = 0.0; double solbat_input_max = 0.0; double solbat_input_needed = 0.0; // Ship Batteries input info double shipbat_input_cur = 0.0; double shipbat_input_max = 0.0; double shipbat_input_needed = 0.0; // Flags bool we_done = false; bool ship_needs_charge = false; bool solbat_needs_charge = false; // Math variable double pwrDeficit = 0; // Get Solar Array values for(int i = 0; i < srpSolarBlocks.Count ; i++){ System.Text.RegularExpressions.Match match = solarPwrRegex.Match(srpSolarBlocks[i].DetailedInfo); Double n; if(match.Success ){ // Max output of the solar panel if(Double.TryParse( match.Groups[1].Value, out n )){ solarr_output_max += n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf( match.Groups[2].Value)); } // Current output of the solar panel if(Double.TryParse( match.Groups[3].Value, out n )){ solarr_output_cur += n * Math.Pow( 1000.0, ".kMGTPEZY".IndexOf( match.Groups[4].Value)); } } } solarr_output_avail = solarr_output_max - solarr_output_cur; // Available power // Get docked battery info for(int i = 0; i < dockedBatteryBlocks.Count; i++){ // Get the detailed power data and put it in the temp vars if(setTempBatteryData(dockedBatteryBlocks[i])){ // Ship batteries are always set to recharge if(!dockedBatteryBlocks[i].DetailedInfo.Contains("recharged")){ dockedBatteryBlocks[i].GetActionWithName("Recharge").Apply(dockedBatteryBlocks[i]); // Turn it off so we don't overload the array by adding a lot of new batteries at once. if((dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ dockedBatteryBlocks[i].GetActionWithName("OnOff_Off").Apply(dockedBatteryBlocks[i]); } } // If it's on and set to recharge, and it's not full, and it's functional, include it if((dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled & dockedBatteryBlocks[i].DetailedInfo.Contains("recharged") & temp_storage_max > temp_storage_cur){ shipbat_input_max += temp_input_max; shipbat_input_cur += temp_input_cur; } // If it's not full and not set to recharge, make note that we have batteries still needing charge else if(temp_storage_max > temp_storage_cur & !(dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ ship_needs_charge = true; } } } // Get SRP Battery info for(int i = 0; i < srpBatteryBlocks.Count; i++){ // Get the detailed power data and put it in the temp vars if(setTempBatteryData(srpBatteryBlocks[i])){ // If the battery has juice avabile, then include it in the total if(temp_storage_cur > 0 & (srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled & !srpBatteryBlocks[i].DetailedInfo.Contains("recharged")){ solbat_output_max += temp_output_max; solbat_output_cur += temp_output_cur; }else if(temp_storage_cur > 0){ solbat_output_avail_idle += temp_output_max; } // If it's on and set to recharge and it's not full if((srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled & srpBatteryBlocks[i].DetailedInfo.Contains("recharged") & temp_storage_max > temp_storage_cur){ solbat_input_max += temp_input_max; solbat_input_cur += temp_input_cur; }else if(temp_storage_max > temp_storage_cur){ solbat_needs_charge = true; } } } solbat_output_avail = solbat_output_max - solbat_output_cur; solbat_input_needed = solbat_input_max - solbat_input_max; shipbat_input_needed = shipbat_input_max - shipbat_input_cur; myDebug("solbat_out_max: "+solbat_output_max.ToString(), debugBat); myDebug("solarr_out_max: "+solarr_output_max.ToString(), debugBat); myDebug("solbat_input_max: "+solbat_input_max.ToString(), debugBat); myDebug("shipbat_input_max: "+shipbat_input_max.ToString(), debugBat); // If we keep the batteries on and current power is not optimal, then turn all batteries on and set them to discharge (this is complete powerloss prevention) if(keepBatteriesOn & currentPwr < minPwr){ // Loop through solarbats and make sure they're all on and set to discharge for(int i = 0; i < srpBatteryBlocks.Count; i++){ myDebug("Discharge: "+srpBatteryBlocks[i].CustomName, debugBat); // Set it to decharge if it's not already if(srpBatteryBlocks[i].DetailedInfo.Contains("recharged")){ srpBatteryBlocks[i].GetActionWithName("Recharge").Apply(srpBatteryBlocks[i]); } // Make sure it's on if(!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ srpBatteryBlocks[i].GetActionWithName("OnOff_On").Apply(srpBatteryBlocks[i]); } } } // Discharge any full batteries else if(keepBatteriesOn){ // Loop through solarbats and make sure they're all on and set to discharge for(int i = 0; i < srpBatteryBlocks.Count; i++){ if(setTempBatteryData(srpBatteryBlocks[i]) & temp_storage_cur >= temp_storage_max){ // Set it to decharge if it's not already if(srpBatteryBlocks[i].DetailedInfo.Contains("recharged")){ srpBatteryBlocks[i].GetActionWithName("Recharge").Apply(srpBatteryBlocks[i]); } // Make sure it's on if(!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ srpBatteryBlocks[i].GetActionWithName("OnOff_On").Apply(srpBatteryBlocks[i]); } } } } // If solar power + solar battery power is currently overloaded if(solarr_output_avail == 0 & solbat_output_avail == 0){ myDebug("Overloaded", debugBat); // No ships need charging, AND the solar array is optimal if(shipbat_input_max <= 0 & !ship_needs_charge & currentPwr >= minPwr){ pwrDeficit = Math.Abs(solarr_output_max - solbat_input_max); myDebug("pwrDeficit="+pwrDeficit.ToString(), debugBat); //If the power deficit is less than that of one charging array battery, ignore it if((shipType == "large" & pwrDeficit < largeBatteryMax) | (shipType == "small" & pwrDeficit < smallBatteryMax)){ myDebug("Ignore Overload", debugBat); return; } } // Loop through solar bats, find one that is set to recharge, and turn it off for(int i = 0; i < srpBatteryBlocks.Count; i++){ if(srpBatteryBlocks[i].DetailedInfo.Contains("recharged") & (srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ // Turn it off srpBatteryBlocks[i].GetActionWithName("OnOff_Off").Apply(srpBatteryBlocks[i]); // We only change 1 battery per tick return; } } // Loop through Solar bats, find one that has fuel, turn it one, and set it to discharge for(int i = 0; i < srpBatteryBlocks.Count; i++){ if(setTempBatteryData(srpBatteryBlocks[i])){ //if there is one that has fuel, and is not on or set to discharge, turn it on and set it to discharge if(temp_storage_cur > 0 & (!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled | srpBatteryBlocks[i].DetailedInfo.Contains("recharged")) ){ // Set it to decharge if it's not already if(srpBatteryBlocks[i].DetailedInfo.Contains("recharged")){ srpBatteryBlocks[i].GetActionWithName("Recharge").Apply(srpBatteryBlocks[i]); } // Make sure it's on if(!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ srpBatteryBlocks[i].GetActionWithName("OnOff_On").Apply(srpBatteryBlocks[i]); } // We only change 1 battery per tick return; } } } pwrDeficit = (solarr_output_max + solbat_output_max) - (shipbat_input_cur + solbat_input_cur); if(pwrDeficit < -smallBatteryMax & chargeDockedBatteries){ // Loop through ship bats, find one that is charging and turn it off for(int i = 0; i < dockedBatteryBlocks.Count; i++){ // If there is one that is charging if(dockedBatteryBlocks[i].IsFunctional & (dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled & dockedBatteryBlocks[i].DetailedInfo.Contains("recharged")){ // turn it off dockedBatteryBlocks[i].GetActionWithName("OnOff_Off").Apply(dockedBatteryBlocks[i]); // We only change 1 battery per tick return; } } } // Nothing could help the overload, we don't want to do anything else though. return; } // If there is no needed input for Ship Batteries, then charge solar bats if((shipbat_input_max <= 0 & !ship_needs_charge) | !chargeDockedBatteries){ myDebug("No Ships", debugBat); // Find any functional Solar Bats that are set to discharge and are turned on, and turn them off if(!keepBatteriesOn){ for(int i = 0; i < srpBatteryBlocks.Count; i++){ // Currently being depleted if(!srpBatteryBlocks[i].DetailedInfo.Contains("recharged") & (srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ // Turn it off srpBatteryBlocks[i].GetActionWithName("OnOff_Off").Apply(srpBatteryBlocks[i]); // We only change 1 battery per tick return; } } } // Only recharge solar bats if we're optimal, OR have enough excess to fully accomadate if(currentPwr >= minPwr | (shipType == "small" & solarr_output_avail > smallBatteryMax) | (shipType == "large" & solarr_output_avail > largeBatteryMax)){ // Loop through functional Solar bats, find one that is not full, and set it to recharge for(int i = 0; i < srpBatteryBlocks.Count; i++){ if(setTempBatteryData(srpBatteryBlocks[i])){ // If not full, and power available < power max, where the battery is either off or not charging if(temp_storage_max > temp_storage_cur & solarr_output_max > solarr_output_cur & (!srpBatteryBlocks[i].DetailedInfo.Contains("recharged") | !(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled) ){ // Charge it if(!srpBatteryBlocks[i].DetailedInfo.Contains("recharged")){ srpBatteryBlocks[i].GetActionWithName("Recharge").Apply(srpBatteryBlocks[i]); } // Make sure it's on if(!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ srpBatteryBlocks[i].GetActionWithName("OnOff_On").Apply(srpBatteryBlocks[i]); } // We only change 1 battery per tick return; } } } } } // If all of the ship bats are set to charge, the maybe turn off or charge some solar bats else if(shipbat_input_max == shipbat_input_cur & solarr_output_avail > largeBatteryMax & !ship_needs_charge){ myDebug("All Ships charging", debugBat); //TODO: Do this later, it's not essential } // If there are ship bats that need charging else if(chargeDockedBatteries){ myDebug("Ships need charging", debugBat); // Loop through ship bats, Find one that is not full and if there is power available, set it to charge for(int i = 0; i < dockedBatteryBlocks.Count; i++){ if(setTempBatteryData(dockedBatteryBlocks[i])){ // If not full, and power available > power_required and it's off or not set to recharge if(temp_storage_max > temp_storage_cur & (solbat_output_max + solarr_output_max) > (solbat_output_cur + solarr_output_cur) & (!dockedBatteryBlocks[i].DetailedInfo.Contains("recharged") | !(dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled ) ){ // Charge it if(!dockedBatteryBlocks[i].DetailedInfo.Contains("recharged")){ dockedBatteryBlocks[i].GetActionWithName("Recharge").Apply(dockedBatteryBlocks[i]); } // Make sure it's on if(!(dockedBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ dockedBatteryBlocks[i].GetActionWithName("OnOff_On").Apply(dockedBatteryBlocks[i]); } // We only change 1 battery per tick return; } } } // Loop through solar bats, If there are functional solar bats that are not discharging but can be, then put them on the grid for(int i = 0; i < srpBatteryBlocks.Count; i++){ if(setTempBatteryData(srpBatteryBlocks[i])){ // If has charge, and not discharging if(temp_storage_cur > 0 & (!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled | srpBatteryBlocks[i].DetailedInfo.Contains("recharged")) ){ // Charge it if(!srpBatteryBlocks[i].DetailedInfo.Contains("recharged")){ srpBatteryBlocks[i].GetActionWithName("Recharge").Apply(srpBatteryBlocks[i]); } // Make sure it's on if(!(srpBatteryBlocks[i] as IMyFunctionalBlock).Enabled){ srpBatteryBlocks[i].GetActionWithName("OnOff_On").Apply(srpBatteryBlocks[i]); } // We only change 1 battery per tick return; } } } } } } /** * Debug function for echoing strings * * @param String message * @param bool show * @return void */ void myDebug(String message, bool show){ if(show){ Echo(message); } } //////////////////////////////////// // Block Filters & Fetches //////////////////////////////////// /** * Get the currently running ProgrammableBlock * * @return IMyProgrammableBlock */ IMyProgrammableBlock getSelf(){ var runningBlocks = new List<IMyTerminalBlock>(); GridTerminalSystem.GetBlocksOfType<IMyProgrammableBlock>(runningBlocks,filterRunningPB); if(runningBlocks.Count > 1){ throw new Exception("More than one blocks is running"); } return runningBlocks[0] as IMyProgrammableBlock; } /** * Filter for finding the currently running programmable block * * @param IMyTerminalBlock block * @return bool */ bool filterRunningPB(IMyTerminalBlock block) { return (block is IMyProgrammableBlock) & (block as IMyProgrammableBlock).IsRunning; } /** * Filter for finding functional Solar Panels on this grid * * @param IMyTerminalBlock block * @return bool */ bool filterSRPSolarPanels(IMyTerminalBlock block){ return ((block is IMySolarPanel) & block.IsFunctional & block.CubeGrid == thisProgrammableBlock.CubeGrid); } /** * Filter for finding functional Gyros on this grid * * @param IMyTerminalBlock block * @return bool */ bool filterSRPGyros(IMyTerminalBlock block){ return ((block is IMyGyro) & block.IsFunctional & block.CubeGrid == thisProgrammableBlock.CubeGrid); } /** * Filter for finding Batteries on this grid * * @param IMyTerminalBlock block * @return bool */ bool filterSRPBatteries(IMyTerminalBlock block){ return ((block is IMyBatteryBlock) & block.IsFunctional & block.CubeGrid == thisProgrammableBlock.CubeGrid); } /** * Filter for finding Docked Batteries * * @param IMyTerminalBlock block * @return bool */ bool filterDockedBatteries(IMyTerminalBlock block){ return ((block is IMyBatteryBlock) & block.IsFunctional & block.CubeGrid != thisProgrammableBlock.CubeGrid); } ////////////////// // Lazy Storage ////////////////// // TODO: Write or find a storage class to make this WAY more robust /** * Save a single variable to the Storage string * Currently only saves a double and only one of two variables * * @param String name * @param String name * @return void */ void saveVar(String name, double newValue){ switch(name){ case "currentPower": double highestPower = getVar("highestPower"); saveVars(newValue, highestPower); break; case "highestPower": double currentPower = getVar("currentPower"); saveVars(currentPower, newValue); break; } } /** * Save a all the variables to the Storage string * * @param double currentPower * @param double highestPower * @return void */ void saveVars(double currentPower, double highestPower){ Storage = currentPower.ToString()+"|"+highestPower.ToString(); } /** * Get a single variable of name from the Storage string * * @param string name * @return double */ double getVar(string name){ if(Storage.Length == 0){ return 0; } double myVal; switch(name){ case "currentPower": double.TryParse(Storage.Substring(0, Storage.IndexOf('|')),out myVal); return myVal; break; case "highestPower": double.TryParse(Storage.Substring(Storage.IndexOf('|')+1),out myVal); return myVal; break; } Echo("WTF"); return 0; }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Text.RegularExpressions; using NDesk.Options; using GitTfs.Core; using StructureMap; namespace GitTfs.Commands { [Pluggable("init")] [Description("init [options] tfs-url-or-instance-name repository-path [git-repository]")] public class Init : GitTfsCommand { private readonly InitOptions _initOptions; private readonly RemoteOptions _remoteOptions; private readonly Globals _globals; private readonly IGitHelpers _gitHelper; public Init(RemoteOptions remoteOptions, InitOptions initOptions, Globals globals, IGitHelpers gitHelper) { _remoteOptions = remoteOptions; _gitHelper = gitHelper; _globals = globals; _initOptions = initOptions; } public OptionSet OptionSet { get { return _initOptions.OptionSet.Merge(_remoteOptions.OptionSet); } } public bool IsBare { get { return _initOptions.IsBare; } } public IGitHelpers GitHelper { get { return _gitHelper; } } public int Run(string tfsUrl, string tfsRepositoryPath) { tfsRepositoryPath.AssertValidTfsPathOrRoot(); DoGitInitDb(); CommitTheGitIgnoreFile(_initOptions.GitIgnorePath); GitTfsInit(tfsUrl, tfsRepositoryPath); return 0; } private void CommitTheGitIgnoreFile(string pathToGitIgnoreFile) { if (string.IsNullOrWhiteSpace(pathToGitIgnoreFile)) { Trace.WriteLine("No .gitignore file specified..."); return; } _globals.Repository.CommitGitIgnore(pathToGitIgnoreFile); } public int Run(string tfsUrl, string tfsRepositoryPath, string gitRepositoryPath) { tfsRepositoryPath.AssertValidTfsPathOrRoot(); if (!_initOptions.IsBare) { InitSubdir(gitRepositoryPath); } else { Environment.CurrentDirectory = gitRepositoryPath; _globals.GitDir = "."; } var runResult = Run(tfsUrl, tfsRepositoryPath); try { File.WriteAllText(@".git\description", tfsRepositoryPath + "\n" + HideUserCredentials(_globals.CommandLineRun)); } catch (Exception) { Trace.WriteLine("warning: Unable to update de repository description!"); } return runResult; } public static string HideUserCredentials(string commandLineRun) { Regex rgx = new Regex("(--username|-u)[= ][^ ]+"); commandLineRun = rgx.Replace(commandLineRun, "--username=xxx"); rgx = new Regex("(--password|-p)[= ][^ ]+"); return rgx.Replace(commandLineRun, "--password=xxx"); } private void InitSubdir(string repositoryPath) { if (!Directory.Exists(repositoryPath)) Directory.CreateDirectory(repositoryPath); Environment.CurrentDirectory = repositoryPath; _globals.GitDir = ".git"; } private void DoGitInitDb() { if (!Directory.Exists(_globals.GitDir) || _initOptions.IsBare) { _gitHelper.CommandNoisy(BuildInitCommand()); } _globals.Repository = _gitHelper.MakeRepository(_globals.GitDir); if (!string.IsNullOrWhiteSpace(_initOptions.WorkspacePath)) { Trace.WriteLine("workspace path:" + _initOptions.WorkspacePath); try { Directory.CreateDirectory(_initOptions.WorkspacePath); _globals.Repository.SetConfig(GitTfsConstants.WorkspaceConfigKey, _initOptions.WorkspacePath); } catch (Exception) { throw new GitTfsException("error: workspace path is invalid!"); } } _globals.Repository.SetConfig(GitTfsConstants.IgnoreBranches, false.ToString()); } private string[] BuildInitCommand() { var initCommand = new List<string> { "init" }; if (_initOptions.GitInitTemplate != null) initCommand.Add("--template=" + _initOptions.GitInitTemplate); if (_initOptions.IsBare) initCommand.Add("--bare"); if (_initOptions.GitInitShared is string) initCommand.Add("--shared=" + _initOptions.GitInitShared); else if (_initOptions.GitInitShared != null) initCommand.Add("--shared"); return initCommand.ToArray(); } private void GitTfsInit(string tfsUrl, string tfsRepositoryPath) { _globals.Repository.CreateTfsRemote(new RemoteInfo { Id = _globals.RemoteId, Url = tfsUrl, Repository = tfsRepositoryPath, RemoteOptions = _remoteOptions, }, _initOptions.GitInitAutoCrlf, _initOptions.GitInitIgnoreCase); } } public static class Ext { private static readonly Regex ValidTfsPath = new Regex("^\\$/.+"); public static bool IsValidTfsPath(this string tfsPath) { return ValidTfsPath.IsMatch(tfsPath); } public static void AssertValidTfsPathOrRoot(this string tfsPath) { if (tfsPath == GitTfsConstants.TfsRoot) return; AssertValidTfsPath(tfsPath); } public static void AssertValidTfsPath(this string tfsPath) { if (!ValidTfsPath.IsMatch(tfsPath)) throw new GitTfsException("TFS repository can not be root and must start with \"$/\".", SuggestPaths(tfsPath)); } private static IEnumerable<string> SuggestPaths(string tfsPath) { if (tfsPath == "$" || tfsPath == "$/") yield return "Cloning an entire TFS repository is not supported. Try using a subdirectory of the root (e.g. $/MyProject)."; else if (tfsPath.StartsWith("$")) yield return "Try using $/" + tfsPath.Substring(1); else yield return "Try using $/" + tfsPath; } public static string ToGitRefName(this string expectedRefName) { expectedRefName = Regex.Replace(expectedRefName, @"[!~$?[*^: \\]", string.Empty); expectedRefName = expectedRefName.Replace("@{", string.Empty); expectedRefName = expectedRefName.Replace("..", string.Empty); expectedRefName = expectedRefName.Replace("//", string.Empty); expectedRefName = expectedRefName.Replace("/.", "/"); expectedRefName = expectedRefName.TrimEnd('.', '/'); return expectedRefName.Trim('/'); } public static string ToGitBranchNameFromTfsRepositoryPath(this string tfsRepositoryPath, bool includeTeamProjectName = false) { if (includeTeamProjectName) { return tfsRepositoryPath .Replace("$/", string.Empty) .ToGitRefName(); } string gitBranchNameExpected = tfsRepositoryPath.IndexOf("$/") == 0 ? tfsRepositoryPath.Remove(0, tfsRepositoryPath.IndexOf('/', 2) + 1) : tfsRepositoryPath; return gitBranchNameExpected.ToGitRefName(); } public static string ToTfsTeamProjectRepositoryPath(this string tfsRepositoryPath) { if (!tfsRepositoryPath.StartsWith("$/")) { return tfsRepositoryPath; } var index = tfsRepositoryPath.IndexOf('/', 2); return index == -1 ? tfsRepositoryPath : tfsRepositoryPath.Remove(index, tfsRepositoryPath.Length - index); } public static string ToLocalGitRef(this string refName) { return "refs/heads/" + refName; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Description; using WootzJs.Site.Api.Areas.HelpPage.Models; namespace WootzJs.Site.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); model = GenerateApiModel(apiDescription, sampleGenerator); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HelpPageSampleGenerator sampleGenerator) { HelpPageApiModel apiModel = new HelpPageApiModel(); apiModel.ApiDescription = apiDescription; try { foreach (var item in sampleGenerator.GetSampleRequests(apiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception Message: {0}", e.Message)); } return apiModel; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
// // OciParameterDescriptor.cs // // Part of managed C#/.NET library System.Data.OracleClient.dll // // Part of the Mono class libraries at // mcs/class/System.Data.OracleClient/System.Data.OracleClient.Oci // // Assembly: System.Data.OracleClient.dll // Namespace: System.Data.OracleClient.Oci // // Author: // Tim Coleman <tim@timcoleman.com> // // Copyright (C) Tim Coleman, 2003 // using System; using System.Data.OracleClient; using System.Runtime.InteropServices; namespace System.Data.OracleClient.Oci { internal sealed class OciParameterDescriptor : OciDescriptorHandle { #region Fields OciErrorHandle errorHandle; OciServiceHandle service; OciDataType type; #endregion // Fields #region Constructors public OciParameterDescriptor (OciHandle parent, IntPtr handle) : base (OciHandleType.Parameter, parent, handle) { } #endregion // Constructors #region Properties public OciErrorHandle ErrorHandle { get { return errorHandle; } set { errorHandle = value; } } #endregion // Properties #region Methods public string GetName () { return GetAttributeString (OciAttributeType.Name, ErrorHandle); } public int GetDataSize () { return (int) GetAttributeUInt16 (OciAttributeType.DataSize, ErrorHandle); } public OciDataType GetDataType () { return (OciDataType) GetAttributeInt32 (OciAttributeType.DataType, ErrorHandle); } public Type GetFieldType (string sDataTypeName) { switch (sDataTypeName) { case "VarChar2": return typeof (System.String); case "Number": return typeof (System.Decimal); case "Integer": return typeof (System.Int32); case "Float": return typeof (System.Decimal); case "String": return typeof (System.String); case "VarNum": return typeof (System.Decimal); case "Long": return typeof (System.String); case "VarChar": return typeof (System.String); case "RowId": return typeof (System.String); case "Date": return typeof (System.DateTime); case "VarRaw": return Type.GetType ("System.Byte[]"); case "Raw": return Type.GetType ("System.Byte[]"); case "LongRaw": return Type.GetType ("System.Byte[]"); case "UnsignedInt": return typeof (System.UInt32); case "LongVarChar": return typeof (System.String); case "LongVarRaw": return Type.GetType ("System.Byte[]"); case "Char": return typeof (System.String); case "CharZ": return typeof (System.String); case "RowIdDescriptor": return typeof (System.String); case "NamedDataType": return typeof (System.String); case "Ref": return Type.GetType ("System.Data.OracleClient.OracleDataReader"); case "Clob": return typeof (System.String); case "Blob": return Type.GetType ("System.Byte[]"); case "BFile": return Type.GetType ("System.Byte[]"); case "OciString": return typeof (System.String); case "OciDate": return typeof (System.DateTime); default: // FIXME: are these types correct? return typeof(System.String); } } public string GetDataTypeName () { switch(GetDataType()) { case OciDataType.VarChar2: return "VarChar2"; case OciDataType.Number: return "Number"; case OciDataType.Integer: return "Integer"; case OciDataType.Float: return "Float"; case OciDataType.String: return "String"; case OciDataType.VarNum: return "VarNum"; case OciDataType.Long: return "Long"; case OciDataType.VarChar: return "VarChar"; case OciDataType.RowId: return "RowId"; case OciDataType.Date: return "Date"; case OciDataType.VarRaw: return "VarRaw"; case OciDataType.Raw: return "Raw"; case OciDataType.LongRaw: return "LongRaw"; case OciDataType.UnsignedInt: return "UnsignedInt"; case OciDataType.LongVarChar: return "LongVarChar"; case OciDataType.LongVarRaw: return "LongVarRaw"; case OciDataType.Char: return "Char"; case OciDataType.CharZ: return "CharZ"; case OciDataType.RowIdDescriptor: return "RowIdDescriptor"; case OciDataType.NamedDataType: return "NamedDataType"; case OciDataType.Ref: return "Ref"; case OciDataType.Clob: return "Clob"; case OciDataType.Blob: return "Blob"; case OciDataType.BFile: return "BFile"; case OciDataType.OciString: return "OciString"; case OciDataType.OciDate: return "OciDate"; default: return "Unknown"; } } public short GetPrecision () { return (short) GetAttributeByte (OciAttributeType.Precision, ErrorHandle); } public short GetScale () { return (short) GetAttributeSByte (OciAttributeType.Scale, ErrorHandle); } public bool GetIsNull () { return GetAttributeBool (OciAttributeType.IsNull, ErrorHandle); } #endregion // Methods } }
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 AppTokenMvcApiService.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; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // // using System; using System.Runtime.InteropServices; #pragma warning disable 436 // Redefining types from Windows.Foundation namespace Windows.UI.Xaml { // // Duration is the managed projection of Windows.UI.Xaml.Duration. Any changes to the layout // of this type must be exactly mirrored on the native WinRT side as well. // // DurationType is the managed projection of Windows.UI.Xaml.DurationType. Any changes to this // enumeration must be exactly mirrored on the native WinRT side as well. // // Note that these types are owned by the Jupiter team. Please contact them before making any // changes here. // public enum DurationType { Automatic, TimeSpan, Forever } [StructLayout(LayoutKind.Sequential)] public struct Duration { private TimeSpan _timeSpan; private DurationType _durationType; public Duration(TimeSpan timeSpan) { _durationType = DurationType.TimeSpan; _timeSpan = timeSpan; } public static implicit operator Duration(TimeSpan timeSpan) { return new Duration(timeSpan); } public static Duration operator +(Duration t1, Duration t2) { if (t1.HasTimeSpan && t2.HasTimeSpan) { return new Duration(t1._timeSpan + t2._timeSpan); } else if (t1._durationType != DurationType.Automatic && t2._durationType != DurationType.Automatic) { return Duration.Forever; } else { // Automatic + anything is Automatic return Duration.Automatic; } } public static Duration operator -(Duration t1, Duration t2) { if (t1.HasTimeSpan && t2.HasTimeSpan) { return new Duration(t1._timeSpan - t2._timeSpan); } else if (t1._durationType == DurationType.Forever && t2.HasTimeSpan) { return Duration.Forever; } else { return Duration.Automatic; } } public static bool operator ==(Duration t1, Duration t2) { return t1.Equals(t2); } public static bool operator !=(Duration t1, Duration t2) { return !(t1.Equals(t2)); } public static bool operator >(Duration t1, Duration t2) { if (t1.HasTimeSpan && t2.HasTimeSpan) { return t1._timeSpan > t2._timeSpan; } else if (t1.HasTimeSpan && t2._durationType == DurationType.Forever) { return false; } else if (t1._durationType == DurationType.Forever && t2.HasTimeSpan) { return true; } else { return false; } } public static bool operator >=(Duration t1, Duration t2) { if (t1._durationType == DurationType.Automatic && t2._durationType == DurationType.Automatic) { return true; } else if (t1._durationType == DurationType.Automatic || t2._durationType == DurationType.Automatic) { return false; } else { return !(t1 < t2); } } public static bool operator <(Duration t1, Duration t2) { if (t1.HasTimeSpan && t2.HasTimeSpan) { return t1._timeSpan < t2._timeSpan; } else if (t1.HasTimeSpan && t2._durationType == DurationType.Forever) { return true; } else if (t1._durationType == DurationType.Forever && t2.HasTimeSpan) { return false; } else { return false; } } public static bool operator <=(Duration t1, Duration t2) { if (t1._durationType == DurationType.Automatic && t2._durationType == DurationType.Automatic) { return true; } else if (t1._durationType == DurationType.Automatic || t2._durationType == DurationType.Automatic) { return false; } else { return !(t1 > t2); } } public static int Compare(Duration t1, Duration t2) { if (t1._durationType == DurationType.Automatic) { if (t2._durationType == DurationType.Automatic) { return 0; } else { return -1; } } else if (t2._durationType == DurationType.Automatic) { return 1; } else { if (t1 < t2) { return -1; } else if (t1 > t2) { return 1; } else { return 0; } } } public static Duration operator +(Duration duration) { return duration; } public bool HasTimeSpan { get { return (_durationType == DurationType.TimeSpan); } } public static Duration Automatic { get { Duration duration = new Duration(); duration._durationType = DurationType.Automatic; return duration; } } public static Duration Forever { get { Duration duration = new Duration(); duration._durationType = DurationType.Forever; return duration; } } public TimeSpan TimeSpan { get { if (HasTimeSpan) { return _timeSpan; } else { throw new InvalidOperationException(); } } } public Duration Add(Duration duration) { return this + duration; } public override bool Equals(object value) { return value is Duration && Equals((Duration)value); } public bool Equals(Duration duration) { if (HasTimeSpan) { if (duration.HasTimeSpan) { return _timeSpan == duration._timeSpan; } else { return false; } } else { return _durationType == duration._durationType; } } public static bool Equals(Duration t1, Duration t2) { return t1.Equals(t2); } public override int GetHashCode() { if (HasTimeSpan) { return _timeSpan.GetHashCode(); } else { return _durationType.GetHashCode() + 17; } } public Duration Subtract(Duration duration) { return this - duration; } public override string ToString() { if (HasTimeSpan) { return _timeSpan.ToString(); // "00"; //TypeDescriptor.GetConverter(_timeSpan).ConvertToString(_timeSpan); } else if (_durationType == DurationType.Forever) { return "Forever"; } else // IsAutomatic { return "Automatic"; } } } } #pragma warning restore 436
/* * 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 LSLInteger = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; namespace OpenSim.Region.ScriptEngine.Shared.ScriptBase { public partial class ScriptBaseClass { // LSL CONSTANTS public static readonly LSLInteger TRUE = new LSLInteger(1); public static readonly LSLInteger FALSE = new LSLInteger(0); public const int STATUS_PHYSICS = 1; public const int STATUS_ROTATE_X = 2; public const int STATUS_ROTATE_Y = 4; public const int STATUS_ROTATE_Z = 8; public const int STATUS_PHANTOM = 16; public const int STATUS_SANDBOX = 32; public const int STATUS_BLOCK_GRAB = 64; public const int STATUS_DIE_AT_EDGE = 128; public const int STATUS_RETURN_AT_EDGE = 256; public const int STATUS_CAST_SHADOWS = 512; public const int STATUS_BLOCK_GRAB_OBJECT = 1024; public const int AGENT = 1; public const int AGENT_BY_LEGACY_NAME = 1; public const int AGENT_BY_USERNAME = 0x10; public const int NPC = 0x20; public const int ACTIVE = 2; public const int PASSIVE = 4; public const int SCRIPTED = 8; public const int OS_NPC = 0x01000000; public const int CONTROL_FWD = 1; public const int CONTROL_BACK = 2; public const int CONTROL_LEFT = 4; public const int CONTROL_RIGHT = 8; public const int CONTROL_UP = 16; public const int CONTROL_DOWN = 32; public const int CONTROL_ROT_LEFT = 256; public const int CONTROL_ROT_RIGHT = 512; public const int CONTROL_LBUTTON = 268435456; public const int CONTROL_ML_LBUTTON = 1073741824; //Permissions public const int PERMISSION_DEBIT = 2; public const int PERMISSION_TAKE_CONTROLS = 4; public const int PERMISSION_REMAP_CONTROLS = 8; public const int PERMISSION_TRIGGER_ANIMATION = 16; public const int PERMISSION_ATTACH = 32; public const int PERMISSION_RELEASE_OWNERSHIP = 64; public const int PERMISSION_CHANGE_LINKS = 128; public const int PERMISSION_CHANGE_JOINTS = 256; public const int PERMISSION_CHANGE_PERMISSIONS = 512; public const int PERMISSION_TRACK_CAMERA = 1024; public const int PERMISSION_CONTROL_CAMERA = 2048; public const int AGENT_FLYING = 1; public const int AGENT_ATTACHMENTS = 2; public const int AGENT_SCRIPTED = 4; public const int AGENT_MOUSELOOK = 8; public const int AGENT_SITTING = 16; public const int AGENT_ON_OBJECT = 32; public const int AGENT_AWAY = 64; public const int AGENT_WALKING = 128; public const int AGENT_IN_AIR = 256; public const int AGENT_TYPING = 512; public const int AGENT_CROUCHING = 1024; public const int AGENT_BUSY = 2048; public const int AGENT_ALWAYS_RUN = 4096; //Particle Systems public const int PSYS_PART_INTERP_COLOR_MASK = 1; public const int PSYS_PART_INTERP_SCALE_MASK = 2; public const int PSYS_PART_BOUNCE_MASK = 4; public const int PSYS_PART_WIND_MASK = 8; public const int PSYS_PART_FOLLOW_SRC_MASK = 16; public const int PSYS_PART_FOLLOW_VELOCITY_MASK = 32; public const int PSYS_PART_TARGET_POS_MASK = 64; public const int PSYS_PART_TARGET_LINEAR_MASK = 128; public const int PSYS_PART_EMISSIVE_MASK = 256; public const int PSYS_PART_RIBBON_MASK = 1024; public const int PSYS_PART_FLAGS = 0; public const int PSYS_PART_START_COLOR = 1; public const int PSYS_PART_START_ALPHA = 2; public const int PSYS_PART_END_COLOR = 3; public const int PSYS_PART_END_ALPHA = 4; public const int PSYS_PART_START_SCALE = 5; public const int PSYS_PART_END_SCALE = 6; public const int PSYS_PART_MAX_AGE = 7; public const int PSYS_SRC_ACCEL = 8; public const int PSYS_SRC_PATTERN = 9; public const int PSYS_SRC_INNERANGLE = 10; public const int PSYS_SRC_OUTERANGLE = 11; public const int PSYS_SRC_TEXTURE = 12; public const int PSYS_SRC_BURST_RATE = 13; public const int PSYS_SRC_BURST_PART_COUNT = 15; public const int PSYS_SRC_BURST_RADIUS = 16; public const int PSYS_SRC_BURST_SPEED_MIN = 17; public const int PSYS_SRC_BURST_SPEED_MAX = 18; public const int PSYS_SRC_MAX_AGE = 19; public const int PSYS_SRC_TARGET_KEY = 20; public const int PSYS_SRC_OMEGA = 21; public const int PSYS_SRC_ANGLE_BEGIN = 22; public const int PSYS_SRC_ANGLE_END = 23; public const int PSYS_PART_BLEND_FUNC_SOURCE = 24; public const int PSYS_PART_BLEND_FUNC_DEST = 25; public const int PSYS_PART_START_GLOW = 26; public const int PSYS_PART_END_GLOW = 27; public const int PSYS_PART_BF_ONE = 0; public const int PSYS_PART_BF_ZERO = 1; public const int PSYS_PART_BF_DEST_COLOR = 2; public const int PSYS_PART_BF_SOURCE_COLOR = 3; public const int PSYS_PART_BF_ONE_MINUS_DEST_COLOR = 4; public const int PSYS_PART_BF_ONE_MINUS_SOURCE_COLOR = 5; public const int PSYS_PART_BF_SOURCE_ALPHA = 7; public const int PSYS_PART_BF_ONE_MINUS_SOURCE_ALPHA = 9; public const int PSYS_SRC_PATTERN_DROP = 1; public const int PSYS_SRC_PATTERN_EXPLODE = 2; public const int PSYS_SRC_PATTERN_ANGLE = 4; public const int PSYS_SRC_PATTERN_ANGLE_CONE = 8; public const int PSYS_SRC_PATTERN_ANGLE_CONE_EMPTY = 16; public const int VEHICLE_TYPE_NONE = 0; public const int VEHICLE_TYPE_SLED = 1; public const int VEHICLE_TYPE_CAR = 2; public const int VEHICLE_TYPE_BOAT = 3; public const int VEHICLE_TYPE_AIRPLANE = 4; public const int VEHICLE_TYPE_BALLOON = 5; public const int VEHICLE_LINEAR_FRICTION_TIMESCALE = 16; public const int VEHICLE_ANGULAR_FRICTION_TIMESCALE = 17; public const int VEHICLE_LINEAR_MOTOR_DIRECTION = 18; public const int VEHICLE_LINEAR_MOTOR_OFFSET = 20; public const int VEHICLE_ANGULAR_MOTOR_DIRECTION = 19; public const int VEHICLE_HOVER_HEIGHT = 24; public const int VEHICLE_HOVER_EFFICIENCY = 25; public const int VEHICLE_HOVER_TIMESCALE = 26; public const int VEHICLE_BUOYANCY = 27; public const int VEHICLE_LINEAR_DEFLECTION_EFFICIENCY = 28; public const int VEHICLE_LINEAR_DEFLECTION_TIMESCALE = 29; public const int VEHICLE_LINEAR_MOTOR_TIMESCALE = 30; public const int VEHICLE_LINEAR_MOTOR_DECAY_TIMESCALE = 31; public const int VEHICLE_ANGULAR_DEFLECTION_EFFICIENCY = 32; public const int VEHICLE_ANGULAR_DEFLECTION_TIMESCALE = 33; public const int VEHICLE_ANGULAR_MOTOR_TIMESCALE = 34; public const int VEHICLE_ANGULAR_MOTOR_DECAY_TIMESCALE = 35; public const int VEHICLE_VERTICAL_ATTRACTION_EFFICIENCY = 36; public const int VEHICLE_VERTICAL_ATTRACTION_TIMESCALE = 37; public const int VEHICLE_BANKING_EFFICIENCY = 38; public const int VEHICLE_BANKING_MIX = 39; public const int VEHICLE_BANKING_TIMESCALE = 40; public const int VEHICLE_REFERENCE_FRAME = 44; public const int VEHICLE_RANGE_BLOCK = 45; public const int VEHICLE_ROLL_FRAME = 46; public const int VEHICLE_FLAG_NO_DEFLECTION_UP = 1; public const int VEHICLE_FLAG_LIMIT_ROLL_ONLY = 2; public const int VEHICLE_FLAG_HOVER_WATER_ONLY = 4; public const int VEHICLE_FLAG_HOVER_TERRAIN_ONLY = 8; public const int VEHICLE_FLAG_HOVER_GLOBAL_HEIGHT = 16; public const int VEHICLE_FLAG_HOVER_UP_ONLY = 32; public const int VEHICLE_FLAG_LIMIT_MOTOR_UP = 64; public const int VEHICLE_FLAG_MOUSELOOK_STEER = 128; public const int VEHICLE_FLAG_MOUSELOOK_BANK = 256; public const int VEHICLE_FLAG_CAMERA_DECOUPLED = 512; public const int VEHICLE_FLAG_NO_X = 1024; public const int VEHICLE_FLAG_NO_Y = 2048; public const int VEHICLE_FLAG_NO_Z = 4096; public const int VEHICLE_FLAG_LOCK_HOVER_HEIGHT = 8192; public const int VEHICLE_FLAG_NO_DEFLECTION = 16392; public const int VEHICLE_FLAG_LOCK_ROTATION = 32784; public const int INVENTORY_ALL = -1; public const int INVENTORY_NONE = -1; public const int INVENTORY_TEXTURE = 0; public const int INVENTORY_SOUND = 1; public const int INVENTORY_LANDMARK = 3; public const int INVENTORY_CLOTHING = 5; public const int INVENTORY_OBJECT = 6; public const int INVENTORY_NOTECARD = 7; public const int INVENTORY_SCRIPT = 10; public const int INVENTORY_BODYPART = 13; public const int INVENTORY_ANIMATION = 20; public const int INVENTORY_GESTURE = 21; public const int ATTACH_CHEST = 1; public const int ATTACH_HEAD = 2; public const int ATTACH_LSHOULDER = 3; public const int ATTACH_RSHOULDER = 4; public const int ATTACH_LHAND = 5; public const int ATTACH_RHAND = 6; public const int ATTACH_LFOOT = 7; public const int ATTACH_RFOOT = 8; public const int ATTACH_BACK = 9; public const int ATTACH_PELVIS = 10; public const int ATTACH_MOUTH = 11; public const int ATTACH_CHIN = 12; public const int ATTACH_LEAR = 13; public const int ATTACH_REAR = 14; public const int ATTACH_LEYE = 15; public const int ATTACH_REYE = 16; public const int ATTACH_NOSE = 17; public const int ATTACH_RUARM = 18; public const int ATTACH_RLARM = 19; public const int ATTACH_LUARM = 20; public const int ATTACH_LLARM = 21; public const int ATTACH_RHIP = 22; public const int ATTACH_RULEG = 23; public const int ATTACH_RLLEG = 24; public const int ATTACH_LHIP = 25; public const int ATTACH_LULEG = 26; public const int ATTACH_LLLEG = 27; public const int ATTACH_BELLY = 28; public const int ATTACH_RPEC = 29; public const int ATTACH_LPEC = 30; public const int ATTACH_LEFT_PEC = 29; // Same value as ATTACH_RPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_RIGHT_PEC = 30; // Same value as ATTACH_LPEC, see https://jira.secondlife.com/browse/SVC-580 public const int ATTACH_HUD_CENTER_2 = 31; public const int ATTACH_HUD_TOP_RIGHT = 32; public const int ATTACH_HUD_TOP_CENTER = 33; public const int ATTACH_HUD_TOP_LEFT = 34; public const int ATTACH_HUD_CENTER_1 = 35; public const int ATTACH_HUD_BOTTOM_LEFT = 36; public const int ATTACH_HUD_BOTTOM = 37; public const int ATTACH_HUD_BOTTOM_RIGHT = 38; public const int ATTACH_NECK = 39; public const int ATTACH_AVATAR_CENTER = 40; #region osMessageAttachments constants /// <summary> /// Instructs osMessageAttachements to send the message to attachments /// on every point. /// </summary> /// <remarks> /// One might expect this to be named OS_ATTACH_ALL, but then one might /// also expect functions designed to attach or detach or get /// attachments to work with it too. Attaching a no-copy item to /// many attachments could be dangerous. /// when combined with OS_ATTACH_MSG_INVERT_POINTS, will prevent the /// message from being sent. /// if combined with OS_ATTACH_MSG_OBJECT_CREATOR or /// OS_ATTACH_MSG_SCRIPT_CREATOR, could result in no message being /// sent- this is expected behaviour. /// </remarks> public const int OS_ATTACH_MSG_ALL = -65535; /// <summary> /// Instructs osMessageAttachements to invert how the attachment points /// list should be treated (e.g. go from inclusive operation to /// exclusive operation). /// </summary> /// <remarks> /// This might be used if you want to deliver a message to one set of /// attachments and a different message to everything else. With /// this flag, you only need to build one explicit list for both calls. /// </remarks> public const int OS_ATTACH_MSG_INVERT_POINTS = 1; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the host object CreatorID /// </summary> /// <remarks> /// This would be used if distributed in an object vendor/updater server. /// </remarks> public const int OS_ATTACH_MSG_OBJECT_CREATOR = 2; /// <summary> /// Instructs osMessageAttachments to only send the message to /// attachments with a CreatorID that matches the sending script CreatorID /// </summary> /// <remarks> /// This might be used if the script is distributed independently of a /// containing object. /// </remarks> public const int OS_ATTACH_MSG_SCRIPT_CREATOR = 4; #endregion public const int LAND_LEVEL = 0; public const int LAND_RAISE = 1; public const int LAND_LOWER = 2; public const int LAND_SMOOTH = 3; public const int LAND_NOISE = 4; public const int LAND_REVERT = 5; public const int LAND_SMALL_BRUSH = 1; public const int LAND_MEDIUM_BRUSH = 2; public const int LAND_LARGE_BRUSH = 3; //Agent Dataserver public const int DATA_ONLINE = 1; public const int DATA_NAME = 2; public const int DATA_BORN = 3; public const int DATA_RATING = 4; public const int DATA_SIM_POS = 5; public const int DATA_SIM_STATUS = 6; public const int DATA_SIM_RATING = 7; public const int DATA_PAYINFO = 8; public const int DATA_SIM_RELEASE = 128; public const int ANIM_ON = 1; public const int LOOP = 2; public const int REVERSE = 4; public const int PING_PONG = 8; public const int SMOOTH = 16; public const int ROTATE = 32; public const int SCALE = 64; public const int ALL_SIDES = -1; public const int LINK_SET = -1; public const int LINK_ROOT = 1; public const int LINK_ALL_OTHERS = -2; public const int LINK_ALL_CHILDREN = -3; public const int LINK_THIS = -4; public const int CHANGED_INVENTORY = 1; public const int CHANGED_COLOR = 2; public const int CHANGED_SHAPE = 4; public const int CHANGED_SCALE = 8; public const int CHANGED_TEXTURE = 16; public const int CHANGED_LINK = 32; public const int CHANGED_ALLOWED_DROP = 64; public const int CHANGED_OWNER = 128; public const int CHANGED_REGION = 256; public const int CHANGED_TELEPORT = 512; public const int CHANGED_REGION_RESTART = 1024; public const int CHANGED_REGION_START = 1024; //LL Changed the constant from CHANGED_REGION_RESTART public const int CHANGED_MEDIA = 2048; public const int CHANGED_ANIMATION = 16384; public const int TYPE_INVALID = 0; public const int TYPE_INTEGER = 1; public const int TYPE_FLOAT = 2; public const int TYPE_STRING = 3; public const int TYPE_KEY = 4; public const int TYPE_VECTOR = 5; public const int TYPE_ROTATION = 6; //XML RPC Remote Data Channel public const int REMOTE_DATA_CHANNEL = 1; public const int REMOTE_DATA_REQUEST = 2; public const int REMOTE_DATA_REPLY = 3; //llHTTPRequest public const int HTTP_METHOD = 0; public const int HTTP_MIMETYPE = 1; public const int HTTP_BODY_MAXLENGTH = 2; public const int HTTP_VERIFY_CERT = 3; public const int HTTP_VERBOSE_THROTTLE = 4; public const int HTTP_CUSTOM_HEADER = 5; public const int HTTP_PRAGMA_NO_CACHE = 6; // llSetContentType public const int CONTENT_TYPE_TEXT = 0; //text/plain public const int CONTENT_TYPE_HTML = 1; //text/html public const int CONTENT_TYPE_XML = 2; //application/xml public const int CONTENT_TYPE_XHTML = 3; //application/xhtml+xml public const int CONTENT_TYPE_ATOM = 4; //application/atom+xml public const int CONTENT_TYPE_JSON = 5; //application/json public const int CONTENT_TYPE_LLSD = 6; //application/llsd+xml public const int CONTENT_TYPE_FORM = 7; //application/x-www-form-urlencoded public const int CONTENT_TYPE_RSS = 8; //application/rss+xml public const int PRIM_MATERIAL = 2; public const int PRIM_PHYSICS = 3; public const int PRIM_TEMP_ON_REZ = 4; public const int PRIM_PHANTOM = 5; public const int PRIM_POSITION = 6; public const int PRIM_SIZE = 7; public const int PRIM_ROTATION = 8; public const int PRIM_TYPE = 9; public const int PRIM_TEXTURE = 17; public const int PRIM_COLOR = 18; public const int PRIM_BUMP_SHINY = 19; public const int PRIM_FULLBRIGHT = 20; public const int PRIM_FLEXIBLE = 21; public const int PRIM_TEXGEN = 22; public const int PRIM_CAST_SHADOWS = 24; // Not implemented, here for completeness sake public const int PRIM_POINT_LIGHT = 23; // Huh? public const int PRIM_GLOW = 25; public const int PRIM_TEXT = 26; public const int PRIM_NAME = 27; public const int PRIM_DESC = 28; public const int PRIM_ROT_LOCAL = 29; public const int PRIM_OMEGA = 32; public const int PRIM_POS_LOCAL = 33; public const int PRIM_LINK_TARGET = 34; public const int PRIM_SLICE = 35; public const int PRIM_SPECULAR = 36; public const int PRIM_NORMAL = 37; public const int PRIM_ALPHA_MODE = 38; public const int PRIM_TEXGEN_DEFAULT = 0; public const int PRIM_TEXGEN_PLANAR = 1; public const int PRIM_TYPE_BOX = 0; public const int PRIM_TYPE_CYLINDER = 1; public const int PRIM_TYPE_PRISM = 2; public const int PRIM_TYPE_SPHERE = 3; public const int PRIM_TYPE_TORUS = 4; public const int PRIM_TYPE_TUBE = 5; public const int PRIM_TYPE_RING = 6; public const int PRIM_TYPE_SCULPT = 7; public const int PRIM_HOLE_DEFAULT = 0; public const int PRIM_HOLE_CIRCLE = 16; public const int PRIM_HOLE_SQUARE = 32; public const int PRIM_HOLE_TRIANGLE = 48; public const int PRIM_MATERIAL_STONE = 0; public const int PRIM_MATERIAL_METAL = 1; public const int PRIM_MATERIAL_GLASS = 2; public const int PRIM_MATERIAL_WOOD = 3; public const int PRIM_MATERIAL_FLESH = 4; public const int PRIM_MATERIAL_PLASTIC = 5; public const int PRIM_MATERIAL_RUBBER = 6; public const int PRIM_MATERIAL_LIGHT = 7; public const int PRIM_SHINY_NONE = 0; public const int PRIM_SHINY_LOW = 1; public const int PRIM_SHINY_MEDIUM = 2; public const int PRIM_SHINY_HIGH = 3; public const int PRIM_BUMP_NONE = 0; public const int PRIM_BUMP_BRIGHT = 1; public const int PRIM_BUMP_DARK = 2; public const int PRIM_BUMP_WOOD = 3; public const int PRIM_BUMP_BARK = 4; public const int PRIM_BUMP_BRICKS = 5; public const int PRIM_BUMP_CHECKER = 6; public const int PRIM_BUMP_CONCRETE = 7; public const int PRIM_BUMP_TILE = 8; public const int PRIM_BUMP_STONE = 9; public const int PRIM_BUMP_DISKS = 10; public const int PRIM_BUMP_GRAVEL = 11; public const int PRIM_BUMP_BLOBS = 12; public const int PRIM_BUMP_SIDING = 13; public const int PRIM_BUMP_LARGETILE = 14; public const int PRIM_BUMP_STUCCO = 15; public const int PRIM_BUMP_SUCTION = 16; public const int PRIM_BUMP_WEAVE = 17; public const int PRIM_SCULPT_TYPE_SPHERE = 1; public const int PRIM_SCULPT_TYPE_TORUS = 2; public const int PRIM_SCULPT_TYPE_PLANE = 3; public const int PRIM_SCULPT_TYPE_CYLINDER = 4; public const int PRIM_SCULPT_FLAG_INVERT = 64; public const int PRIM_SCULPT_FLAG_MIRROR = 128; public const int PROFILE_NONE = 0; public const int PROFILE_SCRIPT_MEMORY = 1; public const int MASK_BASE = 0; public const int MASK_OWNER = 1; public const int MASK_GROUP = 2; public const int MASK_EVERYONE = 3; public const int MASK_NEXT = 4; public const int PERM_TRANSFER = 8192; public const int PERM_MODIFY = 16384; public const int PERM_COPY = 32768; public const int PERM_MOVE = 524288; public const int PERM_ALL = 2147483647; public const int PARCEL_MEDIA_COMMAND_STOP = 0; public const int PARCEL_MEDIA_COMMAND_PAUSE = 1; public const int PARCEL_MEDIA_COMMAND_PLAY = 2; public const int PARCEL_MEDIA_COMMAND_LOOP = 3; public const int PARCEL_MEDIA_COMMAND_TEXTURE = 4; public const int PARCEL_MEDIA_COMMAND_URL = 5; public const int PARCEL_MEDIA_COMMAND_TIME = 6; public const int PARCEL_MEDIA_COMMAND_AGENT = 7; public const int PARCEL_MEDIA_COMMAND_UNLOAD = 8; public const int PARCEL_MEDIA_COMMAND_AUTO_ALIGN = 9; public const int PARCEL_MEDIA_COMMAND_TYPE = 10; public const int PARCEL_MEDIA_COMMAND_SIZE = 11; public const int PARCEL_MEDIA_COMMAND_DESC = 12; public const int PARCEL_FLAG_ALLOW_FLY = 0x1; // parcel allows flying public const int PARCEL_FLAG_ALLOW_SCRIPTS = 0x2; // parcel allows outside scripts public const int PARCEL_FLAG_ALLOW_LANDMARK = 0x8; // parcel allows landmarks to be created public const int PARCEL_FLAG_ALLOW_TERRAFORM = 0x10; // parcel allows anyone to terraform the land public const int PARCEL_FLAG_ALLOW_DAMAGE = 0x20; // parcel allows damage public const int PARCEL_FLAG_ALLOW_CREATE_OBJECTS = 0x40; // parcel allows anyone to create objects public const int PARCEL_FLAG_USE_ACCESS_GROUP = 0x100; // parcel limits access to a group public const int PARCEL_FLAG_USE_ACCESS_LIST = 0x200; // parcel limits access to a list of residents public const int PARCEL_FLAG_USE_BAN_LIST = 0x400; // parcel uses a ban list, including restricting access based on payment info public const int PARCEL_FLAG_USE_LAND_PASS_LIST = 0x800; // parcel allows passes to be purchased public const int PARCEL_FLAG_LOCAL_SOUND_ONLY = 0x8000; // parcel restricts spatialized sound to the parcel public const int PARCEL_FLAG_RESTRICT_PUSHOBJECT = 0x200000; // parcel restricts llPushObject public const int PARCEL_FLAG_ALLOW_GROUP_SCRIPTS = 0x2000000; // parcel allows scripts owned by group public const int PARCEL_FLAG_ALLOW_CREATE_GROUP_OBJECTS = 0x4000000; // parcel allows group object creation public const int PARCEL_FLAG_ALLOW_ALL_OBJECT_ENTRY = 0x8000000; // parcel allows objects owned by any user to enter public const int PARCEL_FLAG_ALLOW_GROUP_OBJECT_ENTRY = 0x10000000; // parcel allows with the same group to enter public const int REGION_FLAG_ALLOW_DAMAGE = 0x1; // region is entirely damage enabled public const int REGION_FLAG_FIXED_SUN = 0x10; // region has a fixed sun position public const int REGION_FLAG_BLOCK_TERRAFORM = 0x40; // region terraforming disabled public const int REGION_FLAG_SANDBOX = 0x100; // region is a sandbox public const int REGION_FLAG_DISABLE_COLLISIONS = 0x1000; // region has disabled collisions public const int REGION_FLAG_DISABLE_PHYSICS = 0x4000; // region has disabled physics public const int REGION_FLAG_BLOCK_FLY = 0x80000; // region blocks flying public const int REGION_FLAG_ALLOW_DIRECT_TELEPORT = 0x100000; // region allows direct teleports public const int REGION_FLAG_RESTRICT_PUSHOBJECT = 0x400000; // region restricts llPushObject //llManageEstateAccess public const int ESTATE_ACCESS_ALLOWED_AGENT_ADD = 0; public const int ESTATE_ACCESS_ALLOWED_AGENT_REMOVE = 1; public const int ESTATE_ACCESS_ALLOWED_GROUP_ADD = 2; public const int ESTATE_ACCESS_ALLOWED_GROUP_REMOVE = 3; public const int ESTATE_ACCESS_BANNED_AGENT_ADD = 4; public const int ESTATE_ACCESS_BANNED_AGENT_REMOVE = 5; public static readonly LSLInteger PAY_HIDE = new LSLInteger(-1); public static readonly LSLInteger PAY_DEFAULT = new LSLInteger(-2); public const string NULL_KEY = "00000000-0000-0000-0000-000000000000"; public const string EOF = "\n\n\n"; public const double PI = 3.14159274f; public const double TWO_PI = 6.28318548f; public const double PI_BY_TWO = 1.57079637f; public const double DEG_TO_RAD = 0.01745329238f; public const double RAD_TO_DEG = 57.29578f; public const double SQRT2 = 1.414213538f; public const int STRING_TRIM_HEAD = 1; public const int STRING_TRIM_TAIL = 2; public const int STRING_TRIM = 3; public const int LIST_STAT_RANGE = 0; public const int LIST_STAT_MIN = 1; public const int LIST_STAT_MAX = 2; public const int LIST_STAT_MEAN = 3; public const int LIST_STAT_MEDIAN = 4; public const int LIST_STAT_STD_DEV = 5; public const int LIST_STAT_SUM = 6; public const int LIST_STAT_SUM_SQUARES = 7; public const int LIST_STAT_NUM_COUNT = 8; public const int LIST_STAT_GEOMETRIC_MEAN = 9; public const int LIST_STAT_HARMONIC_MEAN = 100; //ParcelPrim Categories public const int PARCEL_COUNT_TOTAL = 0; public const int PARCEL_COUNT_OWNER = 1; public const int PARCEL_COUNT_GROUP = 2; public const int PARCEL_COUNT_OTHER = 3; public const int PARCEL_COUNT_SELECTED = 4; public const int PARCEL_COUNT_TEMP = 5; public const int DEBUG_CHANNEL = 0x7FFFFFFF; public const int PUBLIC_CHANNEL = 0x00000000; // Constants for llGetObjectDetails public const int OBJECT_UNKNOWN_DETAIL = -1; public const int OBJECT_NAME = 1; public const int OBJECT_DESC = 2; public const int OBJECT_POS = 3; public const int OBJECT_ROT = 4; public const int OBJECT_VELOCITY = 5; public const int OBJECT_OWNER = 6; public const int OBJECT_GROUP = 7; public const int OBJECT_CREATOR = 8; public const int OBJECT_RUNNING_SCRIPT_COUNT = 9; public const int OBJECT_TOTAL_SCRIPT_COUNT = 10; public const int OBJECT_SCRIPT_MEMORY = 11; public const int OBJECT_SCRIPT_TIME = 12; public const int OBJECT_PRIM_EQUIVALENCE = 13; public const int OBJECT_SERVER_COST = 14; public const int OBJECT_STREAMING_COST = 15; public const int OBJECT_PHYSICS_COST = 16; public const int OBJECT_CHARACTER_TIME = 17; public const int OBJECT_ROOT = 18; public const int OBJECT_ATTACHED_POINT = 19; public const int OBJECT_PATHFINDING_TYPE = 20; public const int OBJECT_PHYSICS = 21; public const int OBJECT_PHANTOM = 22; public const int OBJECT_TEMP_ON_REZ = 23; // Pathfinding types public const int OPT_OTHER = -1; public const int OPT_LEGACY_LINKSET = 0; public const int OPT_AVATAR = 1; public const int OPT_CHARACTER = 2; public const int OPT_WALKABLE = 3; public const int OPT_STATIC_OBSTACLE = 4; public const int OPT_MATERIAL_VOLUME = 5; public const int OPT_EXCLUSION_VOLUME = 6; // for llGetAgentList public const int AGENT_LIST_PARCEL = 1; public const int AGENT_LIST_PARCEL_OWNER = 2; public const int AGENT_LIST_REGION = 4; // Can not be public const? public static readonly vector ZERO_VECTOR = new vector(0.0, 0.0, 0.0); public static readonly rotation ZERO_ROTATION = new rotation(0.0, 0.0, 0.0, 1.0); // constants for llSetCameraParams public const int CAMERA_PITCH = 0; public const int CAMERA_FOCUS_OFFSET = 1; public const int CAMERA_FOCUS_OFFSET_X = 2; public const int CAMERA_FOCUS_OFFSET_Y = 3; public const int CAMERA_FOCUS_OFFSET_Z = 4; public const int CAMERA_POSITION_LAG = 5; public const int CAMERA_FOCUS_LAG = 6; public const int CAMERA_DISTANCE = 7; public const int CAMERA_BEHINDNESS_ANGLE = 8; public const int CAMERA_BEHINDNESS_LAG = 9; public const int CAMERA_POSITION_THRESHOLD = 10; public const int CAMERA_FOCUS_THRESHOLD = 11; public const int CAMERA_ACTIVE = 12; public const int CAMERA_POSITION = 13; public const int CAMERA_POSITION_X = 14; public const int CAMERA_POSITION_Y = 15; public const int CAMERA_POSITION_Z = 16; public const int CAMERA_FOCUS = 17; public const int CAMERA_FOCUS_X = 18; public const int CAMERA_FOCUS_Y = 19; public const int CAMERA_FOCUS_Z = 20; public const int CAMERA_POSITION_LOCKED = 21; public const int CAMERA_FOCUS_LOCKED = 22; // constants for llGetParcelDetails public const int PARCEL_DETAILS_NAME = 0; public const int PARCEL_DETAILS_DESC = 1; public const int PARCEL_DETAILS_OWNER = 2; public const int PARCEL_DETAILS_GROUP = 3; public const int PARCEL_DETAILS_AREA = 4; public const int PARCEL_DETAILS_ID = 5; public const int PARCEL_DETAILS_SEE_AVATARS = 6; // not implemented //osSetParcelDetails public const int PARCEL_DETAILS_CLAIMDATE = 10; // constants for llSetClickAction public const int CLICK_ACTION_NONE = 0; public const int CLICK_ACTION_TOUCH = 0; public const int CLICK_ACTION_SIT = 1; public const int CLICK_ACTION_BUY = 2; public const int CLICK_ACTION_PAY = 3; public const int CLICK_ACTION_OPEN = 4; public const int CLICK_ACTION_PLAY = 5; public const int CLICK_ACTION_OPEN_MEDIA = 6; public const int CLICK_ACTION_ZOOM = 7; // constants for the llDetectedTouch* functions public const int TOUCH_INVALID_FACE = -1; public static readonly vector TOUCH_INVALID_TEXCOORD = new vector(-1.0, -1.0, 0.0); public static readonly vector TOUCH_INVALID_VECTOR = ZERO_VECTOR; // constants for llGetPrimMediaParams/llSetPrimMediaParams public const int PRIM_MEDIA_ALT_IMAGE_ENABLE = 0; public const int PRIM_MEDIA_CONTROLS = 1; public const int PRIM_MEDIA_CURRENT_URL = 2; public const int PRIM_MEDIA_HOME_URL = 3; public const int PRIM_MEDIA_AUTO_LOOP = 4; public const int PRIM_MEDIA_AUTO_PLAY = 5; public const int PRIM_MEDIA_AUTO_SCALE = 6; public const int PRIM_MEDIA_AUTO_ZOOM = 7; public const int PRIM_MEDIA_FIRST_CLICK_INTERACT = 8; public const int PRIM_MEDIA_WIDTH_PIXELS = 9; public const int PRIM_MEDIA_HEIGHT_PIXELS = 10; public const int PRIM_MEDIA_WHITELIST_ENABLE = 11; public const int PRIM_MEDIA_WHITELIST = 12; public const int PRIM_MEDIA_PERMS_INTERACT = 13; public const int PRIM_MEDIA_PERMS_CONTROL = 14; public const int PRIM_MEDIA_CONTROLS_STANDARD = 0; public const int PRIM_MEDIA_CONTROLS_MINI = 1; public const int PRIM_MEDIA_PERM_NONE = 0; public const int PRIM_MEDIA_PERM_OWNER = 1; public const int PRIM_MEDIA_PERM_GROUP = 2; public const int PRIM_MEDIA_PERM_ANYONE = 4; public const int PRIM_PHYSICS_SHAPE_TYPE = 30; public const int PRIM_PHYSICS_SHAPE_PRIM = 0; public const int PRIM_PHYSICS_SHAPE_CONVEX = 2; public const int PRIM_PHYSICS_SHAPE_NONE = 1; public const int PRIM_PHYSICS_MATERIAL = 31; public const int DENSITY = 1; public const int FRICTION = 2; public const int RESTITUTION = 4; public const int GRAVITY_MULTIPLIER = 8; // extra constants for llSetPrimMediaParams public static readonly LSLInteger LSL_STATUS_OK = new LSLInteger(0); public static readonly LSLInteger LSL_STATUS_MALFORMED_PARAMS = new LSLInteger(1000); public static readonly LSLInteger LSL_STATUS_TYPE_MISMATCH = new LSLInteger(1001); public static readonly LSLInteger LSL_STATUS_BOUNDS_ERROR = new LSLInteger(1002); public static readonly LSLInteger LSL_STATUS_NOT_FOUND = new LSLInteger(1003); public static readonly LSLInteger LSL_STATUS_NOT_SUPPORTED = new LSLInteger(1004); public static readonly LSLInteger LSL_STATUS_INTERNAL_ERROR = new LSLInteger(1999); public static readonly LSLInteger LSL_STATUS_WHITELIST_FAILED = new LSLInteger(2001); // Constants for default textures public const string TEXTURE_BLANK = "5748decc-f629-461c-9a36-a35a221fe21f"; public const string TEXTURE_DEFAULT = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_PLYWOOD = "89556747-24cb-43ed-920b-47caed15465f"; public const string TEXTURE_TRANSPARENT = "8dcd4a48-2d37-4909-9f78-f7a9eb4ef903"; public const string TEXTURE_MEDIA = "8b5fec65-8d8d-9dc5-cda8-8fdf2716e361"; // Constants for osGetRegionStats public const int STATS_TIME_DILATION = 0; public const int STATS_SIM_FPS = 1; public const int STATS_PHYSICS_FPS = 2; public const int STATS_AGENT_UPDATES = 3; public const int STATS_ROOT_AGENTS = 4; public const int STATS_CHILD_AGENTS = 5; public const int STATS_TOTAL_PRIMS = 6; public const int STATS_ACTIVE_PRIMS = 7; public const int STATS_FRAME_MS = 8; public const int STATS_NET_MS = 9; public const int STATS_PHYSICS_MS = 10; public const int STATS_IMAGE_MS = 11; public const int STATS_OTHER_MS = 12; public const int STATS_IN_PACKETS_PER_SECOND = 13; public const int STATS_OUT_PACKETS_PER_SECOND = 14; public const int STATS_UNACKED_BYTES = 15; public const int STATS_AGENT_MS = 16; public const int STATS_PENDING_DOWNLOADS = 17; public const int STATS_PENDING_UPLOADS = 18; public const int STATS_ACTIVE_SCRIPTS = 19; public const int STATS_SCRIPT_LPS = 20; // Constants for osNpc* functions public const int OS_NPC_FLY = 0; public const int OS_NPC_NO_FLY = 1; public const int OS_NPC_LAND_AT_TARGET = 2; public const int OS_NPC_RUNNING = 4; public const int OS_NPC_SIT_NOW = 0; public const int OS_NPC_CREATOR_OWNED = 0x1; public const int OS_NPC_NOT_OWNED = 0x2; public const int OS_NPC_SENSE_AS_AGENT = 0x4; public const string URL_REQUEST_GRANTED = "URL_REQUEST_GRANTED"; public const string URL_REQUEST_DENIED = "URL_REQUEST_DENIED"; public static readonly LSLInteger RC_REJECT_TYPES = 0; public static readonly LSLInteger RC_DETECT_PHANTOM = 1; public static readonly LSLInteger RC_DATA_FLAGS = 2; public static readonly LSLInteger RC_MAX_HITS = 3; public static readonly LSLInteger RC_REJECT_AGENTS = 1; public static readonly LSLInteger RC_REJECT_PHYSICAL = 2; public static readonly LSLInteger RC_REJECT_NONPHYSICAL = 4; public static readonly LSLInteger RC_REJECT_LAND = 8; public static readonly LSLInteger RC_GET_NORMAL = 1; public static readonly LSLInteger RC_GET_ROOT_KEY = 2; public static readonly LSLInteger RC_GET_LINK_NUM = 4; public static readonly LSLInteger RCERR_UNKNOWN = -1; public static readonly LSLInteger RCERR_SIM_PERF_LOW = -2; public static readonly LSLInteger RCERR_CAST_TIME_EXCEEDED = 3; public const int KFM_MODE = 1; public const int KFM_LOOP = 1; public const int KFM_REVERSE = 3; public const int KFM_FORWARD = 0; public const int KFM_PING_PONG = 2; public const int KFM_DATA = 2; public const int KFM_TRANSLATION = 2; public const int KFM_ROTATION = 1; public const int KFM_COMMAND = 0; public const int KFM_CMD_PLAY = 0; public const int KFM_CMD_STOP = 1; public const int KFM_CMD_PAUSE = 2; /// <summary> /// process name parameter as regex /// </summary> public const int OS_LISTEN_REGEX_NAME = 0x1; /// <summary> /// process message parameter as regex /// </summary> public const int OS_LISTEN_REGEX_MESSAGE = 0x2; } }
/* ==================================================================== Licensed to the 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. ==================================================================== */ /* ================================================================ * About NPOI * Author: Tony Qu * Author's email: tonyqus (at) gmail.com * Author's Blog: tonyqus.wordpress.com.cn (wp.tonyqus.cn) * HomePage: http://www.codeplex.com/npoi * Contributors: * * ==============================================================*/ using System; using System.IO; using System.Collections; using NUnit.Framework; using NStorage.Storage; using NStorage.Utility; using NStorage.FileSystem; using NStorage.Test.POIFS.FileSystem; using NStorage.Test.Utility; namespace NStorage.Test.POIFS.Storage { /** * Class to Test RawDataBlock functionality * * @author Marc Johnson */ [TestFixture] public class TestRawDataBlock { public TestRawDataBlock() { } /** * Test creating a normal RawDataBlock * * @exception IOException */ [Test] public void TestNormalConstructor() { byte[] data = new byte[512]; for (int j = 0; j < 512; j++) { data[j] = (byte)j; } RawDataBlock block = new RawDataBlock(new MemoryStream(data)); Assert.IsTrue(!block.EOF, "Should not be at EOF"); byte[] out_data = block.Data; Assert.AreEqual(data.Length, out_data.Length, "Should be same Length"); for (int j = 0; j < 512; j++) { Assert.AreEqual(data[j], out_data[j], "Should be same value at offset " + j); } } /** * Test creating an empty RawDataBlock * * @exception IOException */ [Test] public void TestEmptyConstructor() { byte[] data = new byte[0]; RawDataBlock block = new RawDataBlock(new MemoryStream(data)); Assert.IsTrue(block.EOF, "Should be at EOF"); try { byte[] a = block.Data; } catch (IOException ) { // as expected } } /** * Test creating a short RawDataBlock * Will trigger a warning, but no longer an IOException, * as people seem to have "valid" truncated files */ [Test] public void TestShortConstructor() { //// Get the logger to be used DummyPOILogger logger = (DummyPOILogger)POILogFactory.GetLogger(typeof(RawDataBlock)); logger.Reset(); // the logger may have been used before Assert.AreEqual(0, logger.logged.Count); // Test for various data sizes for (int k = 1; k <= 512; k++) { byte[] data = new byte[k]; for (int j = 0; j < k; j++) { data[j] = (byte)j; } RawDataBlock block = null; logger.Reset(); Assert.AreEqual(0, logger.logged.Count); // Have it created block = new RawDataBlock(new MemoryStream(data)); Assert.IsNotNull(block); // Check for the warning Is there for <512 if (k < 512) { Assert.AreEqual( 1, logger.logged.Count, "Warning on " + k + " byte short block" ); // Build the expected warning message, and check String bts = k + " byte"; if (k > 1) { bts += "s"; } Assert.AreEqual( (String)logger.logged[0], "7 - Unable to read entire block; " + bts + " read before EOF; expected 512 bytes. Your document was either written by software that ignores the spec, or has been truncated!" ); } else { Assert.AreEqual(0, logger.logged.Count); } } } /** * Tests that when using a slow input stream, which * won't return a full block at a time, we don't * incorrectly think that there's not enough data */ [Test] public void TestSlowInputStream() { // Get the logger to be used DummyPOILogger logger = (DummyPOILogger)POILogFactory.GetLogger(typeof(RawDataBlock)); logger.Reset(); // the logger may have been used before Assert.AreEqual(0, logger.logged.Count); // Test for various ok data sizes for (int k = 1; k < 512; k++) { byte[] data = new byte[512]; for (int j = 0; j < data.Length; j++) { data[j] = (byte)j; } // Shouldn't complain, as there Is enough data, // even if it dribbles through RawDataBlock block = new RawDataBlock(new SlowInputStream(data, 512)); //k is changed to 512 Assert.IsFalse(block.EOF); } // But if there wasn't enough data available, will // complain for (int k = 1; k < 512; k++) { byte[] data = new byte[511]; for (int j = 0; j < data.Length; j++) { data[j] = (byte)j; } logger.Reset(); Assert.AreEqual(0, logger.logged.Count); // Should complain, as there Isn't enough data RawDataBlock block = new RawDataBlock(new SlowInputStream(data, k)); Assert.IsNotNull(block); Assert.AreEqual( 1, logger.logged.Count, "Warning on " + k + " byte short block" ); } } } }
using NUnit.Framework; using System; using GameTimer; using Microsoft.Xna.Framework; namespace GameTimer.Tests { [TestFixture()] public class GameClockTests { #region Setup GameClock test; [SetUp()] public void Setup() { test = new GameClock(); } #endregion //Setup #region Defaults [Test()] public void DefaultCurrentTime() { Assert.AreEqual(0.0f, test.CurrentTime); } [Test()] public void DefaultCurrentTime1() { Assert.AreEqual(0.0f, test.GetCurrentTime()); } [Test()] public void DefaultTimeDelta() { Assert.AreEqual(0.0f, test.TimeDelta); } [Test()] public void DefaultPause() { Assert.AreEqual(false, test.Paused); } [Test()] public void DefaultTimerSpeed() { Assert.AreEqual(1.0f, test.TimerSpeed); } #endregion //Defaults #region Start Tests [Test()] public void StartCurrentTime() { test.CurrentTime = 1.0f; test.Start(); Assert.AreEqual(0.0f, test.CurrentTime); } [Test()] public void StartCurrentTime1() { test.CurrentTime = 1.0f; test.Start(); Assert.AreEqual(0.0f, test.GetCurrentTime()); } [Test()] public void StartTimeDelta() { test.TimeDelta = 1.0f; test.Start(); Assert.AreEqual(1.0f, test.TimeDelta); } [Test()] public void StartPause() { test.Paused = true; test.Start(); Assert.AreEqual(false, test.Paused); } [Test()] public void StartTimerSpeed() { test.TimerSpeed = 2.0f; test.Start(); Assert.AreEqual(2.0f, test.TimerSpeed); } #endregion //Defaults #region Frames [Test()] public void FramesToSeconds() { Assert.AreEqual(1.0f, GameClock.FramesToSeconds(60)); Assert.AreEqual(0.5f, GameClock.FramesToSeconds(30)); Assert.AreEqual(2.0f, GameClock.FramesToSeconds(120)); } [Test()] public void SecondsToFrames() { Assert.AreEqual(60, GameClock.SecondsToFrames(1.0f)); Assert.AreEqual(30, GameClock.SecondsToFrames(0.5f)); Assert.AreEqual(120, GameClock.SecondsToFrames(2.0f)); } #endregion Frames #region String methods [Test()] public void TwoHours() { Assert.AreEqual("2:00:00", GameClock.ToTimeString(7200.0f)); } [Test()] public void SixtyMinutes() { Assert.AreEqual("1:00:00", GameClock.ToTimeString(3600.0f)); } [Test()] public void ThirtyMinutes() { Assert.AreEqual("30:00", GameClock.ToTimeString(1800.0f)); } [Test()] public void SixtyOneMinutes() { Assert.AreEqual("31:00", GameClock.ToTimeString(1860.0f)); } [Test()] public void SixtySeconds() { Assert.AreEqual("1:00", GameClock.ToTimeString(60.0f)); } [Test()] public void SixtyOneSeconds() { Assert.AreEqual("1:01", GameClock.ToTimeString(61.0f)); } [Test()] public void ThirtySeconds() { Assert.AreEqual("0:30", GameClock.ToTimeString(30.0f)); } [Test()] public void FiveSeconds() { Assert.AreEqual("0:05", GameClock.ToTimeString(5.0f)); } [Test()] public void TwelveHoursThirtyFourMinutesFiftySixSeconds() { Assert.AreEqual("12:34:56", GameClock.ToTimeString(43200.0f + 2040.0f + 56.0f)); } [Test()] public void GameClockToString() { test.CurrentTime = (43200.0f + 2040.0f + 56.0f); Assert.AreEqual("12:34:56", test.ToString()); } #endregion //String methods #region Update from gametimer [Test()] public void UpdateFromGameTimerCurrent() { GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); Assert.AreEqual(0.5f, test.CurrentTime); } [Test()] public void UpdateFromGameTimerCurrent1() { GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); Assert.AreEqual(0.5f, test.GetCurrentTime()); } [Test()] public void UpdateFromGameTimerDelta() { GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); Assert.AreEqual(0.5f, test.TimeDelta); } [Test()] public void UpdateFromGameTimerCurrentMultiple() { GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); test.Update(test2); Assert.AreEqual(1.0f, test.CurrentTime); } [Test()] public void UpdateFromGameTimerDeltaMultiple() { GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); test.Update(test2); Assert.AreEqual(0.5f, test.TimeDelta); } [Test()] public void UpdateFromGameTimerPaused() { test.Paused = true; GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); test.Update(test2); Assert.AreEqual(0.0f, test.CurrentTime); } [Test()] public void UpdateFromGameTimerPaused1() { GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); test.Paused = true; test.Update(test2); Assert.AreEqual(0.5f, test.CurrentTime); } [Test()] public void UpdateFromGameTimerFast() { test.TimerSpeed = 2.0f; GameClock test2 = new GameClock(); test2.TimeDelta = 0.5f; test.Update(test2); Assert.AreEqual(1.0f, test.TimeDelta); } #endregion //Update from gametimer } }
// 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.Reflection; using System.Runtime.Remoting; using Alachisoft.NCache.Common.Remoting; namespace Alachisoft.NCache.Management { [CLSCompliant(false)] public class HostBase :IDisposable { protected MarshalByRefObject _remoteableObject; protected RemotingChannels _channel = new RemotingChannels(); protected static string _appName = "NCacheExpress"; protected string _url; /// <summary> /// Overloaded constructor. /// </summary> /// <param name="application"></param> static HostBase() { try { RemotingConfiguration.ApplicationName = _appName; } catch (Exception) { } } public HostBase(MarshalByRefObject remoteableObject,string url) { _remoteableObject = remoteableObject; _url = url; } /// <summary> </summary> public RemotingChannels Channels { get { return _channel; } } /// <summary> Returns the application name of this session. </summary> static public string ApplicationName { get { return _appName; } } protected virtual int GetHttpPort() { return 0; } protected virtual int GetTcpPort() { return 0; } /// <summary> /// Set things in motion so your service can do its work. /// </summary> public void StartHosting(string tcpChannel, string httpChannel) { StartHosting(tcpChannel, GetTcpPort(), httpChannel, GetHttpPort()); } /// <summary> /// Set things in motion so your service can do its work. /// </summary> public void StartHosting(string tcpChannel, string httpChannel, string ip) { StartHosting(tcpChannel, GetTcpPort(), httpChannel, GetHttpPort(), ip); } public void StartHosting(string tcpChannel, string ip, int port) { StartHosting(tcpChannel, port, ip); } public void StartHosting(string tcpChannel, int tcpPort, string ip) { _channel.RegisterTcpChannels(tcpChannel, ip, tcpPort); //muds: //assign the bindtoclusterip to cacheserver.clusterip if (_remoteableObject is CacheServer) ((CacheServer)_remoteableObject).ClusterIP = ip; RemotingServices.Marshal(_remoteableObject, _url); } /// <summary> /// Set things in motion so your service can do its work. /// </summary> public void StartHosting(string tcpChannel, int tcpPort, string httpChannel, int httpPort, string ip) { try { _channel.RegisterTcpChannels(tcpChannel, ip, tcpPort); _channel.RegisterHttpChannels(httpChannel, ip, httpPort); Assembly remoting = Assembly.GetAssembly(typeof(System.Runtime.Remoting.RemotingConfiguration)); //muds: //assign the bindtoclusterip to cacheserver.clusterip if (_remoteableObject is CacheServer) ((CacheServer)_remoteableObject).ClusterIP = ip; RemotingServices.Marshal(_remoteableObject, _url); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; } catch (Exception) { throw; } } /// <summary> /// Set things in motion so your service can do its work. /// </summary> public void StartHosting(string tcpChannel, int tcpPort, string httpChannel, int httpPort) { try { _channel.RegisterTcpChannels(tcpChannel, tcpPort); _channel.RegisterHttpChannels(httpChannel, httpPort); RemotingServices.Marshal(_remoteableObject, _url); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; } catch (Exception) { throw; } } /// <summary> /// Set things in motion so your service can do its work. /// </summary> private void StartHosting(string tcpChannel, int tcpPort, string httpChannel, int httpPort, int sendBuffer, int receiveBuffer) { try { _channel.RegisterTcpChannels(tcpChannel, tcpPort); _channel.RegisterHttpChannels(httpChannel, httpPort); RemotingServices.Marshal(_remoteableObject, CacheServer.ObjectUri); RemotingConfiguration.CustomErrorsMode = CustomErrorsModes.Off; } catch (Exception) { throw; } } /// <summary> /// Stop this service. /// </summary> public void StopHosting() { try { if (_remoteableObject != null) { RemotingServices.Disconnect(_remoteableObject); _channel.UnregisterTcpChannels(); _channel.UnregisterHttpChannels(); ((IDisposable)_remoteableObject).Dispose(); } } catch (Exception) { throw; } } #region / --- IDisposable --- / /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> /// <param name="disposing"></param> /// <remarks> /// </remarks> private void Dispose(bool disposing) { if (_remoteableObject != null) { ((IDisposable)_remoteableObject).Dispose(); _remoteableObject = null; if (disposing) GC.SuppressFinalize(this); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or /// resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; using Dodgeball.AI; using Dodgeball.Entities; using FlatRedBall; using FlatRedBall.Input; using FlatRedBall.Instructions; using FlatRedBall.AI.Pathfinding; using FlatRedBall.Graphics.Animation; using FlatRedBall.Graphics.Particle; using FlatRedBall.Math.Geometry; using FlatRedBall.Localization; using Microsoft.Xna.Framework; using Dodgeball.DataRuntime; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Input; using RenderingLibrary; using Dodgeball.GumRuntimes; using Dodgeball.Components; namespace Dodgeball.Screens { public partial class GameScreen { #region Fields/Properties private SoundEffectInstance playerHitSound; private SoundEffectInstance playerCatchSound; private float PlayAreaTop => -WorldComponentInstance.PlayArea.Y + (FlatRedBall.Camera.Main.OrthogonalHeight/2); private float PlayAreaBottom => PlayAreaTop - WorldComponentInstance.PlayArea.Height; private float PlayAreaLeft = -1920 / 2.0f; private float PlayAreaRight = 1920 / 2.0f; OptionsSelectionLogic optionsSelectionLogic; #endregion #region Initialize void CustomInitialize() { InitializeSounds(); ShareReferences(); InitializePlayerEvents(); PositionPlayers(); AssignAIControllers(); InitializeInput(); InitializeUi(); } private void InitializeUi() { // moves this above the health bars: this.WrapUpComponentInstance.Z = 3; var playAgainButton = WrapUpComponentInstance.GetGraphicalUiElementByName("PlayAgainButton") as TextButtonRuntime; var quitButton = WrapUpComponentInstance.GetGraphicalUiElementByName("QuitButton") as TextButtonRuntime; optionsSelectionLogic = new OptionsSelectionLogic(playAgainButton, quitButton); } private void InitializeSounds() { playerHitSound = GlobalContent.player_hit_0.CreateInstance(); playerCatchSound = GlobalContent.player_catch.CreateInstance(); } private void PositionPlayers() { var team1 = PlayerList.Where(item => item.TeamIndex == 0).ToArray(); var team2 = PlayerList.Where(item => item.TeamIndex == 1).ToArray(); var top = PlayAreaTop - PlayerList[0].CircleInstance.Radius; var bottom = PlayAreaBottom + PlayerList[0].CircleInstance.Radius; var distanceBetween = (top - bottom) / 3.0f; for (int i = 0; i < team1.Length; i++) { team1[i].X = PlayAreaLeft; team1[i].Y = top - distanceBetween * i; } for (int i = 0; i < team2.Length; i++) { team2[i].X = PlayAreaRight; team2[i].Y = top - distanceBetween * i; } } private void AssignAIControllers() { foreach (var player in this.PlayerList) { player.InitializeAIControl(); } } private void ShareReferences() { foreach(var player in this.PlayerList) { player.AllPlayers = PlayerList; player.WorldComponent = WorldComponentInstance; player.Ball = BallInstance; player.MoveUiTo(UILayer, UILayerGum); } } private void InitializeInput() { if(InputManager.NumberOfConnectedGamePads != 0) { bool hasAnyAssigned = GlobalData.JoinStatuses.Any(item => item != JoinStatus.Undecided); if(hasAnyAssigned) { for(int i = 0; i < 4; i++) { var gamepad = InputManager.Xbox360GamePads[i]; var joinStatus = GlobalData.JoinStatuses[i]; if (joinStatus != JoinStatus.Undecided && gamepad.IsConnected) { int teamToJoin; if(joinStatus == JoinStatus.Team1) { teamToJoin = 0; } else { teamToJoin = 1; } var playerToAssign = PlayerList.First(item => item.TeamIndex == teamToJoin && item.IsAiControlled); playerToAssign.InitializeXbox360Controls(gamepad); } } } else { // didn't go through the screen to assign characters, so let's default to one control PlayerList[0].InitializeXbox360Controls(InputManager.Xbox360GamePads[0]); } } else { // no controllers connected, so just use a keyboard: Player1.InitializeKeyboardControls(); } } private void InitializePlayerEvents() { foreach(var player in PlayerList) { player.Dying += () => ShowNumberOfPlayersForTeam(player.TeamIndex); } } #endregion #region Activity void CustomActivity(bool firstTimeCalled) { SuperThrowZoomIfNecessary(); SuperHitZoomIfNecessary(); CollisionActivity(); EndGameActivity(); WrapUpComponentActivity(); PlayMusicActivity(); #if DEBUG DebugActivity(); #endif } private void WrapUpComponentActivity() { if(WrapUpComponentInstance.Visible) { optionsSelectionLogic.Activity(); if(optionsSelectionLogic.DidPushAButton) { if(optionsSelectionLogic.SelectedOption == 0) { FlatRedBall.Audio.AudioManager.StopSong(); // play again RestartScreen(reloadContent: false); } else { // go to main menu MoveToScreen(typeof(TitleScreen)); } } } } private void SuperHitZoomIfNecessary() { var superHitPlayer = PlayerList.FirstOrDefault(p => p.IsHitBySuperThrow); var shouldSuperHitZoom = superHitPlayer != null; if (shouldSuperHitZoom) { superHitPlayer.IsHitBySuperThrow = false; var superHitAnimation = superHitPlayer.TeamIndex == 0 ? SuperThrowHitInstance.Team0SuperHitAnimation : SuperThrowHitInstance.Team1SuperHitAnimation; PauseThisScreen(); GlobalContent.superThrow.Play(); SuperThrowHitInstance.SetColors(shirtColor: superHitPlayer.ShirtColor, shortsColor: superHitPlayer.ShortsColor); SuperThrowHitInstance.Visible = true; superHitAnimation.Play(); this.Call(() => { SuperThrowHitInstance.Visible = false; UnpauseThisScreen(); }).After(superHitAnimation.Length); } } private void SuperThrowZoomIfNecessary() { var superThrowPlayer = PlayerList.FirstOrDefault(p => p.IsPerformingSuperThrow); var shouldSuperThrowZoom = superThrowPlayer != null; if (shouldSuperThrowZoom) { superThrowPlayer.IsPerformingSuperThrow = false; var superThrowAnimation = superThrowPlayer.TeamIndex == 0 ? SuperThrowZoomInstance.Team0SuperThrowAnimation : SuperThrowZoomInstance.Team1SuperThrowAnimation; PauseThisScreen(); GlobalContent.superHit.Play(); SuperThrowZoomInstance.SetColors(shirtColor: superThrowPlayer.ShirtColor, shortsColor:superThrowPlayer.ShortsColor); SuperThrowZoomInstance.Visible = true; superThrowAnimation.Play(); this.Call(() => { SuperThrowZoomInstance.Visible = false; UnpauseThisScreen(); }).After(superThrowAnimation.Length); } } private void PlayMusicActivity() { bool shouldLoop = FlatRedBall.Audio.AudioManager.CurrentlyPlayingSong == null && // If the wrap component is shown, don't play again, we want it to stay quiet. !this.WrapUpComponentInstance.Visible; if (shouldLoop) { FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.dodgeball_bgm, true, true); } } #if DEBUG private void DebugActivity() { if(InputManager.Keyboard.KeyPushed(Microsoft.Xna.Framework.Input.Keys.R)) { this.RestartScreen(reloadContent: true); } } #endif private void CollisionActivity() { PlayerVsPlayerCollision(); if (BallInstance.CurrentOwnershipState != Ball.OwnershipState.Held) { BallVsPlayerCollision(); BallVsWallsCollision(); } } private void PlayerVsPlayerCollision() { // Destroys aren't being called here so we can forward-loop for (var i = 0; i < PlayerList.Count; i++) { var firstPlayer = PlayerList[i]; if(firstPlayer.IsDying == false) { for (var j = i + 1; j < PlayerList.Count; j++) { var secondPlayer = PlayerList[j]; if(secondPlayer.IsDying == false) { firstPlayer.CircleInstance.CollideAgainstBounce( secondPlayer.CircleInstance, 1, 1, 0.1f); } } } } } private void BallVsWallsCollision() { if (BallInstance.XVelocity < 0 && BallInstance.X < PlayAreaLeft + BallInstance.CircleInstance.Radius || BallInstance.XVelocity > 0 && BallInstance.X > PlayAreaRight - BallInstance.CircleInstance.Radius) { BallInstance.BounceOffWall(isLeftOrRightWall: true); } if((BallInstance.YVelocity > 0 && (BallInstance.Y - (BallInstance.CircleInstance.Radius / 2) > PlayAreaTop)) || (BallInstance.YVelocity < 0 && BallInstance.Y - BallInstance.CircleInstance.Radius < PlayAreaBottom)) { BallInstance.BounceOffWall(isLeftOrRightWall: false); } } private void BallVsPlayerCollision() { bool isAbovePlayers = BallInstance.Altitude > Player.PlayerHeight; if (isAbovePlayers == false) { if (BallInstance.CurrentOwnershipState == Entities.Ball.OwnershipState.Free) { PickUpFreeBallActivity(); } else if (BallInstance.CurrentOwnershipState == Entities.Ball.OwnershipState.Thrown) { CatchAndGetHitByBallCollisionActivity(); } // don't perform collision if the ball is being held } } private void CatchAndGetHitByBallCollisionActivity() { // reverse loop since players can be removed: for (int i = PlayerList.Count - 1; i > -1; i--) { var player = PlayerList[i]; if (BallInstance.ThrowOwner != player && player.IsDying == false && player.IsDodging == false && player.IsHit == false && player.CollideAgainst(BallInstance)) { if (player.IsAttemptingCatch && player.CatchIsEffective) { PerformCatchBallLogic(player); } else { PerformGetHitLogic(player); } } } } private void PickUpFreeBallActivity() { //Can't catch a ball you're dodging or hit var validPlayers = PlayerList.Where(player => !player.IsDodging && !player.IsHit).ToList(); foreach (var player in validPlayers) { if (player.IsDying == false && player.CollideAgainst(BallInstance)) { PerformPickupLogic(player); break; } } } private void PerformCatchBallLogic(Player playerCatchingBall) { var playerCatchPan = MathHelper.Clamp(playerCatchingBall.X / 540f, -1, 1); playerCatchSound.Pan = playerCatchPan; playerCatchSound.Play(); playerCatchingBall.CatchBall(BallInstance); TrySwitchingControlToPlayerGettingBall(playerCatchingBall); } private void PerformGetHitLogic(Entities.Player player) { //Let player react and determine if they'll take damage player.GetHitBy(BallInstance); if (!player.IsAiControlled && player.IsDying) TrySwitchingControlToAliveAIPlayer(player); //Make a hit sound var ballVelocity = BallInstance.Velocity.Length(); var maxVelocity = GameVariables.MaxThrowVelocity; var playerHitPan = MathHelper.Clamp(player.X / 540f, -1, 1); var playerHitVol = MathHelper.Clamp((ballVelocity * 2) / maxVelocity, 0.1f, 1); SetPlayerHitSoundByVelocity(ballVelocity, maxVelocity); playerHitSound.Pan = playerHitPan; playerHitSound.Volume = playerHitVol; playerHitSound.Play(); // make the ball bounce off the player: BallInstance.CollideAgainstBounce(player, 0, 1, 1); BallInstance.CurrentOwnershipState = Entities.Ball.OwnershipState.Free; } private void TrySwitchingControlToAliveAIPlayer(Player playerDying) { var eligibleAIControlledTeammate = PlayerList .FirstOrDefault(item => item.IsAiControlled == true && item.IsDying == false && item.TeamIndex == playerDying.TeamIndex); if (eligibleAIControlledTeammate != null) { playerDying.SwitchInputTo(eligibleAIControlledTeammate); } } private void SetPlayerHitSoundByVelocity(float ballVelocity, float maxVelocity) { //This is the highest numbered sound effect available in GlobalContent: 8 player_hit sounds var maxHitIndex = 8; var pctOfPossibleVelocity = ballVelocity / maxVelocity; var hitIndex = Convert.ToInt32(pctOfPossibleVelocity * maxHitIndex); var playerHitSoundName = $"player_hit_{hitIndex}"; var hitSound = GlobalContent.GetFile(playerHitSoundName) as SoundEffect; if (hitSound != null) { playerHitSound = hitSound.CreateInstance(); } } private void PerformPickupLogic(Entities.Player playerPickingUpBall) { playerPickingUpBall.PickUpBall(); TrySwitchingControlToPlayerGettingBall(playerPickingUpBall); } private void TrySwitchingControlToPlayerGettingBall(Player playerGettingBall) { if (playerGettingBall.IsAiControlled) { var eligiblePlayerControlledTeammates = PlayerList .Where(item => item.IsAiControlled == false && item.IsDying == false && item.TeamIndex == playerGettingBall.TeamIndex); var playerToSwitchInputFrom = eligiblePlayerControlledTeammates .OrderBy(item => (item.Position - playerGettingBall.Position).LengthSquared()) .FirstOrDefault(); if (playerToSwitchInputFrom != null) { playerToSwitchInputFrom.SwitchInputTo(playerGettingBall); } } } private void ShowNumberOfPlayersForTeam(int teamIndex) { string playersRemaining = "Players Remaining"; var playerCount = PlayerList.Count(item => item.TeamIndex == teamIndex && item.IsDying == false); if (playerCount == 1) { playersRemaining = "Player Remaining"; } GumRuntimes.TextRuntime textToShow = null; if(teamIndex == 0) { textToShow = PlayersRemaingTextTeam1; } else { textToShow = PlayersRemaingTextTeam2; } textToShow.Text = $"{playerCount} {playersRemaining}"; textToShow.Visible = true; this.Call(() => textToShow.Visible = false).After(2); } private void EndGameActivity() { if(WrapUpComponentInstance.Visible == false) { bool didTeam0Win = !PlayerList.Any(item => item.TeamIndex == 1); bool didTeam1Win = !PlayerList.Any(item => item.TeamIndex == 0); #if DEBUG var keyboard = InputManager.Keyboard; bool ctrlDown = keyboard.KeyDown(Microsoft.Xna.Framework.Input.Keys.LeftControl); if (keyboard.KeyPushed(Keys.D1) && ctrlDown) { didTeam0Win = true; } if (keyboard.KeyPushed(Keys.D2) && ctrlDown) { didTeam1Win = true; } #endif if (didTeam0Win || didTeam1Win) { // todo: stop the normal song... this.Call(() => { FlatRedBall.Audio.AudioManager.StopSong(); FlatRedBall.Audio.AudioManager.PlaySong(GlobalContent.dodgeball_end_sting, true, true); }).After(.25); WrapUpComponentInstance.Visible = true; foreach (var player in PlayerList) { player.ClearInput(); } } if (didTeam1Win) { WrapUpComponentInstance.CurrentTeamNumberState = GumRuntimes.WrapUpComponentRuntime.TeamNumber.Team01; } else if(didTeam0Win) { WrapUpComponentInstance.CurrentTeamNumberState = GumRuntimes.WrapUpComponentRuntime.TeamNumber.Team02; } } } #endregion void CustomDestroy() { } static void CustomLoadStaticContent(string contentManagerName) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using Xunit; namespace System.Linq.Expressions.Tests { public static class BinaryGreaterThanTests { #region Test methods [Fact] public static void CheckByteGreaterThanTest() { byte[] array = new byte[] { 0, 1, byte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyByteGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckCharGreaterThanTest() { char[] array = new char[] { '\0', '\b', 'A', '\uffff' }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyCharGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckDecimalGreaterThanTest() { decimal[] array = new decimal[] { decimal.Zero, decimal.One, decimal.MinusOne, decimal.MinValue, decimal.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDecimalGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckDoubleGreaterThanTest() { double[] array = new double[] { 0, 1, -1, double.MinValue, double.MaxValue, double.Epsilon, double.NegativeInfinity, double.PositiveInfinity, double.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyDoubleGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckFloatGreaterThanTest() { float[] array = new float[] { 0, 1, -1, float.MinValue, float.MaxValue, float.Epsilon, float.NegativeInfinity, float.PositiveInfinity, float.NaN }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyFloatGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckIntGreaterThanTest() { int[] array = new int[] { 0, 1, -1, int.MinValue, int.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyIntGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckLongGreaterThanTest() { long[] array = new long[] { 0, 1, -1, long.MinValue, long.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyLongGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckSByteGreaterThanTest() { sbyte[] array = new sbyte[] { 0, 1, -1, sbyte.MinValue, sbyte.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifySByteGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckShortGreaterThanTest() { short[] array = new short[] { 0, 1, -1, short.MinValue, short.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyShortGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckUIntGreaterThanTest() { uint[] array = new uint[] { 0, 1, uint.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUIntGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckULongGreaterThanTest() { ulong[] array = new ulong[] { 0, 1, ulong.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyULongGreaterThan(array[i], array[j]); } } } [Fact] public static void CheckUShortGreaterThanTest() { ushort[] array = new ushort[] { 0, 1, ushort.MaxValue }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < array.Length; j++) { VerifyUShortGreaterThan(array[i], array[j]); } } } #endregion #region Test verifiers private static void VerifyByteGreaterThan(byte a, byte b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(byte)), Expression.Constant(b, typeof(byte))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyCharGreaterThan(char a, char b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(char)), Expression.Constant(b, typeof(char))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyDecimalGreaterThan(decimal a, decimal b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(decimal)), Expression.Constant(b, typeof(decimal))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyDoubleGreaterThan(double a, double b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(double)), Expression.Constant(b, typeof(double))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyFloatGreaterThan(float a, float b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(float)), Expression.Constant(b, typeof(float))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyIntGreaterThan(int a, int b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(int)), Expression.Constant(b, typeof(int))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyLongGreaterThan(long a, long b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(long)), Expression.Constant(b, typeof(long))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifySByteGreaterThan(sbyte a, sbyte b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(sbyte)), Expression.Constant(b, typeof(sbyte))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyShortGreaterThan(short a, short b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(short)), Expression.Constant(b, typeof(short))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyUIntGreaterThan(uint a, uint b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(uint)), Expression.Constant(b, typeof(uint))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyULongGreaterThan(ulong a, ulong b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(ulong)), Expression.Constant(b, typeof(ulong))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } private static void VerifyUShortGreaterThan(ushort a, ushort b) { Expression<Func<bool>> e = Expression.Lambda<Func<bool>>( Expression.GreaterThan( Expression.Constant(a, typeof(ushort)), Expression.Constant(b, typeof(ushort))), Enumerable.Empty<ParameterExpression>()); Func<bool> f = e.Compile(); // compute with expression tree bool etResult = default(bool); Exception etException = null; try { etResult = f(); } catch (Exception ex) { etException = ex; } // compute with real IL bool csResult = default(bool); Exception csException = null; try { csResult = (bool)(a > b); } catch (Exception ex) { csException = ex; } // either both should have failed the same way or they should both produce the same result if (etException != null || csException != null) { Assert.NotNull(etException); Assert.NotNull(csException); Assert.Equal(csException.GetType(), etException.GetType()); } else { Assert.Equal(csResult, etResult); } } #endregion [Fact] public static void CannotReduce() { Expression exp = Expression.GreaterThan(Expression.Constant(0), Expression.Constant(0)); Assert.False(exp.CanReduce); Assert.Same(exp, exp.Reduce()); Assert.Throws<ArgumentException>(null, () => exp.ReduceAndCheck()); } [Fact] public static void ThrowsOnLeftNull() { Assert.Throws<ArgumentNullException>("left", () => Expression.GreaterThan(null, Expression.Constant(0))); } [Fact] public static void ThrowsOnRightNull() { Assert.Throws<ArgumentNullException>("right", () => Expression.GreaterThan(Expression.Constant(0), null)); } private static class Unreadable<T> { public static T WriteOnly { set { } } } [Fact] public static void ThrowsOnLeftUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("left", () => Expression.GreaterThan(value, Expression.Constant(1))); } [Fact] public static void ThrowsOnRightUnreadable() { Expression value = Expression.Property(null, typeof(Unreadable<int>), "WriteOnly"); Assert.Throws<ArgumentException>("right", () => Expression.GreaterThan(Expression.Constant(1), value)); } } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.ClassLib; using Mosa.DeviceSystem; using Mosa.FileSystem.VFS; namespace Mosa.FileSystem.FAT { #region Constants /// <summary> /// /// </summary> internal struct BootSector { internal const uint JumpInstruction = 0x00; // 3 internal const uint EOMName = 0x03; // 8 - "IBM 3.3", "MSDOS5.0", "MSWIN4.1", "FreeDOS" internal const uint BytesPerSector = 0x0B; // 2 - common value 512 internal const uint SectorsPerCluster = 0x0D; // 1 - valid 1 to 128 internal const uint ReservedSectors = 0x0E; // 2 - 1 for FAT12/FAT16, usually 32 for FAT32 internal const uint FatAllocationTables = 0x10; // 1 - always 2 internal const uint MaxRootDirEntries = 0x11; // 2 internal const uint TotalSectors16 = 0x13; // 2 internal const uint MediaDescriptor = 0x15; // 1 internal const uint SectorsPerFAT = 0x16; // 2 internal const uint SectorsPerTrack = 0x18; // 2 internal const uint NumberOfHeads = 0x1A; // 2 internal const uint HiddenSectors = 0x1C; // 4 internal const uint TotalSectors32 = 0x20; // 4 // Extended BIOS Paremeter Block internal const uint PhysicalDriveNbr = 0x24; // 1 internal const uint ReservedCurrentHead = 0x25; // 1 internal const uint ExtendedBootSignature = 0x26; // 1 // value: 0x29 or 0x28 internal const uint IDSerialNumber = 0x27; // 4 internal const uint VolumeLabel = 0x2B; // 11 internal const uint FATType = 0x36; // 8 - padded with blanks (0x20) "FAT12"; "FAT16" internal const uint OSBootCode = 0x3E; // 448 - Operating system boot code internal const uint BootSectorSignature = 0x1FE; // 2 - value: 0x55 0xaa // FAT32 internal const uint FAT32_SectorPerFAT = 0x24; // 4 internal const uint FAT32_Flags = 0x28; // 2 internal const uint FAT32_Version = 0x2A; // 2 internal const uint FAT32_ClusterNumberOfRoot = 0x2C; // 4 internal const uint FAT32_SectorFSInformation = 0x30; // 2 internal const uint FAT32_SecondBootSector = 0x32; // 2 internal const uint FAT32_Reserved1 = 0x34; // 12 internal const uint FAT32_PhysicalDriveNbr = 0x40; // 1 internal const uint FAT32_Reserved2 = 0x40; // 1 internal const uint FAT32_ExtendedBootSignature = 0x42; // 1 internal const uint FAT32_IDSerialNumber = 0x43; // 4 internal const uint FAT32_VolumeLabel = 0x47; // 2 internal const uint FAT32_FATType = 0x52; // 2 internal const uint FAT32_OSBootCode = 0x5A; // 2 } /// <summary> /// /// </summary> internal struct FSInfo { internal const uint FSI_LeadSignature = 0x00; // 4 - always 0x41615252 internal const uint FSI_Reserved1 = 0x04; // 480 - always 0 internal const uint FSI_StructureSigature = 484; // 4 - always 0x61417272 internal const uint FSI_FreeCount = 488; // 4 internal const uint FSI_NextFree = 492; // 4 internal const uint FSI_Reserved2 = 496; // 4 - always 0 internal const uint FSI_TrailSignature = 508; // 4 - always 0xAA550000 internal const uint FSI_TrailSignature2 = 510; // 4 - always 0xAA55 } /// <summary> /// /// </summary> internal struct Entry { internal const uint DOSName = 0x00; // 8 internal const uint DOSExtension = 0x08; // 3 internal const uint FileAttributes = 0x0B; // 1 internal const uint Reserved = 0x0C; // 1 internal const uint CreationTimeFine = 0x0D; // 1 internal const uint CreationTime = 0x0E; // 2 internal const uint CreationDate = 0x10; // 2 internal const uint LastAccessDate = 0x12; // 2 internal const uint EAIndex = 0x14; // 2 internal const uint LastModifiedTime = 0x16; // 2 internal const uint LastModifiedDate = 0x18; // 2 internal const uint FirstCluster = 0x1A; // 2 internal const uint FileSize = 0x1C; // 4 internal const uint EntrySize = 32; } /// <summary> /// /// </summary> internal struct FileNameAttribute { internal const uint LastEntry = 0x00; internal const uint Escape = 0x05; // special msdos hack where 0x05 really means 0xE5 (since 0xE5 was already used for delete) internal const uint Dot = 0x2E; internal const uint Deleted = 0xE5; } #endregion Constants /// <summary> /// /// </summary> public class FatFileSystem : GenericFileSystem { // Limitation: Long file names are not supported /// <summary> /// /// </summary> private FatType fatType; /// <summary> /// /// </summary> private uint endOfClusterMark; /// <summary> /// /// </summary> private uint badClusterMark; /// <summary> /// /// </summary> private uint reservedClusterMark; /// <summary> /// /// </summary> private uint fatMask; /// <summary> /// /// </summary> private uint bytesPerSector; /// <summary> /// /// </summary> private byte sectorsPerCluster; /// <summary> /// /// </summary> private byte reservedSectors; /// <summary> /// /// </summary> private byte nbrFats; /// <summary> /// /// </summary> private uint rootEntries; /// <summary> /// /// </summary> private uint totalClusters; /// <summary> /// /// </summary> private uint rootDirSectors; /// <summary> /// /// </summary> private uint firstDataSector; /// <summary> /// /// </summary> private uint totalSectors; /// <summary> /// /// </summary> private uint dataSectors; /// <summary> /// /// </summary> private uint dataAreaStart; /// <summary> /// /// </summary> private uint entriesPerSector; /// <summary> /// /// </summary> private uint firstRootDirectorySector; /// <summary> /// /// </summary> private uint rootCluster32; /// <summary> /// /// </summary> private uint fatEntries; /// <summary> /// /// </summary> private uint clusterSizeInBytes; /// <summary> /// /// </summary> public interface ICompare { /// <summary> /// Compares the specified data. /// </summary> /// <param name="data">The data.</param> /// <param name="offset">The offset.</param> /// <param name="type">The type.</param> /// <returns></returns> bool Compare(byte[] data, uint offset, FatType type); } /// <summary> /// Gets the type of the FAT. /// </summary> /// <value>The type of the FAT.</value> public FatType FATType { get { return fatType; } } /// <summary> /// Initializes a new instance of the <see cref="FatFileSystem"/> class. /// </summary> /// <param name="partition">The partition.</param> public FatFileSystem(IPartitionDevice partition) : base(partition) { ReadBootSector(); } /// <summary> /// Gets the type of the settings. /// </summary> /// <value>The type of the settings.</value> public GenericFileSystemSettings SettingsType { get { return new FatSettings(); } } /// <summary> /// Creates the VFS mount. /// </summary> /// <returns></returns> public override IFileSystem CreateVFSMount() { return new VfsFileSystem(this); } /// <summary> /// Gets a value indicating whether this instance is read only. /// </summary> /// <value> /// <c>true</c> if this instance is read only; otherwise, <c>false</c>. /// </value> public bool IsReadOnly { get { return true; } } /// <summary> /// /// </summary> public uint ClusterSizeInBytes { get { return clusterSizeInBytes; } } /// <summary> /// Gets the sectors per cluster. /// </summary> /// <value>The sectors per cluster.</value> public uint SectorsPerCluster { get { return sectorsPerCluster; } } /// <summary> /// Reads the cluster. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns></returns> public byte[] ReadCluster(uint cluster) { return partition.ReadBlock(dataAreaStart + ((cluster - 2) * (uint)sectorsPerCluster), sectorsPerCluster); } /// <summary> /// Reads the cluster. /// </summary> /// <param name="cluster">The cluster.</param> /// <param name="block">The block.</param> /// <returns></returns> public bool ReadCluster(uint cluster, byte[] block) { return partition.ReadBlock(dataAreaStart + ((cluster - 2) * (uint)sectorsPerCluster), sectorsPerCluster, block); } /// <summary> /// Writes the cluster. /// </summary> /// <param name="cluster">The cluster.</param> /// <param name="block">The block.</param> /// <returns></returns> public bool WriteCluster(uint cluster, byte[] block) { return partition.WriteBlock(dataAreaStart + ((cluster - 2) * (uint)sectorsPerCluster), sectorsPerCluster, block); } /// <summary> /// Reads the boot sector. /// </summary> /// <returns></returns> protected bool ReadBootSector() { valid = false; if (blockSize != 512) // only going to work with 512 sector sizes (for now) return false; BinaryFormat bootSector = new BinaryFormat(partition.ReadBlock(0, 1)); if (bootSector.GetUShort(BootSector.BootSectorSignature) != 0xAA55) return false; byte extendedBootSignature = bootSector.GetByte(BootSector.ExtendedBootSignature); byte extendedBootSignature32 = bootSector.GetByte(BootSector.FAT32_ExtendedBootSignature); if ((extendedBootSignature != 0x29) && (extendedBootSignature != 0x28) && (extendedBootSignature32 != 0x29)) return false; volumeLabel = bootSector.GetString(BootSector.VolumeLabel, 8).ToString().TrimEnd(); bytesPerSector = bootSector.GetUShort(BootSector.BytesPerSector); sectorsPerCluster = bootSector.GetByte(BootSector.SectorsPerCluster); reservedSectors = bootSector.GetByte(BootSector.ReservedSectors); nbrFats = bootSector.GetByte(BootSector.FatAllocationTables); rootEntries = bootSector.GetUShort(BootSector.MaxRootDirEntries); rootCluster32 = bootSector.GetUInt(BootSector.FAT32_ClusterNumberOfRoot); uint sectorsPerFat16 = bootSector.GetUShort(BootSector.SectorsPerFAT); uint sectorsPerFat32 = bootSector.GetUInt(BootSector.FAT32_SectorPerFAT); uint totalSectors16 = bootSector.GetUShort(BootSector.TotalSectors16); uint totalSectors32 = bootSector.GetUInt(BootSector.TotalSectors32); uint sectorsPerFat = (sectorsPerFat16 != 0) ? sectorsPerFat16 : sectorsPerFat32; uint fatSectors = 0; try { fatSectors = nbrFats * sectorsPerFat; clusterSizeInBytes = sectorsPerCluster * blockSize; rootDirSectors = (((rootEntries * 32) + (bytesPerSector - 1)) / bytesPerSector); firstDataSector = reservedSectors + (nbrFats * sectorsPerFat) + rootDirSectors; totalSectors = (totalSectors16 != 0) ? totalSectors16 : totalSectors32; dataSectors = totalSectors - (reservedSectors + (nbrFats * sectorsPerFat) + rootDirSectors); totalClusters = dataSectors / sectorsPerCluster; entriesPerSector = (bytesPerSector / 32); firstRootDirectorySector = reservedSectors + fatSectors; dataAreaStart = firstRootDirectorySector + rootDirSectors; } catch { return false; } // Some basic checks if ((nbrFats == 0) || (nbrFats > 2) || (totalSectors == 0) || (sectorsPerFat == 0)) return false; if (totalClusters < 4085) fatType = FatType.FAT12; else if (totalClusters < 65525) fatType = FatType.FAT16; else fatType = FatType.FAT32; if (fatType == FatType.FAT12) { reservedClusterMark = 0xFF0; endOfClusterMark = 0x0FF8; badClusterMark = 0x0FF7; fatMask = 0xFFFFFFFF; fatEntries = sectorsPerFat * 3 * blockSize / 2; } else if (fatType == FatType.FAT16) { reservedClusterMark = 0xFFF0; endOfClusterMark = 0xFFF8; badClusterMark = 0xFFF7; fatMask = 0xFFFFFFFF; fatEntries = sectorsPerFat * blockSize / 2; } else { // if (type == FatType.FAT32) { reservedClusterMark = 0xFFF0; endOfClusterMark = 0x0FFFFFF8; badClusterMark = 0x0FFFFFF7; fatMask = 0x0FFFFFFF; fatEntries = sectorsPerFat * blockSize / 4; } // More basic checks if ((fatType == FatType.FAT32) && (rootCluster32 == 0)) return false; valid = true; serialNbr = bootSector.GetBytes(fatType != FatType.FAT32 ? BootSector.IDSerialNumber : BootSector.FAT32_IDSerialNumber, 4); return true; } /// <summary> /// Formats the partition with specified fat settings. /// </summary> /// <param name="fatSettings">The fat settings.</param> /// <returns></returns> public bool Format(FatSettings fatSettings) { if (!partition.CanWrite) return false; this.fatType = fatSettings.FATType; bytesPerSector = 512; nbrFats = 2; totalSectors = partition.BlockCount; sectorsPerCluster = GetSectorsPerClusterByTotalSectors(fatType, totalSectors); if (sectorsPerCluster == 0) return false; if (fatType == FatType.FAT32) { reservedSectors = 32; rootEntries = 0; } else { reservedSectors = 1; rootEntries = 512; } rootDirSectors = (((rootEntries * 32) + (bytesPerSector - 1)) / bytesPerSector); uint val1 = totalSectors - (reservedSectors + rootDirSectors); uint val2 = (uint)((sectorsPerCluster * 256) + nbrFats); if (fatType == FatType.FAT32) val2 = val2 / 2; uint sectorsPerFat = (val1 + (val2 - 1)) / val2; firstRootDirectorySector = reservedSectors + sectorsPerFat; BinaryFormat bootSector = new BinaryFormat(512); bootSector.SetUInt(BootSector.JumpInstruction, 0); bootSector.SetString(BootSector.EOMName, "MOSA "); bootSector.SetUShort(BootSector.BytesPerSector, (ushort)bytesPerSector); bootSector.SetByte(BootSector.SectorsPerCluster, (byte)sectorsPerCluster); bootSector.SetUShort(BootSector.ReservedSectors, (ushort)reservedSectors); bootSector.SetByte(BootSector.FatAllocationTables, nbrFats); bootSector.SetUShort(BootSector.MaxRootDirEntries, (ushort)rootEntries); bootSector.SetUShort(BootSector.BootSectorSignature, 0xAA55); if (totalSectors > 0xFFFF) { bootSector.SetUShort(BootSector.TotalSectors16, 0); bootSector.SetUInt(BootSector.TotalSectors32, totalSectors); } else { bootSector.SetUShort(BootSector.TotalSectors16, (ushort)totalSectors); bootSector.SetUInt(BootSector.TotalSectors32, 0); } if (fatSettings.FloppyMedia) { // Default is 1.44 bootSector.SetByte(BootSector.MediaDescriptor, 0xF0); // 0xF0 = 3.5" Double Sided, 80 tracks per side, 18 sectors per track (1.44MB). } else bootSector.SetByte(BootSector.MediaDescriptor, 0xF8); // 0xF8 = Hard disk bootSector.SetUShort(BootSector.SectorsPerTrack, fatSettings.SectorsPerTrack); bootSector.SetUShort(BootSector.NumberOfHeads, fatSettings.NumberOfHeads); bootSector.SetUInt(BootSector.HiddenSectors, fatSettings.HiddenSectors); if (fatType != FatType.FAT32) { bootSector.SetUShort(BootSector.SectorsPerFAT, (ushort)sectorsPerFat); if (fatSettings.FloppyMedia) bootSector.SetByte(BootSector.PhysicalDriveNbr, 0x00); else bootSector.SetByte(BootSector.PhysicalDriveNbr, 0x80); bootSector.SetByte(BootSector.ReservedCurrentHead, 0); bootSector.SetByte(BootSector.ExtendedBootSignature, 0x29); bootSector.SetBytes(BootSector.IDSerialNumber, fatSettings.SerialID, 0, (uint)Math.Min(4, fatSettings.SerialID.Length)); if (string.IsNullOrEmpty(fatSettings.VolumeLabel)) bootSector.SetString(BootSector.VolumeLabel, "NO NAME "); else { bootSector.SetString(BootSector.VolumeLabel, " "); // 11 blank spaces bootSector.SetString(BootSector.VolumeLabel, fatSettings.VolumeLabel, (uint)Math.Min(11, fatSettings.VolumeLabel.Length)); } if (fatSettings.OSBootCode != null) { if (fatSettings.OSBootCode.Length == 512) { bootSector.SetBytes(BootSector.JumpInstruction, fatSettings.OSBootCode, BootSector.JumpInstruction, 3); bootSector.SetBytes(BootSector.OSBootCode, fatSettings.OSBootCode, BootSector.OSBootCode, 448); } else { bootSector.SetByte(BootSector.JumpInstruction, 0xEB); // 0xEB = JMP Instruction bootSector.SetByte(BootSector.JumpInstruction + 1, 0x3C); bootSector.SetByte(BootSector.JumpInstruction + 2, 0x90); bootSector.SetBytes(BootSector.OSBootCode, fatSettings.OSBootCode, 0, (uint)Math.Min(448, fatSettings.OSBootCode.Length)); } } if (fatType == FatType.FAT12) bootSector.SetString(BootSector.FATType, "FAT12 "); else bootSector.SetString(BootSector.FATType, "FAT16 "); } if (fatType == FatType.FAT32) { bootSector.SetUShort(BootSector.SectorsPerFAT, 0); bootSector.SetUInt(BootSector.FAT32_SectorPerFAT, sectorsPerFat); bootSector.SetByte(BootSector.FAT32_Flags, 0); bootSector.SetUShort(BootSector.FAT32_Version, 0); bootSector.SetUInt(BootSector.FAT32_ClusterNumberOfRoot, 2); bootSector.SetUShort(BootSector.FAT32_SectorFSInformation, 1); bootSector.SetUShort(BootSector.FAT32_SecondBootSector, 6); bootSector.SetByte(BootSector.FAT32_PhysicalDriveNbr, 0x80); bootSector.SetByte(BootSector.FAT32_Reserved2, 0); bootSector.SetByte(BootSector.FAT32_ExtendedBootSignature, 0x29); bootSector.SetBytes(BootSector.FAT32_IDSerialNumber, fatSettings.SerialID, 0, (uint)Math.Min(4, fatSettings.SerialID.Length)); bootSector.SetString(BootSector.FAT32_VolumeLabel, " "); // 11 blank spaces bootSector.SetString(BootSector.FAT32_VolumeLabel, fatSettings.VolumeLabel, (uint)(fatSettings.VolumeLabel.Length <= 11 ? fatSettings.VolumeLabel.Length : 11)); bootSector.SetString(BootSector.FAT32_FATType, "FAT32 "); if (fatSettings.OSBootCode.Length == 512) { bootSector.SetBytes(BootSector.JumpInstruction, fatSettings.OSBootCode, BootSector.JumpInstruction, 3); bootSector.SetBytes(BootSector.FAT32_OSBootCode, fatSettings.OSBootCode, BootSector.FAT32_OSBootCode, 420); } else { bootSector.SetByte(BootSector.JumpInstruction, 0xEB); // 0xEB = JMP Instruction bootSector.SetByte(BootSector.JumpInstruction + 1, 0x58); bootSector.SetByte(BootSector.JumpInstruction + 2, 0x90); bootSector.SetBytes(BootSector.FAT32_OSBootCode, fatSettings.OSBootCode, 0, (uint)Math.Min(420, fatSettings.OSBootCode.Length)); } } // Write Boot Sector partition.WriteBlock(0, 1, bootSector.Data); if (fatType == FatType.FAT32) { // Write backup Boot Sector if (fatType == FatType.FAT32) partition.WriteBlock(6, 1, bootSector.Data); // Create FSInfo Structure BinaryFormat infoSector = new BinaryFormat(512); infoSector.SetUInt(FSInfo.FSI_LeadSignature, 0x41615252); //FSInfo.FSI_Reserved1 infoSector.SetUInt(FSInfo.FSI_StructureSigature, 0x61417272); infoSector.SetUInt(FSInfo.FSI_FreeCount, 0xFFFFFFFF); infoSector.SetUInt(FSInfo.FSI_NextFree, 0xFFFFFFFF); //FSInfo.FSI_Reserved2 bootSector.SetUInt(FSInfo.FSI_TrailSignature, 0xAA550000); // Write FSInfo Structure partition.WriteBlock(1, 1, infoSector.Data); partition.WriteBlock(7, 1, infoSector.Data); // Create 2nd sector BinaryFormat secondSector = new BinaryFormat(512); secondSector.SetUShort(FSInfo.FSI_TrailSignature2, 0xAA55); partition.WriteBlock(2, 1, secondSector.Data); partition.WriteBlock(8, 1, secondSector.Data); } // Create FAT table(s) // Clear primary & secondary FATs BinaryFormat emptyFat = new BinaryFormat(512); for (uint i = 1; i < sectorsPerFat; i++) partition.WriteBlock(reservedSectors + i, 1, emptyFat.Data); if (nbrFats == 2) for (uint i = 1; i < sectorsPerFat; i++) partition.WriteBlock(reservedSectors + sectorsPerFat + i, 1, emptyFat.Data); // First FAT block is special BinaryFormat firstFat = new BinaryFormat(512); if (fatType == FatType.FAT12) { firstFat.SetByte(1, 0xFF); firstFat.SetByte(2, 0xFF); // 0xF8 } else if (fatType == FatType.FAT16) { firstFat.SetUShort(0, 0xFFFF); firstFat.SetUShort(2, 0xFFFF); // 0xFFF8 } else // if (type == FatType.FAT32) { firstFat.SetUInt(0, 0x0FFFFFFF); firstFat.SetUInt(4, 0x0FFFFFFF); // 0x0FFFFFF8 firstFat.SetUInt(8, 0x0FFFFFFF); // Also reserve the 2nd cluster for root directory } if (fatSettings.FloppyMedia) firstFat.SetByte(0, 0xF0); else firstFat.SetByte(0, 0xF8); partition.WriteBlock(reservedSectors, 1, firstFat.Data); if (nbrFats == 2) partition.WriteBlock(reservedSectors + sectorsPerFat, 1, firstFat.Data); // Create Empty Root Directory if (fatType == FatType.FAT32) { } else { for (uint i = 0; i < rootDirSectors; i++) partition.WriteBlock(firstRootDirectorySector + i, 1, emptyFat.Data); } return ReadBootSector(); } /// <summary> /// Determines whether [is cluster free] [the specified cluster]. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns> /// <c>true</c> if [is cluster free] [the specified cluster]; otherwise, <c>false</c>. /// </returns> protected bool IsClusterFree(uint cluster) { return ((cluster & fatMask) == 0x00); } /// <summary> /// Determines whether [is cluster reserved] [the specified cluster]. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns> /// <c>true</c> if [is cluster reserved] [the specified cluster]; otherwise, <c>false</c>. /// </returns> protected bool IsClusterReserved(uint cluster) { return (((cluster & fatMask) == 0x00) || ((cluster & fatMask) >= reservedClusterMark) && ((cluster & fatMask) < badClusterMark)); } /// <summary> /// Determines whether [is cluster bad] [the specified cluster]. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns> /// <c>true</c> if [is cluster bad] [the specified cluster]; otherwise, <c>false</c>. /// </returns> protected bool IsClusterBad(uint cluster) { return ((cluster & fatMask) == badClusterMark); } /// <summary> /// Determines whether [is cluster last] [the specified cluster]. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns> /// <c>true</c> if [is cluster last] [the specified cluster]; otherwise, <c>false</c>. /// </returns> protected bool IsClusterLast(uint cluster) { return ((cluster & fatMask) >= endOfClusterMark); } /// <summary> /// Gets the cluster by sector. /// </summary> /// <param name="sector">The sector.</param> /// <returns></returns> protected uint GetClusterBySector(uint sector) { if (sector < dataAreaStart) return 0; return (sector - dataAreaStart) / sectorsPerCluster; } /// <summary> /// Gets the sector by cluster. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns></returns> public uint GetSectorByCluster(uint cluster) { return dataAreaStart + ((cluster - 2) * sectorsPerCluster); } /// <summary> /// Gets the cluster entry value. /// </summary> /// <param name="cluster">The cluster.</param> /// <returns></returns> protected uint GetClusterEntryValue(uint cluster) { uint fatoffset = 0; if (fatType == FatType.FAT12) fatoffset = (cluster + (cluster / 2)); else if (fatType == FatType.FAT16) fatoffset = cluster * 2; else //if (type == FatType.FAT32) fatoffset = cluster * 4; uint sector = reservedSectors + (fatoffset / bytesPerSector); uint sectorOffset = fatoffset % bytesPerSector; uint nbrSectors = 1; if ((fatType == FatType.FAT12) && (sectorOffset == bytesPerSector - 1)) nbrSectors = 2; BinaryFormat fat = new BinaryFormat(partition.ReadBlock(sector, nbrSectors)); uint clusterValue; if (fatType == FatType.FAT12) { clusterValue = fat.GetUShort(sectorOffset); if (cluster % 2 == 1) clusterValue = clusterValue >> 4; else clusterValue = clusterValue & 0x0FFF; } else if (fatType == FatType.FAT16) clusterValue = fat.GetUShort(sectorOffset); else //if (type == FatType.FAT32) clusterValue = fat.GetUInt(sectorOffset) & 0x0FFFFFFF; return clusterValue; } /// <summary> /// Sets the cluster entry value. /// </summary> /// <param name="cluster">The cluster.</param> /// <param name="nextcluster">The nextcluster.</param> /// <returns></returns> protected bool SetClusterEntryValue(uint cluster, uint nextcluster) { uint fatOffset = 0; if (fatType == FatType.FAT12) fatOffset = (cluster + (cluster / 2)); else if (fatType == FatType.FAT16) fatOffset = cluster * 2; else //if (type == FatType.FAT32) fatOffset = cluster * 4; uint sector = reservedSectors + (fatOffset / bytesPerSector); uint sectorOffset = fatOffset % bytesPerSector; uint nbrSectors = 1; if ((fatType == FatType.FAT12) && (sectorOffset == bytesPerSector - 1)) nbrSectors = 2; BinaryFormat fat = new BinaryFormat(partition.ReadBlock(sector, nbrSectors)); if (fatType == FatType.FAT12) { uint clustervalue = fat.GetUShort(sectorOffset); if (cluster % 2 == 1) clustervalue = ((clustervalue & 0x000F) | (nextcluster << 4)); else clustervalue = ((clustervalue & 0xF000) | (nextcluster & 0x0FFF)); fat.SetUShort(sectorOffset, (ushort)clustervalue); } else if (fatType == FatType.FAT16) fat.SetUShort(sectorOffset, (ushort)(nextcluster & 0xFFFF)); else //if (type == FatType.FAT32) fat.SetUInt(sectorOffset, nextcluster); partition.WriteBlock(sector, nbrSectors, fat.Data); return true; } /// <summary> /// Gets the sectors per cluster by total sectors. /// </summary> /// <param name="type">The type.</param> /// <param name="sectors">The sectors.</param> /// <returns></returns> public static byte GetSectorsPerClusterByTotalSectors(FatType type, uint sectors) { switch (type) { case FatType.FAT12: { if (sectors < 512) return 1; else if (sectors == 720) return 2; else if (sectors == 1440) return 2; else if (sectors <= 2880) return 1; else if (sectors <= 5760) return 2; else if (sectors <= 16384) return 4; else if (sectors <= 32768) return 8; else return 0; } case FatType.FAT16: { if (sectors < 8400) return 0; else if (sectors < 32680) return 2; else if (sectors < 262144) return 4; else if (sectors < 524288) return 8; else if (sectors < 1048576) return 16; else if (sectors < 2097152) return 32; else if (sectors < 4194304) return 64; else return 0; } case FatType.FAT32: { if (sectors < 66600) return 0; else if (sectors < 532480) return 1; else if (sectors < 16777216) return 8; else if (sectors < 33554432) return 16; else if (sectors < 67108864) return 32; else return 64; } default: return 0; } } /// <summary> /// Extracts the name of the file. /// </summary> /// <param name="directory">The directory.</param> /// <param name="index">The index.</param> /// <returns></returns> public static string ExtractFileName(byte[] directory, uint index) { // rewrite to use string BinaryFormat entry = new BinaryFormat(directory); char[] name = new char[12]; for (uint i = 0; i < 8; i++) name[i] = (char)entry.GetByte(index + i + Entry.DOSName); int len = 8; for (int i = 7; i > 0; i--) if (name[i] == ' ') len--; else break; // special case where real character is same as the delete if ((len >= 1) && (name[0] == (char)FileNameAttribute.Escape)) name[0] = (char)FileNameAttribute.Deleted; name[len] = '.'; len++; for (uint i = 0; i < 3; i++) name[len + i] = (char)entry.GetByte(index + i + Entry.DOSExtension); len = len + 3; int spaces = 0; for (int i = len - 1; i >= 0; i--) if (name[i] == ' ') spaces++; else break; if (spaces == 3) spaces = 4; len = len - spaces; // FIXME string str = string.Empty; for (uint i = 0; i < len; i++) str = str + (char)name[i]; return str; } /// <summary> /// Determines whether [is valid fat character] [the specified c]. /// </summary> /// <param name="c">The c.</param> /// <returns> /// <c>true</c> if [is valid fat character] [the specified c]; otherwise, <c>false</c>. /// </returns> protected static bool IsValidFatCharacter(char c) { if ((c >= 'A') || (c <= 'Z')) return true; if ((c >= '0') || (c <= '9')) return true; if ((c >= 128) || (c <= 255)) return true; string valid = " !#$%&'()-@^_`{}~"; for (int i = 0; i < valid.Length; i++) if (valid[i] == c) return true; return false; } /// <summary> /// Gets the cluster entry. /// </summary> /// <param name="data">The data.</param> /// <param name="index">The index.</param> /// <param name="type">The type.</param> /// <returns></returns> static public uint GetClusterEntry(byte[] data, uint index, FatType type) { BinaryFormat entry = new BinaryFormat(data); uint cluster = entry.GetUShort(Entry.FirstCluster + (index * Entry.EntrySize)); if (type == FatType.FAT32) cluster |= ((uint)entry.GetUShort(Entry.EAIndex + (index * Entry.EntrySize))) << 16; return cluster; } /// <summary> /// Finds the entry. /// </summary> /// <param name="compare">The compare.</param> /// <param name="startCluster">The start cluster.</param> /// <returns></returns> public FatFileLocation FindEntry(FatFileSystem.ICompare compare, uint startCluster) { uint activeSector = startCluster * sectorsPerCluster; if (startCluster == 0) activeSector = (fatType == FatType.FAT32) ? GetSectorByCluster(rootCluster32) : firstRootDirectorySector; uint increment = 0; for (;;) { BinaryFormat directory = new BinaryFormat(partition.ReadBlock(activeSector, 1)); for (uint index = 0; index < entriesPerSector; index++) { if (compare.Compare(directory.Data, index * 32, fatType)) { FatFileAttributes attribute = (FatFileAttributes)directory.GetByte((index * Entry.EntrySize) + Entry.FileAttributes); return new FatFileLocation(GetClusterEntry(directory.Data, index, fatType), activeSector, index, (attribute & FatFileAttributes.SubDirectory) != 0); } if (directory.GetByte(Entry.DOSName + (index * Entry.EntrySize)) == FileNameAttribute.LastEntry) return new FatFileLocation(); } ++increment; if ((startCluster == 0) && (fatType != FatType.FAT32)) { // FAT12/16 Root directory if (increment >= rootDirSectors) return new FatFileLocation(); activeSector = startCluster + increment; continue; } else { // subdirectory if (increment < sectorsPerCluster) { // still within cluster activeSector = startCluster + increment; continue; } // exiting cluster // goto next cluster (if any) uint cluster = GetClusterBySector(startCluster); if (cluster == 0) return new FatFileLocation(); uint nextCluster = GetClusterEntryValue(cluster); if ((IsClusterLast(nextCluster)) || (IsClusterBad(nextCluster)) || (IsClusterFree(nextCluster)) || (IsClusterReserved(nextCluster))) return new FatFileLocation(); activeSector = (uint)(dataAreaStart + (nextCluster - 1 * sectorsPerCluster)); continue; } } } /// <summary> /// Gets the size of the file. /// </summary> /// <param name="directoryBlock">The directory block.</param> /// <param name="index">The index.</param> /// <returns></returns> public uint GetFileSize(uint directoryBlock, uint index) { BinaryFormat directory = new BinaryFormat(partition.ReadBlock(directoryBlock, 1)); return directory.GetUInt((index * Entry.EntrySize) + Entry.FileSize); } /// <summary> /// Updates the length. /// </summary> /// <param name="size">The size.</param> /// <param name="firstCluster">The first cluster.</param> /// <param name="directorySector">The directory sector.</param> /// <param name="directorySectorIndex">Index of the directory sector.</param> public void UpdateLength(uint size, uint firstCluster, uint directorySector, uint directorySectorIndex) { // Truncate the file BinaryFormat entry = new BinaryFormat(partition.ReadBlock(directorySector, 1)); // Truncate the file length and set entry.SetUInt(Entry.FileSize + (directorySectorIndex * Entry.EntrySize), size); if (size == 0) entry.SetUInt(Entry.FirstCluster + (directorySectorIndex * Entry.EntrySize), 0); partition.WriteBlock(directorySector, 1, entry.Data); if (size == 0) FreeClusterChain(firstCluster); } /// <summary> /// Creates the file. /// </summary> /// <param name="filename">The filename.</param> /// <param name="fileAttributes">The file attributes.</param> /// <param name="directoryCluster">The directory cluster.</param> /// <returns></returns> public FatFileLocation CreateFile(string filename, FatFileAttributes fileAttributes, uint directoryCluster) { FatFileLocation location = FindEntry(new Find.WithName(filename), directoryCluster); if (location.Valid) { // Truncate the file BinaryFormat entry = new BinaryFormat(partition.ReadBlock(location.DirectorySector, 1)); // Truncate the file length and reset the start cluster entry.SetUInt(Entry.FileSize + (location.DirectorySectorIndex * Entry.EntrySize), 0); entry.SetUInt(Entry.FirstCluster + (location.DirectorySectorIndex * Entry.EntrySize), 0); partition.WriteBlock(location.DirectorySector, 1, entry.Data); FreeClusterChain(location.FirstCluster); location.FirstCluster = 0; return location; } // Find an empty location in the directory location = FindEntry(new Find.Empty(), directoryCluster); if (!location.Valid) { // Extend Directory // TODO return location; } BinaryFormat directory = new BinaryFormat(partition.ReadBlock(location.DirectorySector, 1)); if (filename.Length > 11) filename = filename.Substring(0, 11); // Create Entry directory.SetString(Entry.DOSName + (location.DirectorySectorIndex * Entry.EntrySize), " ", 11); directory.SetString(Entry.DOSName + (location.DirectorySectorIndex * Entry.EntrySize), filename); directory.SetByte(Entry.FileAttributes + (location.DirectorySectorIndex * Entry.EntrySize), (byte)fileAttributes); directory.SetByte(Entry.Reserved + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetByte(Entry.CreationTimeFine + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.CreationTime + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.CreationDate + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.LastAccessDate + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.LastModifiedTime + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.LastModifiedDate + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.FirstCluster + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUInt(Entry.FileSize + (location.DirectorySectorIndex * Entry.EntrySize), 0); partition.WriteBlock(location.DirectorySector, 1, directory.Data); return location; } /// <summary> /// Deletes the specified file or directory /// </summary> /// <param name="targetCluster">The target cluster.</param> /// <param name="directorySector">The directory sector.</param> /// <param name="directorySectorIndex">Index of the directory sector.</param> public void Delete(uint targetCluster, uint directorySector, uint directorySectorIndex) { BinaryFormat entry = new BinaryFormat(partition.ReadBlock(directorySector, 1)); entry.SetByte(Entry.DOSName + (directorySectorIndex * Entry.EntrySize), (byte)FileNameAttribute.Deleted); partition.WriteBlock(directorySector, 1, entry.Data); FreeClusterChain(targetCluster); } /// <summary> /// Sets the name of the volume. /// </summary> /// <param name="volumeName">Name of the volume.</param> public void SetVolumeName(string volumeName) { if (volumeLabel.Length > 8) volumeLabel = volumeLabel.Substring(0, 8); FatFileLocation location = FindEntry(new Find.Volume(), 0); if (!location.Valid) { location = FindEntry(new Find.Empty(), 0); if (!location.Valid) return; // TODO: something went wrong } BinaryFormat directory = new BinaryFormat(partition.ReadBlock(location.DirectorySector, 1)); if (volumeName.Length > 8) volumeName = volumeName.Substring(0, 8); // Create Entry directory.SetString(Entry.DOSName + (location.DirectorySectorIndex * Entry.EntrySize), " ", 11); directory.SetString(Entry.DOSName + (location.DirectorySectorIndex * Entry.EntrySize), volumeName); directory.SetByte(Entry.FileAttributes + (location.DirectorySectorIndex * Entry.EntrySize), (byte)FatFileAttributes.VolumeLabel); directory.SetByte(Entry.Reserved + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetByte(Entry.CreationTimeFine + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.CreationTime + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.CreationDate + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.LastAccessDate + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.LastModifiedTime + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.LastModifiedDate + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUShort(Entry.FirstCluster + (location.DirectorySectorIndex * Entry.EntrySize), 0); directory.SetUInt(Entry.FileSize + (location.DirectorySectorIndex * Entry.EntrySize), 0); partition.WriteBlock(location.DirectorySector, 1, directory.Data); } /// <summary> /// Frees the cluster chain. /// </summary> /// <param name="firstCluster">The first cluster.</param> /// <returns></returns> protected bool FreeClusterChain(uint firstCluster) { if (firstCluster == 0) return true; uint at = firstCluster; while (true) { uint next = GetClusterEntryValue(firstCluster); SetClusterEntryValue(at, 0); if (IsClusterLast(next)) return true; if (IsClusterFree(next) || IsClusterBad(next) || IsClusterReserved(next)) return false; at = next; } } /// <summary> /// Finds the Nth cluster. /// </summary> /// <param name="start">The start.</param> /// <param name="count">The count.</param> /// <returns></returns> public uint FindNthCluster(uint start, uint count) { // TODO: add locking uint at = start; for (int i = 0; i < count; i++) { at = GetClusterEntryValue(at); if (IsClusterLast(at)) return 0; if (IsClusterFree(at) || IsClusterBad(at) || IsClusterReserved(at)) return 0; } return at; } /// <summary> /// Gets the next cluster. /// </summary> /// <param name="start">The start.</param> /// <returns></returns> public uint GetNextCluster(uint start) { // TODO: add locking uint at = GetClusterEntryValue(start); if (IsClusterLast(at)) return 0; if (IsClusterFree(at) || IsClusterBad(at) || IsClusterReserved(at)) return 0; return at; } protected uint lastFreeHint = 0; /// <summary> /// Allocates the cluster. /// </summary> /// <returns></returns> protected uint AllocateCluster() { uint at = lastFreeHint + 1; if (at < 2) at = 2; uint last = at - 1; if (last == 1) last = fatEntries; while (at != last) { uint value = GetClusterEntryValue(at); if (IsClusterFree(value)) { SetClusterEntryValue(at, 0xFFFFFFFF /*endOfClusterMark*/); lastFreeHint = at; return at; } at++; if (at >= fatEntries) at = 2; } return 0; // mean no free space } /// <summary> /// Allocates the first cluster. /// </summary> /// <param name="directorySector">The directory sector.</param> /// <param name="directorySectorIndex">Index of the directory sector.</param> /// <returns></returns> public uint AllocateFirstCluster(uint directorySector, uint directorySectorIndex) { uint newCluster = AllocateCluster(); if (newCluster == 0) return 0; // Truncate set first cluster BinaryFormat entry = new BinaryFormat(partition.ReadBlock(directorySector, 1)); entry.SetUInt(Entry.FirstCluster + (directorySectorIndex * Entry.EntrySize), newCluster); partition.WriteBlock(directorySector, 1, entry.Data); return newCluster; } /// <summary> /// Adds the cluster. /// </summary> /// <param name="lastCluster">The last cluster.</param> /// <returns></returns> public uint AddCluster(uint lastCluster) { uint newCluster = AllocateCluster(); if (newCluster == 0) return 0; if (!SetClusterEntryValue(lastCluster, newCluster)) return 0; return newCluster; } //protected OpenFile ExtractFileInformation (MemoryBlock directory, uint index, OpenFile parent) //{ // uint offset = index * 32; // byte first = directory.GetByte (offset + Entry.DOSName); // if ((first == FileNameAttribute.LastEntry) || (first == FileNameAttribute.Deleted)) // return null; // FileAttributes attribute = (FileAttributes)directory.GetByte (offset + Entry.FileAttributes); // if (attribute == FileAttributes.LongFileName) // return null; // long file names are not supported // byte second = directory.GetByte (offset + Entry.DOSName); // if ((first == FileNameAttribute.Dot) && (first == FileNameAttribute.Dot)) // return null; // OpenFile file = new OpenFile (); // if ((attribute & FileAttributes.SubDirectory) != 0) // file.Type = FileType.Directory; // else // file.Type = FileType.File; // file.ReadOnly = ((attribute & FileAttributes.ReadOnly) == FileAttributes.ReadOnly); // file.Hidden = ((attribute & FileAttributes.Hidden) == FileAttributes.Hidden); // file.Archive = ((attribute & FileAttributes.Archive) == FileAttributes.Archive); // file.System = ((attribute & FileAttributes.System) == FileAttributes.System); // file.Size = directory.GetUInt (offset + Entry.FileSize); // //TODO: build file name name.Trim()+'.'+ext.Trim() // //string name = ByteBuffer.GetString(directory, 8, offset + Entry.DOSName); // //string ext = ByteBuffer.GetString(directory, 3, offset + Entry.DOSExtension); // file.Name = ExtractFileName (directory.Offset (index * 32)); // ushort cdate = directory.GetUShort (offset + Entry.CreationDate); // ushort ctime = directory.GetUShort (offset + Entry.CreationTime); // ushort mtime = directory.GetUShort (offset + Entry.LastModifiedTime); // ushort mdate = directory.GetUShort (offset + Entry.LastModifiedDate); // ushort adate = directory.GetUShort (offset + Entry.LastAccessDate); // ushort msec = (ushort)(directory.GetByte (offset + Entry.CreationTimeFine) * 10); // file.CreateTime.Year = (ushort)((cdate >> 9) + 1980); // file.CreateTime.Month = (ushort)(((cdate >> 5) - 1) & 0x0F); // file.CreateTime.Day = (ushort)(cdate & 0x1F); // file.CreateTime.Hour = (ushort)(ctime >> 11); // file.CreateTime.Month = (ushort)((ctime >> 5) & 0x0F); // file.CreateTime.Second = (ushort)(((ctime & 0x1F) * 2) + (msec / 100)); // file.CreateTime.Milliseconds = (ushort)(msec / 20); // file.LastModifiedTime.Year = (ushort)((mdate >> 9) + 1980); // file.LastModifiedTime.Month = (ushort)((mdate >> 5) & 0x0F); // file.LastModifiedTime.Day = (ushort)(mdate & 0x1F); // file.LastModifiedTime.Hour = (ushort)(mtime >> 11); // file.LastModifiedTime.Minute = (ushort)((mtime >> 5) & 0x3F); // file.LastModifiedTime.Second = (ushort)((mtime & 0x1F) * 2); // file.LastModifiedTime.Milliseconds = 0; // file.LastAccessTime.Year = (ushort)((adate >> 9) + 1980); // file.LastAccessTime.Month = (ushort)((adate >> 5) & 0x0F); // file.LastAccessTime.Day = (ushort)(adate & 0x1F); // file.Directory = parent; // file._startdisklocation = directory.GetUShort (offset + Entry.FirstCluster); // if (file.Type == FileType.Directory) // file._startdisklocation = dataareastart + ((file._startdisklocation - 2) * sectorspercluster); // file._position = 0; // file._count = 0; // return file; //} } }
// ---------------------------------------------------------------------------- // <copyright file="AccountService.cs" company="Exit Games GmbH"> // Photon Cloud Account Service - Copyright (C) 2012 Exit Games GmbH // </copyright> // <summary> // Provides methods to register a new user-account for the Photon Cloud and // get the resulting appId. // </summary> // <author>developer@exitgames.com</author> // ---------------------------------------------------------------------------- #if UNITY_EDITOR using System.Net.Security; using System.Security.Cryptography.X509Certificates; using System; using System.Collections.Generic; using System.IO; using System.Net; using ExitGames.Client.Photon; using Newtonsoft.Json; namespace Photon.Pun { public class AccountService { private const string ServiceUrl = "https://service.exitgames.com/AccountExt/AccountServiceExt.aspx"; private Action<AccountService> registrationCallback; // optional (when using async reg) public string Message { get; private set; } // msg from server (in case of success, this is the appid) protected internal Exception Exception { get; set; } // exceptions in account-server communication public string AppId { get; private set; } public string AppId2 { get; private set; } public int ReturnCode { get; private set; } // 0 = OK. anything else is a error with Message public enum Origin : byte { ServerWeb = 1, CloudWeb = 2, Pun = 3, Playmaker = 4 }; /// <summary> /// Creates a instance of the Account Service to register Photon Cloud accounts. /// </summary> public AccountService() { WebRequest.DefaultWebProxy = null; ServicePointManager.ServerCertificateValidationCallback = Validator; } public static bool Validator(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors policyErrors) { return true; // any certificate is ok in this case } /// <summary> /// Attempts to create a Photon Cloud Account. /// Check ReturnCode, Message and AppId to get the result of this attempt. /// </summary> /// <param name="email">Email of the account.</param> /// <param name="origin">Marks which channel created the new account (if it's new).</param> /// <param name="serviceType">Defines which type of Photon-service is being requested.</param> public void RegisterByEmail(string email, Origin origin, string serviceType = null) { this.registrationCallback = null; this.AppId = string.Empty; this.AppId2 = string.Empty; this.Message = string.Empty; this.ReturnCode = -1; string result; try { WebRequest req = HttpWebRequest.Create(this.RegistrationUri(email, (byte) origin, serviceType)); HttpWebResponse resp = req.GetResponse() as HttpWebResponse; // now read result StreamReader reader = new StreamReader(resp.GetResponseStream()); result = reader.ReadToEnd(); } catch (Exception ex) { this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; this.Exception = ex; return; } this.ParseResult(result); } /// <summary> /// Attempts to create a Photon Cloud Account asynchronously. /// Once your callback is called, check ReturnCode, Message and AppId to get the result of this attempt. /// </summary> /// <param name="email">Email of the account.</param> /// <param name="origin">Marks which channel created the new account (if it's new).</param> /// <param name="serviceType">Defines which type of Photon-service is being requested.</param> /// <param name="callback">Called when the result is available.</param> public void RegisterByEmailAsync(string email, Origin origin, string serviceType, Action<AccountService> callback = null) { this.registrationCallback = callback; this.AppId = string.Empty; this.AppId2 = string.Empty; this.Message = string.Empty; this.ReturnCode = -1; try { HttpWebRequest req = (HttpWebRequest) HttpWebRequest.Create(this.RegistrationUri(email, (byte) origin, serviceType)); req.Timeout = 5000; req.BeginGetResponse(this.OnRegisterByEmailCompleted, req); } catch (Exception ex) { this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; this.Exception = ex; if (this.registrationCallback != null) { this.registrationCallback(this); } } } /// <summary> /// Internal callback with result of async HttpWebRequest (in RegisterByEmailAsync). /// </summary> /// <param name="ar"></param> private void OnRegisterByEmailCompleted(IAsyncResult ar) { try { HttpWebRequest request = (HttpWebRequest) ar.AsyncState; HttpWebResponse response = request.EndGetResponse(ar) as HttpWebResponse; if (response != null && response.StatusCode == HttpStatusCode.OK) { // no error. use the result StreamReader reader = new StreamReader(response.GetResponseStream()); string result = reader.ReadToEnd(); this.ParseResult(result); } else { // a response but some error on server. show message this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; } } catch (Exception ex) { // not even a response. show message this.Message = "Failed to connect to Cloud Account Service. Please register via account website."; this.Exception = ex; } if (this.registrationCallback != null) { this.registrationCallback(this); } } /// <summary> /// Creates the service-call Uri, escaping the email for security reasons. /// </summary> /// <param name="email">Email of the account.</param> /// <param name="origin">1 = server-web, 2 = cloud-web, 3 = PUN, 4 = playmaker</param> /// <param name="serviceType">Defines which type of Photon-service is being requested. Options: "", "voice", "chat"</param> /// <returns>Uri to call.</returns> private Uri RegistrationUri(string email, byte origin, string serviceType) { if (serviceType == null) { serviceType = string.Empty; } string emailEncoded = Uri.EscapeDataString(email); string uriString = string.Format("{0}?email={1}&origin={2}&serviceType={3}", ServiceUrl, emailEncoded, origin, serviceType); return new Uri(uriString); } /// <summary> /// Reads the Json response and applies it to local properties. /// </summary> /// <param name="result"></param> private void ParseResult(string result) { if (string.IsNullOrEmpty(result)) { this.Message = "Server's response was empty. Please register through account website during this service interruption."; return; } Dictionary<string, string> values = JsonConvert.DeserializeObject<Dictionary<string, string>>(result); if (values == null) { this.Message = "Service temporarily unavailable. Please register through account website."; return; } int returnCodeInt = -1; string returnCodeString = string.Empty; string message; string messageDetailed; values.TryGetValue("ReturnCode", out returnCodeString); values.TryGetValue("Message", out message); values.TryGetValue("MessageDetailed", out messageDetailed); int.TryParse(returnCodeString, out returnCodeInt); this.ReturnCode = returnCodeInt; if (returnCodeInt == 0) { // returnCode == 0 means: all ok. message is new AppId this.AppId = message; if (PhotonEditorUtils.HasVoice) { this.AppId2 = messageDetailed; } } else { // any error gives returnCode != 0 this.AppId = string.Empty; if (PhotonEditorUtils.HasVoice) { this.AppId2 = string.Empty; } this.Message = message; } } } } #endif
/* * Utils.cs - Implementation of the "DotGNU.Images.Utils" class. * * Copyright (C) 2003 Southern Storm Software, Pty Ltd. * * This program is free software, you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY, without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program, if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ namespace DotGNU.Images { using System; using System.IO; internal sealed class Utils { // Read a little-endian 16-bit integer value from a buffer. public static int ReadUInt16(byte[] buffer, int offset) { return ((buffer[offset]) | (buffer[offset + 1] << 8)); } // Read a little-endian 32-bit integer value from a buffer. public static int ReadInt32(byte[] buffer, int offset) { return ((buffer[offset]) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)); } // Read a big-endian 16-bit integer value from a buffer. public static int ReadUInt16B(byte[] buffer, int offset) { return ((buffer[offset + 1]) | (buffer[offset] << 8)); } // Read a big-endian 32-bit integer value from a buffer. public static int ReadInt32B(byte[] buffer, int offset) { return ((buffer[offset + 3]) | (buffer[offset + 2] << 8) | (buffer[offset + 1] << 16) | (buffer[offset] << 24)); } // Read a BGR value from a buffer. public static int ReadBGR(byte[] buffer, int offset) { return ((buffer[offset]) | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16)); } // Read an RGB value from a buffer. public static int ReadRGB(byte[] buffer, int offset) { return ((buffer[offset + 2]) | (buffer[offset + 1] << 8) | (buffer[offset] << 16)); } // Write a little-endian 16-bit integer value to a buffer. public static void WriteUInt16(byte[] buffer, int offset, int value) { buffer[offset] = (byte)value; buffer[offset + 1] = (byte)(value >> 8); } // Write a little-endian 32-bit integer value to a buffer. public static void WriteInt32(byte[] buffer, int offset, int value) { buffer[offset] = (byte)value; buffer[offset + 1] = (byte)(value >> 8); buffer[offset + 2] = (byte)(value >> 16); buffer[offset + 3] = (byte)(value >> 24); } // Write a big-endian 16-bit integer value to a buffer. public static void WriteUInt16B(byte[] buffer, int offset, int value) { buffer[offset + 1] = (byte)value; buffer[offset] = (byte)(value >> 8); } // Write a big-endian 32-bit integer value to a buffer. public static void WriteInt32B(byte[] buffer, int offset, int value) { buffer[offset + 3] = (byte)value; buffer[offset + 2] = (byte)(value >> 8); buffer[offset + 1] = (byte)(value >> 16); buffer[offset] = (byte)(value >> 24); } // Write a BGR value to a buffer as an RGBQUAD. public static void WriteBGR(byte[] buffer, int offset, int value) { buffer[offset] = (byte)value; buffer[offset + 1] = (byte)(value >> 8); buffer[offset + 2] = (byte)(value >> 16); buffer[offset + 3] = (byte)0; } // Write an RGB value to a buffer as a triple. public static void WriteRGB(byte[] buffer, int offset, int value) { buffer[offset + 2] = (byte)value; buffer[offset + 1] = (byte)(value >> 8); buffer[offset] = (byte)(value >> 16); } // Perform a forward-seek on a stream, even on streams that // cannot support seeking properly. "current" is the current // position in the stream, and "offset" is the desired offset. public static void Seek(Stream stream, long current, long offset) { if(offset < current) { throw new FormatException(); } else if(offset == current) { return; } if(stream.CanSeek) { stream.Seek(offset, SeekOrigin.Begin); } else { byte[] buffer = new byte [1024]; int len; while(current < offset) { if((offset - current) < 1024) { len = (int)(offset - current); } else { len = 1024; } if(stream.Read(buffer, 0, len) != len) { throw new FormatException(); } } } } // Convert a pixel format into a stride value. public static int FormatToStride(PixelFormat pixelFormat, int width) { return ((BytesPerLine(pixelFormat, width) + 3) & ~3); } public static int BytesPerLine(PixelFormat pixelFormat, int width) { int lineBytes; switch(pixelFormat) { case PixelFormat.Format1bppIndexed: lineBytes = (width + 7) / 8; break; case PixelFormat.Format4bppIndexed: lineBytes = (width + 1) / 2; break; case PixelFormat.Format8bppIndexed: lineBytes = width; break; case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: lineBytes = width * 2; break; case PixelFormat.Format24bppRgb: lineBytes = width * 3; break; case PixelFormat.Format32bppRgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppArgb: default: lineBytes = width * 4; break; case PixelFormat.Format48bppRgb: lineBytes = width * 6; break; case PixelFormat.Format64bppPArgb: case PixelFormat.Format64bppArgb: lineBytes = width * 8; break; } return lineBytes; } // Convert a pixel format into a bit count value. public static int FormatToBitCount(PixelFormat pixelFormat) { switch(pixelFormat) { case PixelFormat.Format1bppIndexed: return 1; case PixelFormat.Format4bppIndexed: return 4; case PixelFormat.Format8bppIndexed: return 8; case PixelFormat.Format16bppRgb555: case PixelFormat.Format16bppRgb565: case PixelFormat.Format16bppArgb1555: case PixelFormat.Format16bppGrayScale: return 16; case PixelFormat.Format24bppRgb: return 24; case PixelFormat.Format32bppRgb: case PixelFormat.Format32bppPArgb: case PixelFormat.Format32bppArgb: return 32; case PixelFormat.Format48bppRgb: return 48; case PixelFormat.Format64bppPArgb: case PixelFormat.Format64bppArgb: return 64; default: return 32; } } // Convert a bit count into a pixel format. public static PixelFormat BitCountToFormat(int bitCount) { switch(bitCount) { case 1: return PixelFormat.Format1bppIndexed; case 4: return PixelFormat.Format4bppIndexed; case 8: return PixelFormat.Format8bppIndexed; case 15: return PixelFormat.Format16bppRgb555; case 16: return PixelFormat.Format16bppRgb565; case 24: return PixelFormat.Format24bppRgb; case 32: default: return PixelFormat.Format32bppRgb; case 48: return PixelFormat.Format48bppRgb; case 64: return PixelFormat.Format64bppArgb; } } // Return the index to a closest matched color in the palette. public static int BestPaletteColor(int[] palette, int r, int g, int b) { int distance = 200000; int j = -1; for( int i = 0; i < palette.Length; i++) { int color = palette[i]; int bDist = (byte)color - b; int gDist = (byte)(color >>8) - g; int rDist = (byte)(color>>16) - r; int d = bDist * bDist + gDist * gDist + rDist * rDist; if (d < distance) { distance = d; j = i; if (distance == 0) break; } } return j; } // Return the index to a closest matched color in the palette. public static int BestPaletteColor(int[] palette, int color) { return BestPaletteColor(palette, (byte)(color >> 16), (byte)(color >> 8), (byte)color); } }; // class Utils }; // namespace DotGNU.Images
// ==++== // // // Copyright (c) 2006 Microsoft Corporation. All rights reserved. // // The use and distribution terms for this software are contained in the file // named license.txt, which can be found in the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by the // terms of this license. // // You must not remove this notice, or any other, from this software. // // // ==--== namespace Microsoft.JScript { using System; using System.Collections; using System.Collections.Generic; using System.Configuration.Assemblies; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Security.Permissions; internal sealed class CustomAttribute : AST{ private AST ctor; private ASTList args; private AST target; //indicates what kind of member the custom attribute is being applied to internal Object type; // will contain either the Type or ClassScope for the custom attribute type private ArrayList positionalArgValues; private ArrayList namedArgFields; private ArrayList namedArgFieldValues; private ArrayList namedArgProperties; private ArrayList namedArgPropertyValues; internal bool raiseToPropertyLevel; internal CustomAttribute(Context context, AST func, ASTList args) : base(context) { this.ctor = func; this.args = args; this.target = null; this.type = null; this.positionalArgValues = new ArrayList(); this.namedArgFields = new ArrayList(); this.namedArgFieldValues = new ArrayList(); this.namedArgProperties = new ArrayList(); this.namedArgPropertyValues = new ArrayList(); this.raiseToPropertyLevel = false; } //Check that custom attribute is applicable to its target private bool CheckIfTargetOK(Object caType){ if (caType == null) return false; AttributeTargets validOn = (AttributeTargets)0; Type caTypeT = caType as Type; if (caTypeT != null){ Object[] usage = CustomAttribute.GetCustomAttributes(caTypeT, typeof(AttributeUsageAttribute), true); validOn = ((AttributeUsageAttribute)usage[0]).ValidOn; }else validOn = ((ClassScope)caType).owner.validOn; Object target = this.target; Class c = target as Class; if (c != null){ if (c.isInterface){ if ((validOn & AttributeTargets.Interface) != 0) return true; }else if (c is EnumDeclaration){ if ((validOn & AttributeTargets.Enum) != 0) return true; }else if ((validOn & AttributeTargets.Class) != 0){ if (caTypeT == typeof(AttributeUsageAttribute)){ //This is an attribute that describes a new attribute class //Set the validOn field of Class so that it becomes easier to check the usage of the new attribute if (this.positionalArgValues.Count > 0){ Object par0 = this.positionalArgValues[0]; if (par0 is AttributeTargets) c.validOn = (AttributeTargets)par0; } for (int i = 0, n = this.namedArgProperties.Count; i < n; i++){ PropertyInfo prop = this.namedArgProperties[i] as PropertyInfo; if (prop.Name == "AllowMultiple") c.allowMultiple = (bool)this.namedArgPropertyValues[i]; } } return true; }else if (caTypeT.FullName == "System.NonSerializedAttribute"){ c.attributes &= ~TypeAttributes.Serializable; return false; } this.context.HandleError(JSError.InvalidCustomAttributeTarget, CustomAttribute.GetTypeName(caType)); return false; } FunctionDeclaration fDecl = target as FunctionDeclaration; if (fDecl != null){ if ((validOn & AttributeTargets.Property) != 0 && fDecl.enclosingProperty != null){ if (fDecl.enclosingProperty.getter == null || ((JSFieldMethod)fDecl.enclosingProperty.getter).func == fDecl.func){ this.raiseToPropertyLevel = true; return true; }else{ this.context.HandleError(JSError.PropertyLevelAttributesMustBeOnGetter); return false; } } if ((validOn & AttributeTargets.Method) != 0 && fDecl.isMethod) return true; if ((validOn & AttributeTargets.Constructor) != 0 && fDecl.func.isConstructor) return true; this.context.HandleError(JSError.InvalidCustomAttributeTarget, CustomAttribute.GetTypeName(caType)); return false; } if (target is VariableDeclaration || target is Constant){ if ((validOn & AttributeTargets.Field) != 0) return true; this.context.HandleError(JSError.InvalidCustomAttributeTarget, CustomAttribute.GetTypeName(caType)); return false; } if (target is AssemblyCustomAttributeList && (validOn & AttributeTargets.Assembly) != 0) return true; if (target == null && (validOn & AttributeTargets.Parameter) != 0) return true; this.context.HandleError(JSError.InvalidCustomAttributeTarget, CustomAttribute.GetTypeName(caType)); return false; } private static ushort DaysSince2000(){ return (ushort)(DateTime.Now - new DateTime(2000, 1, 1)).Days; } internal override Object Evaluate(){ ConstructorInfo c = (ConstructorInfo)((Binding)this.ctor).member; ParameterInfo[] pars = c.GetParameters(); int pn = pars.Length; for (int i = positionalArgValues.Count; i < pn; i++) positionalArgValues.Add(Convert.CoerceT(null, pars[i].ParameterType)); Object[] pArgVals = new Object[pn]; positionalArgValues.CopyTo(0, pArgVals, 0, pn); Object ca = c.Invoke(BindingFlags.ExactBinding, null, pArgVals, null); for (int i = 0, n = this.namedArgProperties.Count; i < n; i++){ JSProperty prop = this.namedArgProperties[i] as JSProperty; if (prop != null) prop.SetValue(ca, Convert.Coerce(this.namedArgPropertyValues[i], prop.PropertyIR()), null); else ((PropertyInfo)this.namedArgProperties[i]).SetValue(ca, this.namedArgPropertyValues[i], null); } for (int i = 0, n = this.namedArgFields.Count; i < n; i++){ JSVariableField field = this.namedArgFields[i] as JSVariableField; if (field != null) field.SetValue(ca, Convert.Coerce(this.namedArgFieldValues[i], field.GetInferredType(null))); else ((FieldInfo)this.namedArgFields[i]).SetValue(ca, this.namedArgFieldValues[i]); } return ca; } internal CLSComplianceSpec GetCLSComplianceValue(){ Debug.Assert(this.type == Typeob.CLSCompliantAttribute); return ((bool)this.positionalArgValues[0]) ? CLSComplianceSpec.CLSCompliant : CLSComplianceSpec.NonCLSCompliant; } private void ConvertClassScopesAndEnumWrappers(ArrayList vals){ for (int i = 0, n = vals.Count; i < n; i++){ ClassScope csc = vals[i] as ClassScope; if (csc != null){ vals[i] = csc.GetTypeBuilder(); continue;} EnumWrapper wrapper = vals[i] as EnumWrapper; if (wrapper != null) vals[i] = wrapper.ToNumericValue(); } } private void ConvertFieldAndPropertyInfos(ArrayList vals){ for (int i = 0, n = vals.Count; i < n; i++){ JSField jsfld = vals[i] as JSField; if (jsfld != null){ vals[i] = jsfld.GetMetaData(); continue;} JSProperty jsprop = vals[i] as JSProperty; if (jsprop != null){ vals[i] = jsprop.metaData; continue;} } } internal CustomAttributeBuilder GetCustomAttribute(){ ConstructorInfo c = (ConstructorInfo)((Binding)this.ctor).member; ParameterInfo[] pars = c.GetParameters(); int pn = pars.Length; if (c is JSConstructor) c = ((JSConstructor)c).GetConstructorInfo(compilerGlobals); this.ConvertClassScopesAndEnumWrappers(this.positionalArgValues); this.ConvertClassScopesAndEnumWrappers(this.namedArgPropertyValues); this.ConvertClassScopesAndEnumWrappers(this.namedArgFieldValues); this.ConvertFieldAndPropertyInfos(this.namedArgProperties); this.ConvertFieldAndPropertyInfos(this.namedArgFields); for (int i = positionalArgValues.Count; i < pn; i++) positionalArgValues.Add(Convert.CoerceT(null, pars[i].ParameterType)); Object[] pArgVals = new Object[pn]; positionalArgValues.CopyTo(0, pArgVals, 0, pn); PropertyInfo[] nArgProps = new PropertyInfo[namedArgProperties.Count]; namedArgProperties.CopyTo(nArgProps); Object[] nArgPVals = new Object[namedArgPropertyValues.Count]; namedArgPropertyValues.CopyTo(nArgPVals); FieldInfo[] nArgFields = new FieldInfo[namedArgFields.Count]; namedArgFields.CopyTo(nArgFields); Object[] nArgFVals = new Object[namedArgFieldValues.Count]; namedArgFieldValues.CopyTo(nArgFVals); return new CustomAttributeBuilder(c, pArgVals, nArgProps, nArgPVals, nArgFields, nArgFVals); } internal Object GetTypeIfAttributeHasToBeUnique(){ Type t = this.type as Type; if (t != null){ Object[] custAttrs = CustomAttribute.GetCustomAttributes(t, typeof(AttributeUsageAttribute), false); if (custAttrs.Length > 0 && !((AttributeUsageAttribute)custAttrs[0]).AllowMultiple) return t; return null; } if (!((ClassScope)this.type).owner.allowMultiple) return this.type; return null; } private static String GetTypeName(Object t){ Type ty = t as Type; if (ty != null) return ty.FullName; return ((ClassScope)t).GetFullName(); } internal bool IsExpandoAttribute(){ //Use only before partial evaluation has been done Lookup id = this.ctor as Lookup; return id != null && id.Name == "expando"; } internal override AST PartiallyEvaluate(){ this.ctor = this.ctor.PartiallyEvaluateAsCallable(); //first weed out assignment expressions and use them as property initializers ASTList positionalArgs = new ASTList(this.args.context); ASTList namedArgs = new ASTList(this.args.context); for (int i = 0, m = this.args.count; i < m; i++){ AST arg = this.args[i]; Assign assign = arg as Assign; if (assign != null){ assign.rhside = assign.rhside.PartiallyEvaluate(); namedArgs.Append(assign); }else positionalArgs.Append(arg.PartiallyEvaluate()); } int n = positionalArgs.count; IReflect[] argIRs = new IReflect[n]; for (int i = 0; i < n; i++){ AST arg = positionalArgs[i]; // only accept ConstantWrappers if (arg is ConstantWrapper){ Object argument = arg.Evaluate(); if ((argIRs[i] = CustomAttribute.TypeOfArgument(argument)) != null){ this.positionalArgValues.Add(argument); continue; } }else if (arg is ArrayLiteral && ((ArrayLiteral)arg).IsOkToUseInCustomAttribute()){ argIRs[i] = Typeob.ArrayObject; this.positionalArgValues.Add(arg.Evaluate()); continue; } arg.context.HandleError(JSError.InvalidCustomAttributeArgument); return null; // the custom attribute is not good and it will be ignored } //Get the custom attribute and the appropriate constructor (under the covers) this.type = this.ctor.ResolveCustomAttribute(positionalArgs, argIRs, this.target); if (this.type == null) return null; if (Convert.IsPromotableTo((IReflect)this.type, Typeob.CodeAccessSecurityAttribute)){ this.context.HandleError(JSError.CannotUseStaticSecurityAttribute); return null; } //Coerce the positional arguments to the right type and supply default values for optional parameters ConstructorInfo c = (ConstructorInfo)((Binding)this.ctor).member; ParameterInfo[] parameters = c.GetParameters(); int j = 0; int len = this.positionalArgValues.Count; foreach (ParameterInfo p in parameters){ IReflect ir = p is ParameterDeclaration ? ((ParameterDeclaration)p).ParameterIReflect : p.ParameterType; if (j < len ){ Object value = this.positionalArgValues[j]; this.positionalArgValues[j] = Convert.Coerce(value, ir, value is ArrayObject); j++; }else{ Object value; if (TypeReferences.GetDefaultParameterValue(p) == System.Convert.DBNull){ value = Convert.Coerce(null, ir); }else value = TypeReferences.GetDefaultParameterValue(p); this.positionalArgValues.Add(value); } } //Check validity of property/field initializers for (int i = 0, m = namedArgs.count; i < m; i++){ Assign assign = (Assign)namedArgs[i]; if (assign.lhside is Lookup && (assign.rhside is ConstantWrapper || (assign.rhside is ArrayLiteral && ((ArrayLiteral)assign.rhside).IsOkToUseInCustomAttribute()))){ Object value = assign.rhside.Evaluate(); IReflect argType = null; if (value is ArrayObject || ((argType = CustomAttribute.TypeOfArgument(value)) != null && argType != Typeob.Object)){ String name = ((Lookup)assign.lhside).Name; MemberInfo [] members = ((IReflect)this.type).GetMember(name, BindingFlags.Public|BindingFlags.Instance); if (members == null || members.Length == 0){ assign.context.HandleError(JSError.NoSuchMember); return null; } if (members.Length == 1){ MemberInfo member = members[0]; if (member is FieldInfo){ FieldInfo fieldInfo = (FieldInfo)member; if (!fieldInfo.IsLiteral && !fieldInfo.IsInitOnly){ try{ IReflect ir = fieldInfo is JSVariableField ? ((JSVariableField)fieldInfo).GetInferredType(null) : fieldInfo.FieldType; value = Convert.Coerce(value, ir, value is ArrayObject); this.namedArgFields.Add(member); this.namedArgFieldValues.Add(value); continue; }catch(JScriptException){ assign.rhside.context.HandleError(JSError.TypeMismatch); return null; // the custom attribute is not good and it will be ignored } } }else if (member is PropertyInfo){ PropertyInfo propertyInfo = (PropertyInfo)member; MethodInfo setMethodInfo = JSProperty.GetSetMethod(propertyInfo, false); if (setMethodInfo != null){ ParameterInfo [] paramInfo = setMethodInfo.GetParameters(); if (paramInfo != null && paramInfo.Length == 1){ try{ IReflect ir = paramInfo[0] is ParameterDeclaration ? ((ParameterDeclaration)paramInfo[0]).ParameterIReflect : paramInfo[0].ParameterType; value = Convert.Coerce(value, ir, value is ArrayObject); this.namedArgProperties.Add(member); this.namedArgPropertyValues.Add(value); }catch(JScriptException){ assign.rhside.context.HandleError(JSError.TypeMismatch); return null; // the custom attribute is not good and it will be ignored } continue; } } } } } } assign.context.HandleError(JSError.InvalidCustomAttributeArgument); return null; } if (!this.CheckIfTargetOK(this.type)) return null; //Ignore attribute //Consume and discard assembly name attributes try{ Type ty = this.type as Type; if (ty != null && this.target is AssemblyCustomAttributeList){ if (ty.FullName == "System.Reflection.AssemblyAlgorithmIdAttribute"){ if (this.positionalArgValues.Count > 0) this.Engine.Globals.assemblyHashAlgorithm = (AssemblyHashAlgorithm)Convert.CoerceT(this.positionalArgValues[0], typeof(AssemblyHashAlgorithm)); return null; } if (ty.FullName == "System.Reflection.AssemblyCultureAttribute"){ if (this.positionalArgValues.Count > 0){ String cultureId = Convert.ToString(this.positionalArgValues[0]); if (this.Engine.PEFileKind != PEFileKinds.Dll && cultureId.Length > 0){ this.context.HandleError(JSError.ExecutablesCannotBeLocalized); return null; } this.Engine.Globals.assemblyCulture = new CultureInfo(cultureId); } return null; } if (ty.FullName == "System.Reflection.AssemblyDelaySignAttribute"){ if (this.positionalArgValues.Count > 0) this.Engine.Globals.assemblyDelaySign = Convert.ToBoolean(this.positionalArgValues[0], false); return null; } if (ty.FullName == "System.Reflection.AssemblyFlagsAttribute"){ if (this.positionalArgValues.Count > 0) this.Engine.Globals.assemblyFlags = (AssemblyFlags)(uint)Convert.CoerceT(this.positionalArgValues[0], typeof(uint)); return null; } if (ty.FullName == "System.Reflection.AssemblyKeyFileAttribute"){ if (this.positionalArgValues.Count > 0){ this.Engine.Globals.assemblyKeyFileName = Convert.ToString(this.positionalArgValues[0]); this.Engine.Globals.assemblyKeyFileNameContext = this.context; if (this.Engine.Globals.assemblyKeyFileName != null && this.Engine.Globals.assemblyKeyFileName.Length == 0) { this.Engine.Globals.assemblyKeyFileName = null; this.Engine.Globals.assemblyKeyFileNameContext = null; } } return null; } if (ty.FullName == "System.Reflection.AssemblyKeyNameAttribute"){ if (this.positionalArgValues.Count > 0){ this.Engine.Globals.assemblyKeyName = Convert.ToString(this.positionalArgValues[0]); this.Engine.Globals.assemblyKeyNameContext = this.context; if (this.Engine.Globals.assemblyKeyName != null && this.Engine.Globals.assemblyKeyName.Length == 0) { this.Engine.Globals.assemblyKeyName = null; this.Engine.Globals.assemblyKeyNameContext = null; } } return null; } if (ty.FullName == "System.Reflection.AssemblyVersionAttribute"){ if (this.positionalArgValues.Count > 0) this.Engine.Globals.assemblyVersion = this.ParseVersion(Convert.ToString(this.positionalArgValues[0])); return null; } if (ty.FullName == "System.CLSCompliantAttribute"){ this.Engine.isCLSCompliant = this.args == null || this.args.count == 0 || Convert.ToBoolean(this.positionalArgValues[0], false); return this; } } }catch(ArgumentException){ this.context.HandleError(JSError.InvalidCall); } return this; } private Version ParseVersion(String vString){ ushort major = 1; ushort minor = 0; ushort build = 0; ushort revision = 0; try{ int n = vString.Length; int i = vString.IndexOf('.', 0); if (i < 0) throw new Exception(); major = UInt16.Parse(vString.Substring(0, i), CultureInfo.InvariantCulture); int j = vString.IndexOf('.', i+1); if (j < i+1) minor = UInt16.Parse(vString.Substring(i+1, n-i-1), CultureInfo.InvariantCulture); else{ minor = UInt16.Parse(vString.Substring(i+1, j-i-1), CultureInfo.InvariantCulture); if (vString[j+1] == '*'){ build = CustomAttribute.DaysSince2000(); revision = CustomAttribute.SecondsSinceMidnight(); }else{ int k = vString.IndexOf('.', j+1); if (k < j+1) build = UInt16.Parse(vString.Substring(j+1, n-j-1), CultureInfo.InvariantCulture); else{ build = UInt16.Parse(vString.Substring(j+1, k-j-1), CultureInfo.InvariantCulture); if (vString[k+1] == '*') revision = CustomAttribute.SecondsSinceMidnight(); else revision = UInt16.Parse(vString.Substring(k+1, n-k-1), CultureInfo.InvariantCulture); } } } }catch{ this.args[0].context.HandleError(JSError.NotValidVersionString); } return new Version(major, minor, build, revision); } private static ushort SecondsSinceMidnight(){ TimeSpan sinceMidnight = DateTime.Now - DateTime.Today; return (ushort)((sinceMidnight.Hours*60*60+sinceMidnight.Minutes*60+sinceMidnight.Seconds)/2); } internal void SetTarget(AST target){ this.target = target; } internal override void TranslateToIL(ILGenerator il, Type rtype){ } internal override void TranslateToILInitializer(ILGenerator il){ } internal static IReflect TypeOfArgument(Object argument){ if (argument is Enum) return argument.GetType(); else if (argument is EnumWrapper) return ((EnumWrapper)argument).classScopeOrType; else{ switch (Convert.GetTypeCode(argument)){ case TypeCode.Empty: case TypeCode.DBNull: return Typeob.Object; case TypeCode.Boolean: return Typeob.Boolean; case TypeCode.Char: return Typeob.Char; case TypeCode.Byte: return Typeob.Byte; case TypeCode.UInt16: return Typeob.UInt16; case TypeCode.UInt32: return Typeob.UInt32; case TypeCode.UInt64: return Typeob.UInt64; case TypeCode.SByte: return Typeob.SByte; case TypeCode.Int16: return Typeob.Int16; case TypeCode.Int32: return Typeob.Int32; case TypeCode.Int64: return Typeob.Int64; case TypeCode.Single: return Typeob.Single; case TypeCode.Double: return Typeob.Double; case TypeCode.Object: if (argument is Type) return Typeob.Type; if (argument is ClassScope) return Typeob.Type; break; case TypeCode.String: return Typeob.String; } return null; } } // These APIs are to detect and support ReflectionOnlyLoadFrom which is used at compile time. // If it isn't the reflection only case, then the normal API to get attributes is used. // // At compile time, the only custom attributes which we extract using GetCustomAttributes are: // Microsoft.JScript.JSFunctionAttribute // Microsoft.JScript.NotRecommended // Microsoft.JScript.ReferenceAttribute // System.AttributeUsageAttribute // System.CLSCompliantAttribute // System.ObsoleteAttribute // System.Runtime.InteropServices.CoClassAttribute // System.Security.AllowPartiallyTrustedCallersAttribute // // The only ones we check for using IsDefined are: // Microsoft.JScript.Expando // Microsoft.JScript.JSFunctionAttribute // System.ParamArrayAttribute // System.Runtime.CompilerServices.RequiredAttributeAttribute // // None of these are Inherited attibutes and so the ReflectionOnly code path can ignore the // inherit flag. The System.* attributes are sealed. The Microsoft.JScript ones are not, // though they should be and the compiler will not respect subtypes of these attributes. // private static Object GetCustomAttributeValue(CustomAttributeTypedArgument arg) { Type reflectionOnlyArgType = arg.ArgumentType; // If it's an enumerated type, the value is the boxed underlying value and must be converted. if (reflectionOnlyArgType.IsEnum) return Enum.ToObject(Type.GetType(reflectionOnlyArgType.FullName), arg.Value); return arg.Value; } internal static Object[] GetCustomAttributes(Assembly target, Type caType, bool inherit) { if (!target.ReflectionOnly) return target.GetCustomAttributes(caType, inherit); return CustomAttribute.ExtractCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType); } internal static Object[] GetCustomAttributes(Module target, Type caType, bool inherit) { if (!target.Assembly.ReflectionOnly) return target.GetCustomAttributes(caType, inherit); return CustomAttribute.ExtractCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType); } internal static Object[] GetCustomAttributes(MemberInfo target, Type caType, bool inherit) { // JScript implements subclasses of MemberInfo which throw an exception when Module is // accessed. We know that none of these are from a ReflectionOnly assembly. Type t = target.GetType(); if (t.Assembly == typeof(CustomAttribute).Assembly || !target.Module.Assembly.ReflectionOnly) return target.GetCustomAttributes(caType, inherit); return CustomAttribute.ExtractCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType); } internal static Object[] GetCustomAttributes(ParameterInfo target, Type caType, bool inherit) { // JScript implements subclasses of ParameterInfo which throw an exception when Module is // accessed. We know that none of these are from a ReflectionOnly assembly. Type t = target.GetType(); if (t.Assembly == typeof(CustomAttribute).Assembly || !target.Member.Module.Assembly.ReflectionOnly) return target.GetCustomAttributes(caType, inherit); return CustomAttribute.ExtractCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType); } // This is the common processing code to extract the attributes from the list returned // by the custom attribute data reflector. private static Object[] ExtractCustomAttribute(IList<CustomAttributeData> attributes, Type caType) { // None of the custom attributes we check for have AllowMultiple == true Debug.Assert( caType == typeof(Microsoft.JScript.JSFunctionAttribute) || caType == typeof(Microsoft.JScript.NotRecommended) || caType == typeof(Microsoft.JScript.ReferenceAttribute) || caType == typeof(System.AttributeUsageAttribute) || caType == typeof(System.CLSCompliantAttribute) || caType == typeof(System.ObsoleteAttribute) || caType == typeof(System.Security.AllowPartiallyTrustedCallersAttribute) || caType == typeof(System.ParamArrayAttribute)); Type caReflectionOnlyType = Globals.TypeRefs.ToReferenceContext(caType); foreach(CustomAttributeData caData in attributes) { if (caData.Constructor.DeclaringType == caReflectionOnlyType) { // Build up the constructor argument list and create an instance. ArrayList args = new ArrayList(); foreach(CustomAttributeTypedArgument arg in caData.ConstructorArguments) { args.Add(CustomAttribute.GetCustomAttributeValue(arg)); } Object instance = Activator.CreateInstance(caType, args.ToArray()); // Populate the public fields. foreach(CustomAttributeNamedArgument namedArg in caData.NamedArguments) { caType.InvokeMember(namedArg.MemberInfo.Name, BindingFlags.Instance|BindingFlags.Public|BindingFlags.SetField|BindingFlags.SetProperty, null, instance, new Object[1] { CustomAttribute.GetCustomAttributeValue(namedArg.TypedValue) }, null, CultureInfo.InvariantCulture, null); } return new Object[1] { instance }; } } return new Object[0]; } internal static bool IsDefined(MemberInfo target, Type caType, bool inherit) { // JScript implements subclasses of MemberInfo which throw an exception when Module is // accessed. We know that none of these are from a ReflectionOnly assembly. Type t = target.GetType(); if (t.Assembly == typeof(CustomAttribute).Assembly || !target.Module.Assembly.ReflectionOnly) return target.IsDefined(caType, inherit); return CustomAttribute.CheckForCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType); } internal static bool IsDefined(ParameterInfo target, Type caType, bool inherit) { // JScript implements subclasses of ParameterInfo which throw an exception when Module is // accessed. We know that none of these are from a ReflectionOnly assembly. Type t = target.GetType(); if (t.Assembly == typeof(CustomAttribute).Assembly || !target.Member.Module.Assembly.ReflectionOnly) return target.IsDefined(caType, inherit); return CustomAttribute.CheckForCustomAttribute(CustomAttributeData.GetCustomAttributes(target), caType); } private static bool CheckForCustomAttribute(IList<CustomAttributeData> attributes, Type caType) { Debug.Assert( caType == typeof(Microsoft.JScript.Expando) || caType == typeof(Microsoft.JScript.JSFunctionAttribute) || caType == typeof(System.ParamArrayAttribute) || caType == typeof(System.Runtime.CompilerServices.RequiredAttributeAttribute)); Type caReflectionOnlyType = Globals.TypeRefs.ToReferenceContext(caType); foreach(CustomAttributeData caData in attributes) { if (caData.Constructor.DeclaringType == caReflectionOnlyType) return true; } return false; } } }
using System; using System.Linq; using FluentAssertions; using NUnit.Framework; using Quartz.Impl.Triggers; using Quartz.Simpl; using Quartz.Spi; using Quartz.Util; using TimeZoneConverter; namespace Quartz.Tests.Unit { [TestFixture(typeof(BinaryObjectSerializer))] [TestFixture(typeof(JsonObjectSerializer))] public class CalendarIntervalTriggerTest : SerializationTestSupport<CalendarIntervalTriggerImpl> { public CalendarIntervalTriggerTest(Type serializerType) : base(serializerType) { } [Test] public void TestYearlyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var yearlyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Year, RepeatInterval = 2 // every two years; }; DateTimeOffset targetCalendar = startCalendar.AddYears(4); var fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 4); DateTimeOffset thirdTime = fireTimes[2]; // get the third fire time Assert.AreEqual(targetCalendar, thirdTime, "Year increment result not as expected."); } [Test] public void TestMonthlyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var yearlyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Month, RepeatInterval = 5 // every five months }; DateTimeOffset targetCalendar = startCalendar.AddMonths(25); // jump 25 five months (5 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6); DateTimeOffset sixthTime = fireTimes[5]; // get the sixth fire time Assert.AreEqual(targetCalendar, sixthTime, "Month increment result not as expected."); } [Test] public void TestWeeklyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var yearlyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Week, RepeatInterval = 6 // every six weeks }; DateTimeOffset targetCalendar = startCalendar.AddDays(7*6*4); // jump 24 weeks (4 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 7); DateTimeOffset fifthTime = fireTimes[4]; // get the fifth fire time Assert.AreEqual(targetCalendar, fifthTime, "Week increment result not as expected."); } [Test] public void TestDailyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var dailyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Day, RepeatInterval = 90 // every ninety days }; DateTimeOffset targetCalendar = startCalendar.AddDays(360); // jump 360 days (4 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); DateTimeOffset fifthTime = fireTimes[4]; // get the fifth fire time Assert.AreEqual(targetCalendar, fifthTime, "Day increment result not as expected."); } [Test] public void TestHourlyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var yearlyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Hour, RepeatInterval = 100 // every 100 hours }; DateTimeOffset targetCalendar = startCalendar.AddHours(400); // jump 400 hours (4 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6); DateTimeOffset fifthTime = fireTimes[4]; // get the fifth fire time Assert.AreEqual(targetCalendar, fifthTime, "Hour increment result not as expected."); } [Test] public void TestMinutelyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var yearlyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Minute, RepeatInterval = 100 // every 100 minutes }; DateTimeOffset targetCalendar = startCalendar.AddMinutes(400); // jump 400 minutes (4 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6); DateTimeOffset fifthTime = fireTimes[4]; // get the fifth fire time Assert.AreEqual(targetCalendar, fifthTime, "Minutes increment result not as expected."); } [Test] public void TestSecondlyIntervalGetFireTimeAfter() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 1, 6, 2005); var yearlyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Second, RepeatInterval = 100 // every 100 seconds }; DateTimeOffset targetCalendar = startCalendar.AddSeconds(400); // jump 400 seconds (4 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(yearlyTrigger, null, 6); DateTimeOffset fifthTime = fireTimes[4]; // get the third fire time Assert.AreEqual(targetCalendar, fifthTime, "Seconds increment result not as expected."); } [Test] public void TestDaylightSavingsTransitions() { // Pick a day before a spring daylight savings transition... DateTimeOffset startCalendar = DateBuilder.DateOf(9, 30, 17, 12, 3, 2010); var dailyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Day, RepeatInterval = 5 // every 5 days }; DateTimeOffset targetCalendar = startCalendar.AddDays(10); // jump 10 days (2 intervals) var fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); DateTimeOffset testTime = fireTimes[2]; // get the third fire time Assert.AreEqual(targetCalendar, testTime, "Day increment result not as expected over spring 2010 daylight savings transition."); // And again, Pick a day before a spring daylight savings transition... (QTZ-240) startCalendar = new DateTime(2011, 3, 12, 1, 0, 0); dailyTrigger = new CalendarIntervalTriggerImpl(); dailyTrigger.StartTimeUtc = startCalendar; dailyTrigger.RepeatIntervalUnit = IntervalUnit.Day; dailyTrigger.RepeatInterval = 1; // every day targetCalendar = startCalendar.AddDays(2); // jump 2 days (2 intervals) fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); testTime = fireTimes[2]; // get the third fire time Assert.AreEqual(targetCalendar, testTime, "Day increment result not as expected over spring 2011 daylight savings transition."); // And again, Pick a day before a spring daylight savings transition... (QTZ-240) - and prove time of day is not preserved without setPreserveHourOfDayAcrossDaylightSavings(true) var cetTimeZone = TimeZoneUtil.FindTimeZoneById("Central European Standard Time"); startCalendar = TimeZoneInfo.ConvertTime(new DateTime(2011, 3, 26, 4, 0, 0), cetTimeZone); dailyTrigger = new CalendarIntervalTriggerImpl(); dailyTrigger.StartTimeUtc = startCalendar; dailyTrigger.RepeatIntervalUnit = IntervalUnit.Day; dailyTrigger.RepeatInterval = 1; // every day targetCalendar = TimeZoneUtil.ConvertTime(startCalendar, cetTimeZone); targetCalendar = targetCalendar.AddDays(2); // jump 2 days (2 intervals) fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); testTime = fireTimes[2]; // get the third fire time DateTimeOffset testCal = TimeZoneUtil.ConvertTime(testTime, cetTimeZone); Assert.AreNotEqual(targetCalendar.Hour, testCal.Hour, "Day increment time-of-day result not as expected over spring 2011 daylight savings transition."); // And again, Pick a day before a spring daylight savings transition... (QTZ-240) - and prove time of day is preserved with setPreserveHourOfDayAcrossDaylightSavings(true) startCalendar = TimeZoneUtil.ConvertTime(new DateTime(2011, 3, 26, 4, 0, 0), cetTimeZone); dailyTrigger = new CalendarIntervalTriggerImpl(); dailyTrigger.StartTimeUtc = startCalendar; dailyTrigger.RepeatIntervalUnit = IntervalUnit.Day; dailyTrigger.RepeatInterval = 1; // every day dailyTrigger.TimeZone = cetTimeZone; dailyTrigger.PreserveHourOfDayAcrossDaylightSavings = true; targetCalendar = startCalendar.AddDays(2); // jump 2 days (2 intervals) fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); testTime = fireTimes[1]; // get the second fire time testCal = TimeZoneUtil.ConvertTime(testTime, cetTimeZone); Assert.AreEqual(targetCalendar.Hour, testCal.Hour, "Day increment time-of-day result not as expected over spring 2011 daylight savings transition."); // Pick a day before a fall daylight savings transition... startCalendar = new DateTimeOffset(2010, 10, 31, 9, 30, 17, TimeSpan.Zero); dailyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Day, RepeatInterval = 5 // every 5 days }; targetCalendar = startCalendar.AddDays(15); // jump 15 days (3 intervals) fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); testTime = fireTimes[3]; // get the fourth fire time Assert.AreEqual(targetCalendar, testTime, "Day increment result not as expected over fall daylight savings transition."); } [Test] public void TestFinalFireTimes() { DateTimeOffset startCalendar = DateBuilder.DateOf(9, 0, 0, 12, 3, 2010); DateTimeOffset endCalendar = startCalendar.AddDays(10); // jump 10 days (2 intervals) var dailyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Day, RepeatInterval = 5, // every 5 days EndTimeUtc = endCalendar }; DateTimeOffset? testTime = dailyTrigger.FinalFireTimeUtc; Assert.AreEqual(endCalendar, testTime, "Final fire time not computed correctly for day interval."); endCalendar = startCalendar.AddDays(15).AddMinutes(-2); // jump 15 days and back up 2 minutes dailyTrigger = new CalendarIntervalTriggerImpl { StartTimeUtc = startCalendar, RepeatIntervalUnit = IntervalUnit.Minute, RepeatInterval = 5, // every 5 minutes EndTimeUtc = endCalendar }; testTime = dailyTrigger.FinalFireTimeUtc; Assert.IsTrue(endCalendar > testTime, "Final fire time not computed correctly for minutely interval."); endCalendar = endCalendar.AddMinutes(-3); // back up three more minutes Assert.AreEqual(endCalendar, testTime, "Final fire time not computed correctly for minutely interval."); } [Test] public void TestMisfireInstructionValidity() { var trigger = new CalendarIntervalTriggerImpl(); try { trigger.MisfireInstruction = MisfireInstruction.IgnoreMisfirePolicy; trigger.MisfireInstruction = MisfireInstruction.SmartPolicy; trigger.MisfireInstruction = MisfireInstruction.CalendarIntervalTrigger.DoNothing; trigger.MisfireInstruction = MisfireInstruction.CalendarIntervalTrigger.FireOnceNow; } catch (Exception) { Assert.Fail("Unexpected exception while setting misfire instruction."); } try { trigger.MisfireInstruction = MisfireInstruction.CalendarIntervalTrigger.DoNothing + 1; Assert.Fail("Expected exception while setting invalid misfire instruction but did not get it."); } catch (Exception ex) { if (ex is AssertionException) { throw; } } } [Test] public void TestTimeZoneTransition() { TimeZoneInfo timeZone = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); CalendarIntervalTriggerImpl trigger = new CalendarIntervalTriggerImpl("trigger", IntervalUnit.Day, 1); trigger.TimeZone = timeZone; trigger.StartTimeUtc = new DateTimeOffset(2012, 11, 2, 12, 0, 0, TimeSpan.FromHours(-4)); var fireTimes = TriggerUtils.ComputeFireTimes(trigger, null, 6); var expected = new DateTimeOffset(2012, 11, 2, 12, 0, 0, TimeSpan.FromHours(-4)); Assert.AreEqual(expected, fireTimes[0]); expected = new DateTimeOffset(2012, 11, 3, 12, 0, 0, TimeSpan.FromHours(-4)); Assert.AreEqual(expected, fireTimes[1]); //this next day should be a new daylight savings change, notice the change in offset expected = new DateTimeOffset(2012, 11, 4, 11, 0, 0, TimeSpan.FromHours(-5)); Assert.AreEqual(expected, fireTimes[2]); expected = new DateTimeOffset(2012, 11, 5, 11, 0, 0, TimeSpan.FromHours(-5)); Assert.AreEqual(expected, fireTimes[3]); } [Test] public void TestSkipDayIfItDoesNotExists() { TimeZoneInfo timeZone = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); //March 11, 2012, EST DST starts at 2am and jumps to 3. // 3/11/2012 2:00:00 AM is an invalid time //------------------------------------------------- // DAILY //------------------------------------------------- CalendarIntervalTriggerImpl trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Day; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = true; DateTimeOffset startDate = new DateTimeOffset(2012, 3, 10, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; var fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); var targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); DateTimeOffset expectedTarget = new DateTimeOffset(2012, 3, 12, 2, 0, 0, TimeSpan.FromHours(-4)); // 3/12/2012 2am Assert.AreEqual(expectedTarget, targetTime); //------------------------------------------------- // WEEKLY //------------------------------------------------- trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Week; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = true; startDate = new DateTimeOffset(2012, 3, 4, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); expectedTarget = new DateTimeOffset(2012, 3, 18, 2, 0, 0, TimeSpan.FromHours(-4)); // 3/18/2012 2am Assert.AreEqual(expectedTarget, targetTime); //------------------------------------------------- // MONTHLY //------------------------------------------------- trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Month; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = true; startDate = new DateTimeOffset(2012, 2, 11, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); expectedTarget = new DateTimeOffset(2012, 4, 11, 2, 0, 0, TimeSpan.FromHours(-4)); // 4/11/2012 2am Assert.AreEqual(expectedTarget, targetTime); //------------------------------------------------- // YEARLY //------------------------------------------------- trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Year; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = true; startDate = new DateTimeOffset(2011, 3, 11, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); expectedTarget = new DateTimeOffset(2013, 3, 11, 2, 0, 0, TimeSpan.FromHours(-4)); // 3/11/2013 2am Assert.AreEqual(expectedTarget, targetTime); } [Test] public void TestSkipDayIfItDoesNotExistsIsFalse() { TimeZoneInfo timeZone = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); //March 11, 2012, EST DST starts at 2am and jumps to 3. // 3/11/2012 2:00:00 AM is an invalid time //expected target will always be the on the next valid time, (3/11/2012 3am) in this case DateTimeOffset expectedTarget = new DateTimeOffset(2012, 3, 11, 3, 0, 0, TimeSpan.FromHours(-4)); //------------------------------------------------- // DAILY //------------------------------------------------- CalendarIntervalTriggerImpl trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Day; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = false; DateTimeOffset startDate = new DateTimeOffset(2012, 3, 10, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; var fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); var targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); Assert.AreEqual(expectedTarget, targetTime); //------------------------------------------------- // WEEKLY //------------------------------------------------- trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Week; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = false; startDate = new DateTimeOffset(2012, 3, 4, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); Assert.AreEqual(expectedTarget, targetTime); //------------------------------------------------- // MONTHLY //------------------------------------------------- trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Month; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = false; startDate = new DateTimeOffset(2012, 2, 11, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); Assert.AreEqual(expectedTarget, targetTime); //------------------------------------------------- // YEARLY //------------------------------------------------- trigger = new CalendarIntervalTriggerImpl(); trigger.TimeZone = timeZone; trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Year; trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = false; startDate = new DateTimeOffset(2011, 3, 11, 2, 0, 0, 0, TimeSpan.FromHours(-5)); trigger.StartTimeUtc = startDate; fires = TriggerUtils.ComputeFireTimes(trigger, null, 5); targetTime = fires[1]; //get second fire Assert.IsFalse(timeZone.IsInvalidTime(targetTime.DateTime), "did not seem to skip the day with an hour that doesn't exist."); Assert.AreEqual(expectedTarget, targetTime); } [Test] public void TestStartTimeOnDayInDifferentOffset() { TimeZoneInfo est = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); DateTimeOffset startDate = new DateTimeOffset(2012, 3, 11, 12, 0, 0, TimeSpan.FromHours(-5)); CalendarIntervalTriggerImpl t = new CalendarIntervalTriggerImpl(); t.RepeatInterval = 1; t.RepeatIntervalUnit = IntervalUnit.Day; t.PreserveHourOfDayAcrossDaylightSavings = true; t.SkipDayIfHourDoesNotExist = false; t.StartTimeUtc = startDate; t.TimeZone = est; var fireTimes = TriggerUtils.ComputeFireTimes(t, null, 10); var firstFire = fireTimes[0]; var secondFire = fireTimes[1]; Assert.AreNotEqual(firstFire, secondFire); } [Test] public void TestMovingAcrossDSTAvoidsInfiniteLoop() { TimeZoneInfo est = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); DateTimeOffset startDate = new DateTimeOffset(1990, 10, 27, 0, 0, 0, TimeSpan.FromHours(-4)); CalendarIntervalTriggerImpl t = new CalendarIntervalTriggerImpl(); t.RepeatInterval = 1; t.RepeatIntervalUnit = IntervalUnit.Day; t.PreserveHourOfDayAcrossDaylightSavings = true; t.SkipDayIfHourDoesNotExist = false; t.StartTimeUtc = startDate; t.TimeZone = est; var fireTimes = TriggerUtils.ComputeFireTimes(t, null, 10); var firstFire = fireTimes[0]; var secondFire = fireTimes[1]; Assert.AreNotEqual(firstFire, secondFire); //try to trigger a shift in month startDate = new DateTimeOffset(2012, 6, 1, 0, 0, 0, TimeSpan.FromHours(-4)); t = new CalendarIntervalTriggerImpl(); t.RepeatInterval = 1; t.RepeatIntervalUnit = IntervalUnit.Month; t.PreserveHourOfDayAcrossDaylightSavings = true; t.SkipDayIfHourDoesNotExist = false; t.StartTimeUtc = startDate; t.TimeZone = est; fireTimes = TriggerUtils.ComputeFireTimes(t, null, 10); Assert.AreNotEqual(firstFire, secondFire); } [Test] public void TestCrossingDSTBoundary() { TimeZoneInfo cetTimeZone = TimeZoneUtil.FindTimeZoneById("Central European Standard Time"); DateTimeOffset startCalendar = TimeZoneUtil.ConvertTime(new DateTime(2011, 3, 26, 4, 0, 0), cetTimeZone); CalendarIntervalTriggerImpl dailyTrigger = new CalendarIntervalTriggerImpl(); dailyTrigger.StartTimeUtc = startCalendar; dailyTrigger.RepeatIntervalUnit = IntervalUnit.Day; dailyTrigger.RepeatInterval = 1; dailyTrigger.TimeZone = cetTimeZone; dailyTrigger.PreserveHourOfDayAcrossDaylightSavings = true; var fireTimes = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 6); //none of these should match the previous fire time. for (int i = 1; i < fireTimes.Count; i++) { var previousFire = fireTimes[i - 1]; var currentFire = fireTimes[i]; Assert.AreNotEqual(previousFire, currentFire); } } [Test] public void TestPreserveHourOfDayAcrossDaylightSavingsNotHanging() { TimeZoneInfo est = TimeZoneUtil.FindTimeZoneById("Eastern Standard Time"); DateTimeOffset startTime = new DateTimeOffset(2013, 3, 1, 4, 0, 0, TimeSpan.FromHours(-5)); CalendarIntervalTriggerImpl trigger = new CalendarIntervalTriggerImpl(); trigger.RepeatInterval = 1; trigger.RepeatIntervalUnit = IntervalUnit.Day; trigger.TimeZone = est; trigger.StartTimeUtc = startTime; trigger.PreserveHourOfDayAcrossDaylightSavings = true; DateTimeOffset? fireTimeAfter = new DateTimeOffset(2013, 3, 10, 4, 0, 0, TimeSpan.FromHours(-4)); DateTimeOffset? fireTime = trigger.GetFireTimeAfter(fireTimeAfter); Assert.AreNotEqual(fireTime, fireTimeAfter); Assert.IsTrue(fireTime > fireTimeAfter); } [Test] public void ShouldCreateCorrectFiringsWhenPreservingHourAcrossDaylightSavings() { var tb = TriggerBuilder.Create(); var schedBuilder = CalendarIntervalScheduleBuilder.Create(); schedBuilder.WithIntervalInWeeks(2); schedBuilder .PreserveHourOfDayAcrossDaylightSavings(true) .WithMisfireHandlingInstructionFireAndProceed(); var trigger = tb.StartAt(new DateTimeOffset(new DateTime(2014, 2, 26, 23, 45, 0))) .WithSchedule(schedBuilder) .Build(); DateTimeOffset? fireTime = null; var prevTime = new DateTimeOffset(DateTime.UtcNow); for (int i = 0; i < 100; ++i) { fireTime = trigger.GetFireTimeAfter(fireTime); if (fireTime == null) { break; } var timeSpan = fireTime.Value - prevTime; /* Console.WriteLine("{0}: At {1:yyyy-MM-dd HH:mm:ss} ({2:ddd}) in {3}", i, fireTime.Value.LocalDateTime, fireTime.Value.LocalDateTime, fireTime.Value - prevTime); */ if (i > 1) { Assert.That((int) timeSpan.TotalDays, Is.GreaterThanOrEqualTo(13), "should have had more than 13 days between"); Assert.That((int) timeSpan.TotalDays, Is.LessThanOrEqualTo(15), "should have had less than 15 days between"); } prevTime = fireTime.Value; } } [Test] public void ShouldGetScheduleBuilderWithSameSettingsAsTrigger() { var startTime = DateTimeOffset.UtcNow; var endTime = DateTimeOffset.UtcNow.AddDays(1); var trigger = new CalendarIntervalTriggerImpl("name", "group", startTime, endTime, IntervalUnit.Hour, 10); trigger.PreserveHourOfDayAcrossDaylightSavings = true; trigger.SkipDayIfHourDoesNotExist = true; trigger.TimeZone = TimeZoneInfo.Utc; trigger.MisfireInstruction = MisfireInstruction.CalendarIntervalTrigger.FireOnceNow; var scheduleBuilder = trigger.GetScheduleBuilder(); var cloned = (CalendarIntervalTriggerImpl) scheduleBuilder.Build(); Assert.That(cloned.PreserveHourOfDayAcrossDaylightSavings, Is.EqualTo(trigger.PreserveHourOfDayAcrossDaylightSavings)); Assert.That(cloned.SkipDayIfHourDoesNotExist, Is.EqualTo(trigger.SkipDayIfHourDoesNotExist)); Assert.That(cloned.RepeatInterval, Is.EqualTo(trigger.RepeatInterval)); Assert.That(cloned.RepeatIntervalUnit, Is.EqualTo(trigger.RepeatIntervalUnit)); Assert.That(cloned.MisfireInstruction, Is.EqualTo(trigger.MisfireInstruction)); Assert.That(cloned.TimeZone, Is.EqualTo(trigger.TimeZone)); } [Test(Description = "https://github.com/quartznet/quartznet/issues/505")] public void ShouldRespectTimeZoneForFirstFireTime() { var tz = TZConvert.GetTimeZoneInfo("E. South America Standard Time"); var dailyTrigger = (IOperableTrigger) TriggerBuilder.Create() .StartAt(new DateTime(2017, 1, 4, 15, 0, 0, DateTimeKind.Utc)) .WithCalendarIntervalSchedule(x => x .WithIntervalInDays(2) .InTimeZone(tz)) .Build(); var firstFireTime = TriggerUtils.ComputeFireTimes(dailyTrigger, null, 1).First(); Assert.That(firstFireTime, Is.EqualTo(new DateTimeOffset(2017, 1, 4, 13, 0, 0, TimeSpan.FromHours(-2)))); } [Test] public void TriggerBuilderShouldHandleIgnoreMisfirePolicy() { var trigger1 = TriggerBuilder.Create() .WithCalendarIntervalSchedule(x => x .WithMisfireHandlingInstructionIgnoreMisfires() ) .Build(); var trigger2 = trigger1 .GetTriggerBuilder() .Build(); trigger1.MisfireInstruction.Should().Be(MisfireInstruction.IgnoreMisfirePolicy); trigger2.MisfireInstruction.Should().Be(MisfireInstruction.IgnoreMisfirePolicy); } protected override CalendarIntervalTriggerImpl GetTargetObject() { var jobDataMap = new JobDataMap(); jobDataMap["A"] = "B"; var t = new CalendarIntervalTriggerImpl { Name = "test", Group = "testGroup", CalendarName = "MyCalendar", Description = "CronTriggerDesc", JobDataMap = jobDataMap, RepeatInterval = 5, RepeatIntervalUnit = IntervalUnit.Day }; return t; } protected override void VerifyMatch(CalendarIntervalTriggerImpl original, CalendarIntervalTriggerImpl deserialized) { Assert.IsNotNull(deserialized); Assert.AreEqual(original.Name, deserialized.Name); Assert.AreEqual(original.Group, deserialized.Group); Assert.AreEqual(original.JobName, deserialized.JobName); Assert.AreEqual(original.JobGroup, deserialized.JobGroup); Assert.That(deserialized.StartTimeUtc, Is.EqualTo(original.StartTimeUtc).Within(TimeSpan.FromSeconds(1))); Assert.AreEqual(original.EndTimeUtc, deserialized.EndTimeUtc); Assert.AreEqual(original.CalendarName, deserialized.CalendarName); Assert.AreEqual(original.Description, deserialized.Description); Assert.AreEqual(original.JobDataMap, deserialized.JobDataMap); Assert.AreEqual(original.RepeatInterval, deserialized.RepeatInterval); Assert.AreEqual(original.RepeatIntervalUnit, deserialized.RepeatIntervalUnit); } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ImageAnnotationExamples.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace ExampleLibrary { using System; using System.Reflection; using OxyPlot; using OxyPlot.Annotations; using OxyPlot.Axes; using OxyPlot.Series; [Examples("ImageAnnotation"), Tags("Annotations")] public static class ImageAnnotationExamples { [Example("ImageAnnotation")] public static PlotModel ImageAnnotation() { var model = new PlotModel { Title = "ImageAnnotation", PlotMargins = new OxyThickness(60, 4, 4, 60) }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); OxyImage image; #if UNIVERSAL var assembly = typeof(ImageAnnotationExamples).GetTypeInfo().Assembly; #else var assembly = Assembly.GetExecutingAssembly(); #endif using (var stream = assembly.GetManifestResourceStream("ExampleLibrary.Resources.OxyPlot.png")) { image = new OxyImage(stream); } // Centered in plot area, filling width model.Annotations.Add(new ImageAnnotation { ImageSource = image, Opacity = 0.2, Interpolate = false, X = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0.5, PlotLengthUnit.RelativeToPlotArea), Width = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Middle }); // Relative to plot area, inside top/right corner, 120pt wide model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Width = new PlotLength(120, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Right, VerticalAlignment = VerticalAlignment.Top }); // Relative to plot area, above top/left corner, 20pt high model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), OffsetY = new PlotLength(-5, PlotLengthUnit.ScreenUnits), Height = new PlotLength(20, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); // At the point (50,50), 200pt wide model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(50, PlotLengthUnit.Data), Y = new PlotLength(50, PlotLengthUnit.Data), Width = new PlotLength(200, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); // At the point (50,20), 50 x units wide model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(50, PlotLengthUnit.Data), Y = new PlotLength(20, PlotLengthUnit.Data), Width = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top }); // Relative to the viewport, centered at the bottom, with offset (could also use bottom vertical alignment) model.Annotations.Add(new ImageAnnotation { ImageSource = image, X = new PlotLength(0.5, PlotLengthUnit.RelativeToViewport), Y = new PlotLength(1, PlotLengthUnit.RelativeToViewport), OffsetY = new PlotLength(-35, PlotLengthUnit.ScreenUnits), Height = new PlotLength(30, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top }); // Changing opacity for (int y = 0; y < 10; y++) { model.Annotations.Add( new ImageAnnotation { ImageSource = image, Opacity = (y + 1) / 10.0, X = new PlotLength(10, PlotLengthUnit.Data), Y = new PlotLength(y * 2, PlotLengthUnit.Data), Width = new PlotLength(100, PlotLengthUnit.ScreenUnits), HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Bottom }); } return model; } [Example("ImageAnnotation - gradient backgrounds")] public static PlotModel ImageAnnotationAsBackgroundGradient() { // http://en.wikipedia.org/wiki/Chartjunk var model = new PlotModel { Title = "Using ImageAnnotations to draw a gradient backgrounds", Subtitle = "But do you really want this? This is called 'chartjunk'!", PlotMargins = new OxyThickness(60, 4, 4, 60) }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); // create a gradient image of height n int n = 256; var imageData1 = new OxyColor[1, n]; for (int i = 0; i < n; i++) { imageData1[0, i] = OxyColor.Interpolate(OxyColors.Blue, OxyColors.Red, i / (n - 1.0)); } var image1 = OxyImage.Create(imageData1, ImageFormat.Png); // png is required for silverlight // or create a gradient image of height 2 (requires bitmap interpolation to be supported) var imageData2 = new OxyColor[1, 2]; imageData2[0, 0] = OxyColors.Yellow; // top color imageData2[0, 1] = OxyColors.Gray; // bottom color var image2 = OxyImage.Create(imageData2, ImageFormat.Png); // png is required for silverlight // gradient filling the viewport model.Annotations.Add(new ImageAnnotation { ImageSource = image2, Interpolate = true, Layer = AnnotationLayer.BelowAxes, X = new PlotLength(0, PlotLengthUnit.RelativeToViewport), Y = new PlotLength(0, PlotLengthUnit.RelativeToViewport), Width = new PlotLength(1, PlotLengthUnit.RelativeToViewport), Height = new PlotLength(1, PlotLengthUnit.RelativeToViewport), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); // gradient filling the plot area model.Annotations.Add(new ImageAnnotation { ImageSource = image1, Interpolate = true, Layer = AnnotationLayer.BelowAxes, X = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Y = new PlotLength(0, PlotLengthUnit.RelativeToPlotArea), Width = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), Height = new PlotLength(1, PlotLengthUnit.RelativeToPlotArea), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Top }); // verify that a series is rendered above the gradients model.Series.Add(new FunctionSeries(Math.Sin, 0, 7, 0.01)); return model; } [Example("ImageAnnotation - normal axes")] public static PlotModel ImageAnnotation_NormalAxes() { var model = new PlotModel { Title = "ImageAnnotation - normal axes" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); // create an image var pixels = new OxyColor[2, 2]; pixels[0, 0] = OxyColors.Blue; pixels[1, 0] = OxyColors.Yellow; pixels[0, 1] = OxyColors.Green; pixels[1, 1] = OxyColors.Red; var image = OxyImage.Create(pixels, ImageFormat.Png); model.Annotations.Add( new ImageAnnotation { ImageSource = image, Interpolate = false, X = new PlotLength(0, PlotLengthUnit.Data), Y = new PlotLength(0, PlotLengthUnit.Data), Width = new PlotLength(80, PlotLengthUnit.Data), Height = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); return model; } [Example("ImageAnnotation - reverse horizontal axis")] public static PlotModel ImageAnnotation_ReverseHorizontalAxis() { var model = new PlotModel { Title = "ImageAnnotation - reverse horizontal axis" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, StartPosition = 1, EndPosition = 0 }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left }); // create an image var pixels = new OxyColor[2, 2]; pixels[0, 0] = OxyColors.Blue; pixels[1, 0] = OxyColors.Yellow; pixels[0, 1] = OxyColors.Green; pixels[1, 1] = OxyColors.Red; var image = OxyImage.Create(pixels, ImageFormat.Png); model.Annotations.Add( new ImageAnnotation { ImageSource = image, Interpolate = false, X = new PlotLength(100, PlotLengthUnit.Data), Y = new PlotLength(0, PlotLengthUnit.Data), Width = new PlotLength(80, PlotLengthUnit.Data), Height = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); return model; } [Example("ImageAnnotation - reverse vertical axis")] public static PlotModel ImageAnnotation_ReverseVerticalAxis() { var model = new PlotModel { Title = "ImageAnnotation - reverse vertical axis" }; model.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom }); model.Axes.Add(new LinearAxis { Position = AxisPosition.Left, StartPosition = 1, EndPosition = 0 }); // create an image var pixels = new OxyColor[2, 2]; pixels[0, 0] = OxyColors.Blue; pixels[1, 0] = OxyColors.Yellow; pixels[0, 1] = OxyColors.Green; pixels[1, 1] = OxyColors.Red; var image = OxyImage.Create(pixels, ImageFormat.Png); model.Annotations.Add( new ImageAnnotation { ImageSource = image, Interpolate = false, X = new PlotLength(0, PlotLengthUnit.Data), Y = new PlotLength(100, PlotLengthUnit.Data), Width = new PlotLength(80, PlotLengthUnit.Data), Height = new PlotLength(50, PlotLengthUnit.Data), HorizontalAlignment = HorizontalAlignment.Left, VerticalAlignment = VerticalAlignment.Bottom }); return model; } } }
// Copyright (C) 2014 dot42 // // Original filename: Java.Beans.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. #pragma warning disable 1717 namespace Java.Beans { /// <summary> /// <para>An event that indicates that a constraint or a boundary of a property has changed. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeEvent /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeEvent", AccessFlags = 33)] public partial class PropertyChangeEvent : global::Java.Util.EventObject /* scope: __dot42__ */ { /// <summary> /// <para>The constructor used to create a new <c> PropertyChangeEvent </c> .</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public PropertyChangeEvent(object source, string propertyName, object oldValue, object newValue) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para> /// </summary> /// <returns> /// <para>the name of the property that has changed, or null. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPropertyName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>Sets the propagationId object.</para><para><para>getPropagationId() </para></para> /// </summary> /// <java-name> /// setPropagationId /// </java-name> [Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void SetPropagationId(object propagationId) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para> /// </summary> /// <returns> /// <para>the propagationId object. </para> /// </returns> /// <java-name> /// getPropagationId /// </java-name> [Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetPropagationId() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getOldValue /// </java-name> [Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetOldValue() /* MethodBuilder.Create */ { return default(object); } /// <summary> /// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getNewValue /// </java-name> [Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)] public virtual object GetNewValue() /* MethodBuilder.Create */ { return default(object); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the property that has changed. If an unspecified set of properties has changed it returns null.</para><para></para> /// </summary> /// <returns> /// <para>the name of the property that has changed, or null. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> public string PropertyName { [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPropertyName(); } } /// <summary> /// <para>Returns the propagationId object. This is reserved for future use. Beans 1.0 demands that a listener receiving this property and then sending its own PropertyChangeEvent sets the received propagationId on the new PropertyChangeEvent's propagationId field.</para><para></para> /// </summary> /// <returns> /// <para>the propagationId object. </para> /// </returns> /// <java-name> /// getPropagationId /// </java-name> public object PropagationId { [Dot42.DexImport("getPropagationId", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetPropagationId(); } [Dot42.DexImport("setPropagationId", "(Ljava/lang/Object;)V", AccessFlags = 1)] set{ SetPropagationId(value); } } /// <summary> /// <para>Returns the old value that the property had. If the old value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getOldValue /// </java-name> public object OldValue { [Dot42.DexImport("getOldValue", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetOldValue(); } } /// <summary> /// <para>Returns the new value that the property now has. If the new value is unknown this method returns null.</para><para></para> /// </summary> /// <returns> /// <para>the old property value or null. </para> /// </returns> /// <java-name> /// getNewValue /// </java-name> public object NewValue { [Dot42.DexImport("getNewValue", "()Ljava/lang/Object;", AccessFlags = 1)] get{ return GetNewValue(); } } } /// <summary> /// <para>A PropertyChangeListener can subscribe with a event source. Whenever that source raises a PropertyChangeEvent this listener will get notified. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeListener /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeListener", AccessFlags = 1537)] public partial interface IPropertyChangeListener : global::Java.Util.IEventListener /* scope: __dot42__ */ { /// <summary> /// <para>The source bean calls this method when an event is raised.</para><para></para> /// </summary> /// <java-name> /// propertyChange /// </java-name> [Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1025)] void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ ; } /// <summary> /// <para>The implementation of this listener proxy just delegates the received events to its listener. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeListenerProxy /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeListenerProxy", AccessFlags = 33)] public partial class PropertyChangeListenerProxy : global::Java.Util.EventListenerProxy, global::Java.Beans.IPropertyChangeListener /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new listener proxy that associates a listener with a property name.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public PropertyChangeListenerProxy(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the name of the property associated with this listener proxy.</para><para></para> /// </summary> /// <returns> /// <para>the name of the associated property. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] public virtual string GetPropertyName() /* MethodBuilder.Create */ { return default(string); } /// <summary> /// <para>The source bean calls this method when an event is raised.</para><para></para> /// </summary> /// <java-name> /// propertyChange /// </java-name> [Dot42.DexImport("propertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)] public virtual void PropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeListenerProxy() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the name of the property associated with this listener proxy.</para><para></para> /// </summary> /// <returns> /// <para>the name of the associated property. </para> /// </returns> /// <java-name> /// getPropertyName /// </java-name> public string PropertyName { [Dot42.DexImport("getPropertyName", "()Ljava/lang/String;", AccessFlags = 1)] get{ return GetPropertyName(); } } } /// <summary> /// <para>Manages a list of listeners to be notified when a property changes. Listeners subscribe to be notified of all property changes, or of changes to a single named property.</para><para>This class is thread safe. No locking is necessary when subscribing or unsubscribing listeners, or when publishing events. Callers should be careful when publishing events because listeners may not be thread safe. </para> /// </summary> /// <java-name> /// java/beans/PropertyChangeSupport /// </java-name> [Dot42.DexImport("java/beans/PropertyChangeSupport", AccessFlags = 33)] public partial class PropertyChangeSupport : global::Java.Io.ISerializable /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new instance that uses the source bean as source for any event.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;)V", AccessFlags = 1)] public PropertyChangeSupport(object sourceBean) /* MethodBuilder.Create */ { } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, object @object, object object1) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;ILjava/lang/Object;Ljava/lang/Object;)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, object @object, object object1) /* MethodBuilder.Create */ { } /// <summary> /// <para>Unsubscribes <c> listener </c> from change notifications for the property named <c> propertyName </c> . If multiple subscriptions exist for <c> listener </c> , it will receive one fewer notifications when the property changes. If the property name or listener is null or not subscribed, this method silently does nothing. </para> /// </summary> /// <java-name> /// removePropertyChangeListener /// </java-name> [Dot42.DexImport("removePropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void RemovePropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Subscribes <c> listener </c> to change notifications for the property named <c> propertyName </c> . If the listener is already subscribed, it will receive an additional notification when the property changes. If the property name or listener is null, this method silently does nothing. </para> /// </summary> /// <java-name> /// addPropertyChangeListener /// </java-name> [Dot42.DexImport("addPropertyChangeListener", "(Ljava/lang/String;Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void AddPropertyChangeListener(string propertyName, global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the subscribers to be notified when <c> propertyName </c> changes. This includes both listeners subscribed to all property changes and listeners subscribed to the named property only. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> [Dot42.DexImport("getPropertyChangeListeners", "(Ljava/lang/String;)[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)] public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners(string propertyName) /* MethodBuilder.Create */ { return default(global::Java.Beans.IPropertyChangeListener[]); } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;ZZ)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;IZZ)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, bool boolean, bool boolean1) /* MethodBuilder.Create */ { } /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/lang/String;II)V", AccessFlags = 1)] public virtual void FirePropertyChange(string @string, int int32, int int321) /* MethodBuilder.Create */ { } /// <java-name> /// fireIndexedPropertyChange /// </java-name> [Dot42.DexImport("fireIndexedPropertyChange", "(Ljava/lang/String;III)V", AccessFlags = 1)] public virtual void FireIndexedPropertyChange(string @string, int int32, int int321, int int322) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns true if there are listeners registered to the property with the given name.</para><para></para> /// </summary> /// <returns> /// <para>true if there are listeners registered to that property, false otherwise. </para> /// </returns> /// <java-name> /// hasListeners /// </java-name> [Dot42.DexImport("hasListeners", "(Ljava/lang/String;)Z", AccessFlags = 1)] public virtual bool HasListeners(string propertyName) /* MethodBuilder.Create */ { return default(bool); } /// <summary> /// <para>Unsubscribes <c> listener </c> from change notifications for all properties. If the listener has multiple subscriptions, it will receive one fewer notification when properties change. If the property name or listener is null or not subscribed, this method silently does nothing. </para> /// </summary> /// <java-name> /// removePropertyChangeListener /// </java-name> [Dot42.DexImport("removePropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void RemovePropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Subscribes <c> listener </c> to change notifications for all properties. If the listener is already subscribed, it will receive an additional notification. If the listener is null, this method silently does nothing. </para> /// </summary> /// <java-name> /// addPropertyChangeListener /// </java-name> [Dot42.DexImport("addPropertyChangeListener", "(Ljava/beans/PropertyChangeListener;)V", AccessFlags = 1)] public virtual void AddPropertyChangeListener(global::Java.Beans.IPropertyChangeListener listener) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> [Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)] public virtual global::Java.Beans.IPropertyChangeListener[] GetPropertyChangeListeners() /* MethodBuilder.Create */ { return default(global::Java.Beans.IPropertyChangeListener[]); } /// <summary> /// <para>Publishes a property change event to all listeners of that property. If the event's old and new values are equal (but non-null), no event will be published. </para> /// </summary> /// <java-name> /// firePropertyChange /// </java-name> [Dot42.DexImport("firePropertyChange", "(Ljava/beans/PropertyChangeEvent;)V", AccessFlags = 1)] public virtual void FirePropertyChange(global::Java.Beans.PropertyChangeEvent @event) /* MethodBuilder.Create */ { } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal PropertyChangeSupport() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns all subscribers. This includes both listeners subscribed to all property changes and listeners subscribed to a single property. </para> /// </summary> /// <java-name> /// getPropertyChangeListeners /// </java-name> public global::Java.Beans.IPropertyChangeListener[] PropertyChangeListeners { [Dot42.DexImport("getPropertyChangeListeners", "()[Ljava/beans/PropertyChangeListener;", AccessFlags = 1)] get{ return GetPropertyChangeListeners(); } } } /// <summary> /// <para>A type of PropertyChangeEvent that indicates that an indexed property has changed. </para> /// </summary> /// <java-name> /// java/beans/IndexedPropertyChangeEvent /// </java-name> [Dot42.DexImport("java/beans/IndexedPropertyChangeEvent", AccessFlags = 33)] public partial class IndexedPropertyChangeEvent : global::Java.Beans.PropertyChangeEvent /* scope: __dot42__ */ { /// <summary> /// <para>Creates a new property changed event with an indication of the property index.</para><para></para> /// </summary> [Dot42.DexImport("<init>", "(Ljava/lang/Object;Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;I)V", AccessFlags = 1)] public IndexedPropertyChangeEvent(object source, string propertyName, object oldValue, object newValue, int index) /* MethodBuilder.Create */ { } /// <summary> /// <para>Returns the index of the property that was changed in this event. </para> /// </summary> /// <java-name> /// getIndex /// </java-name> [Dot42.DexImport("getIndex", "()I", AccessFlags = 1)] public virtual int GetIndex() /* MethodBuilder.Create */ { return default(int); } [global::System.ComponentModel.EditorBrowsable(global::System.ComponentModel.EditorBrowsableState.Never)] internal IndexedPropertyChangeEvent() /* TypeBuilder.AddDefaultConstructor */ { } /// <summary> /// <para>Returns the index of the property that was changed in this event. </para> /// </summary> /// <java-name> /// getIndex /// </java-name> public int Index { [Dot42.DexImport("getIndex", "()I", AccessFlags = 1)] get{ return GetIndex(); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace MagiWol.MagiWolDocument { internal class DocumentEx : Document { public DocumentEx() : base() { } public static new DocumentEx Open(string fileName) { var doc = new DocumentEx(); Load(fileName, doc); doc.HasChanged = false; return doc; } public new void Save() { base.Save(); this.HasChanged = false; } public new void Save(string fileName) { base.Save(fileName); this.HasChanged = false; } public void AddAddress(AddressItem item, bool allowDuplicates) { base.AddAddress(item.Address, allowDuplicates); } public void RemoveAddress(AddressItem item) { base.RemoveAddress(item.Address); } public bool HasAddress(AddressItem item) { return base.HasAddress(item.Address); } public void FillListView(ListView list, IEnumerable<AddressItem> selectedItems) { var selectionList = new List<AddressItem>(); if (selectedItems != null) { foreach (var iItem in selectedItems) { selectionList.Add(iItem); } } MagiWolDocument.AddressItem potentialFocus = null; list.BeginUpdate(); Medo.Windows.Forms.State.Save(list); list.Columns.Clear(); list.Columns.Add(new ColumnHeader() { Tag = "Name", Text = "Name", Width = 175 }); if (Settings.ShowColumnMac) { list.Columns.Add(new ColumnHeader() { Tag = "Mac", Text = "Mac", Width = 175 }); } if (Settings.ShowColumnSecureOn) { list.Columns.Add(new ColumnHeader() { Tag = "SecureOn", Text = "SecureOn", Width = 175 }); } if (Settings.ShowColumnBroadcastHost) { list.Columns.Add(new ColumnHeader() { Tag = "BroadcastHost", Text = "Host", Width = 150 }); } if (Settings.ShowColumnBroadcastPort) { list.Columns.Add(new ColumnHeader() { Tag = "BroadcastPort", Text = "Port", Width = 60 }); } if (Settings.ShowColumnNotes) { list.Columns.Add(new ColumnHeader() { Text = "Notes", Tag = "Notes", Width = 270 }); } Medo.Windows.Forms.State.Load(list); list.Items.Clear(); for (int i = 0; i < this._addresses.Count; ++i) { var address = _addresses[i]; var lvi = new AddressItem(_addresses[i]); lvi.Selected = selectionList.Contains(lvi); lvi.RefreshColumns(); list.Items.Add(lvi); if (selectionList.Contains(lvi)) { potentialFocus = lvi; } } list.EndUpdate(); if (potentialFocus != null) { list.FocusedItem = potentialFocus; } } public void Cut(IEnumerable<AddressItem> addressItems) { bool isChanged = false; Copy(addressItems); var addresses = new List<Address>(); foreach (var item in addressItems) { addresses.Add(item.Address); } foreach (var iAddress in addresses) { if (this._addresses.Contains(iAddress)) { this._addresses.Remove(iAddress); isChanged = true; } } if (isChanged) { this.HasChanged = true; } } public void Copy(IEnumerable<AddressItem> addressItems) { var addresses = new List<Address>(); foreach (var item in addressItems) { addresses.Add(item.Address); } var sb = new StringBuilder(); foreach (var iAddress in addresses) { sb.AppendLine(iAddress.Mac + " " + iAddress.Title); } try { Clipboard.Clear(); DataObject clipData = new DataObject(); clipData.SetData(DataFormats.UnicodeText, true, sb.ToString()); clipData.SetData("MagiWOL", false, GetXmlFromAddresses(addresses)); Clipboard.SetDataObject(clipData, true); } catch (ExternalException) { } } public IEnumerable<AddressItem> Paste() { var pastedAddressItems = new List<AddressItem>(); string xmlData = null; string dataText = null; try { IDataObject clipData = Clipboard.GetDataObject(); xmlData = clipData.GetData("MagiWOL") as string; if (xmlData == null) { dataText = clipData.GetData(DataFormats.UnicodeText, true) as string; if (dataText == null) { dataText = clipData.GetData(DataFormats.Text) as string; } } } catch (ExternalException) { return pastedAddressItems; } bool isChanged = false; if (xmlData != null) { foreach (var iAddress in GetAddressesFromXml(this, xmlData)) { if (!this.HasAddress(iAddress)) { this.AddAddress(iAddress, false); pastedAddressItems.Add(new AddressItem(iAddress)); isChanged = true; } else { foreach (var feAddress in this._addresses) { if (feAddress.Equals(iAddress)) { pastedAddressItems.Add(new AddressItem(feAddress)); break; } } } } } else if (dataText != null) { foreach (var iLine in dataText.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)) { var iAddress = GetAddressFromLine(iLine); if (iAddress != null) { if (!this.HasAddress(iAddress)) { this.AddAddress(iAddress, false); pastedAddressItems.Add(new AddressItem(iAddress)); isChanged = true; } else { foreach (var feAddress in this._addresses) { if (feAddress.Equals(iAddress)) { pastedAddressItems.Add(new AddressItem(feAddress)); break; } } } } } } if (isChanged) { this.HasChanged = true; } return pastedAddressItems.AsReadOnly(); } public bool CanPaste() { try { return Clipboard.ContainsData("MagiWOL") || Clipboard.ContainsText(); } catch (ExternalException) { return false; } } public string FileTitle { get { string fileNamePart; if (this.FileName == null) { fileNamePart = "Untitled"; } else { var fi = new FileInfo(this.FileName); fileNamePart = fi.Name; } if (this.HasChanged) { return fileNamePart + "*"; } else { return fileNamePart; } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.ComponentModel; using FlatRedBall.IO.Gif; using FlatRedBall.Graphics.Texture; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework; namespace FlatRedBall.IO { /// <summary> /// Contains an indexed array of Colors to be used by images with ColorType 3 and possibly ColorTypes /// 2 and 6. /// </summary> internal struct PaletteInfo { public RGB[] Entries; } /// <summary> /// Simple struct used to hold sample values. /// </summary> internal struct RGB { public byte R; public byte G; public byte B; public byte A; } /// <summary> /// Class responsible for loading GIF files. /// </summary> /// <remarks> /// For information, see: /// http://www.fileformat.info/format/gif/ /// </remarks> public static class GifLoader { #region Structs private struct GifInfo { public string Header; public int Width; public int Height; public bool HasGlobalColorTable; public int NumberOfColorEntries; public PaletteInfo PaletteInfo; public bool HasTransparency; public int TransparentIndex; public int LzwMin; // the starting number of bits to read public List<Int16> DelayTimes; public bool IsInterlaced; public Int16 CurrentBlockLeft; public Int16 CurrentBlockTop; public Int16 CurrentBlockWidth; public Int16 CurrentBlockHeight; } #endregion #region Fields static int ClrConstant; static int EndConstant; static List<List<int>> mDictionary; static List<byte> mUncompressedColorIndexBuffer; static GifInfo mGifInfo; #endregion #region Properties public static int CurrentEntrySize { get { int numberOfBits = 0; while ((1 << numberOfBits) <= mDictionary.Count) { numberOfBits++; } return numberOfBits; } } #endregion #region Methods #region Public Methods public static ImageDataList GetImageDataList(string gifFileName) { ImageDataList imageDatas = new ImageDataList(); #if XBOX360 || SILVERLIGHT if (gifFileName.StartsWith(@".\") || gifFileName.StartsWith(@"./")) { gifFileName = gifFileName.Substring(2); } #endif #if SILVERLIGHT || WINDOWS_8 using (Stream stream = FileManager.GetStreamForFile(gifFileName)) #else using (FileStream stream = System.IO.File.OpenRead(gifFileName)) #endif { mGifInfo = new GifInfo(); mGifInfo.DelayTimes = new List<short>(); BinaryReader reader = new BinaryReader(stream); #region header // Example: GIF89a byte[] buffer = reader.ReadBytes(6); // set the header here char[] charArray = new char[buffer.Length]; for (int i = 0; i < buffer.Length; i++) { charArray[i] = (char)buffer[i]; } mGifInfo.Header = new string(charArray); #endregion #region Width/Height mGifInfo.Width = reader.ReadInt16(); mGifInfo.Height = reader.ReadInt16(); #endregion #region Packed information // The packed byte has the following info: // Bits 0-2 Size of the Global Color Table // Bit 3 Color Table Sort Flag // Bits 4-6 Color Resolution // Bit 7 Global Color Table Flag Byte packedByte = reader.ReadByte(); int sizeOfGlobalColorTable = (7 & packedByte); mGifInfo.NumberOfColorEntries = 1 * (1 << (sizeOfGlobalColorTable + 1)); mGifInfo.HasGlobalColorTable = (128 & packedByte) != 0; #endregion #region background color reader.ReadByte(); #endregion #region default aspect ratio reader.ReadByte(); #endregion TryReadGlobalColorTable(reader); byte separator = reader.ReadByte(); while (separator != 0x3b) // Extension { switch(separator) { #region Extensions case 0x21: Byte label = reader.ReadByte(); switch (label) { case 0xf9: ReadGraphicsControlExtension(reader); break; case 0xff: ReadApplicationExtensionBlock(reader); break; case 0xfe: ReadCommonExtensionBlock(reader); break; } break; #endregion #region Image Data case 0x2c: ReadImageDescriptor(reader); Color[] color = new Color[mGifInfo.Width * mGifInfo.Height]; int transparentIndex = mGifInfo.TransparentIndex; #region Interlaced if (mGifInfo.IsInterlaced) { int i = 0; for (int pass = 0; pass < 4; ++pass) { int row = 0; int increment = 0; switch (pass) { case 0: row = 0; increment = 8; break; case 1: row = 4; increment = 8; break; case 2: row = 2; increment = 4; break; case 3: row = 1; increment = 2; break; } for (; row < mGifInfo.Height; row += increment) { for (int col = 0; col < mGifInfo.Width; ++col) { int position = (row * mGifInfo.Width) + col; byte index = mUncompressedColorIndexBuffer[i++]; byte alpha = 255; if (mGifInfo.HasTransparency && index == transparentIndex) alpha = 0; #if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE color[position] = new Color( (byte)mGifInfo.PaletteInfo.Entries[index].R, (byte)mGifInfo.PaletteInfo.Entries[index].G, (byte)mGifInfo.PaletteInfo.Entries[index].B, (byte)alpha); #elif FRB_MDX color[position] = Color.FromArgb( alpha, (byte)mGifInfo.PaletteInfo.Entries[index].R, (byte)mGifInfo.PaletteInfo.Entries[index].G, (byte)mGifInfo.PaletteInfo.Entries[index].B); #endif } } } } #endregion else { #region NonInterlaced for (int i = 0; i < mGifInfo.PaletteInfo.Entries.Length; i++) { mGifInfo.PaletteInfo.Entries[transparentIndex].A = 255; } if (mGifInfo.HasTransparency) { mGifInfo.PaletteInfo.Entries[transparentIndex].A = 0; } int x = 0; int y = 0; int colorIndex; for (int i = 0; i < mUncompressedColorIndexBuffer.Count; i++) { byte index = mUncompressedColorIndexBuffer[i]; // Let's see if we can avoid an if statement x = mGifInfo.CurrentBlockLeft + i % mGifInfo.CurrentBlockWidth; y = mGifInfo.CurrentBlockTop + i / mGifInfo.CurrentBlockWidth; colorIndex = x + y * mGifInfo.Width; #if FRB_XNA || SILVERLIGHT || WINDOWS_PHONE color[colorIndex] = new Color( (byte)mGifInfo.PaletteInfo.Entries[index].R, (byte)mGifInfo.PaletteInfo.Entries[index].G, (byte)mGifInfo.PaletteInfo.Entries[index].B, (byte)mGifInfo.PaletteInfo.Entries[index].A); #elif FRB_MDX color[colorIndex] = Color.FromArgb( (byte)mGifInfo.PaletteInfo.Entries[index].A, (byte)mGifInfo.PaletteInfo.Entries[index].R, (byte)mGifInfo.PaletteInfo.Entries[index].G, (byte)mGifInfo.PaletteInfo.Entries[index].B); #endif } #endregion } ImageData imageData = new ImageData( mGifInfo.Width, mGifInfo.Height, color); imageDatas.Add(imageData); mUncompressedColorIndexBuffer.Clear(); break; #endregion #region End of file case 0x3b: // end of file break; #endregion } separator = reader.ReadByte(); } } // Fill the imageDatas with the frame times foreach (short s in mGifInfo.DelayTimes) { imageDatas.FrameTimes.Add(s / 100.0); } return imageDatas; } #endregion #region Private Methods private static void FillDictionary() { mDictionary = new List<List<int>>(); for (int i = 0; i < mGifInfo.NumberOfColorEntries; i++) { mDictionary.Add(new List<int> { i }); } ClrConstant = (1 << mGifInfo.LzwMin); EndConstant = ClrConstant + 1; while (mDictionary.Count < ClrConstant) { mDictionary.Add(new List<int>()); } mDictionary.Add(new List<int> { ClrConstant }); mDictionary.Add(new List<int> { EndConstant }); } private static void FillUncompressedColorIndexBuffer(byte[] data, ref int currentEntrySize, ref bool firstRead) { BitReader reader = new BitReader(data); List<int> nextDictionaryEntry = new List<int>(); while ((reader.BitPosition + currentEntrySize) <= reader.BitLength) { int result = reader.Read(currentEntrySize); bool addToDictionary = !firstRead &&// don't add on the first read (mDictionary.Count < (1 << 12)); // dictionary capped at 12 bits List<int> pattern; if (result < mDictionary.Count) { pattern = mDictionary[result]; } else if (result == mDictionary.Count) { // special case for LZW pattern = new List<int>(nextDictionaryEntry); // pattern.Add(nextDictionaryEntry[nextDictionaryEntry.Count - 1]); pattern.Add(nextDictionaryEntry[0]); } else { int index = mUncompressedColorIndexBuffer.Count - 1; string error = "Error when reading pixel number " + (mUncompressedColorIndexBuffer.Count - 1); int row = (mUncompressedColorIndexBuffer.Count) / mGifInfo.Width + 1; int column = (mUncompressedColorIndexBuffer.Count) % mGifInfo.Width; error += "\n On the image that's (" + column + ", " + row + ")."; throw new Exception(error); } firstRead = false; // Check for constant values if (result == ClrConstant) { // Clear dictionary addToDictionary = false; firstRead = true; nextDictionaryEntry = new List<int>(); currentEntrySize = mGifInfo.LzwMin + 1; FillDictionary(); } else if (result == EndConstant) { // End of image break; } else { // It's just image data for (int i = 0; i < pattern.Count; i++) { mUncompressedColorIndexBuffer.Add((byte)pattern[i]); } #if DEBUG if (mUncompressedColorIndexBuffer.Count > mGifInfo.Width * mGifInfo.Height) { throw new InvalidOperationException("The uncompressed buffer is too big!"); } #endif } if (addToDictionary) { // add to dictionary List<int> newPattern = new List<int>(nextDictionaryEntry); // newPattern.Add(pattern[pattern.Count - 1]); newPattern.Add(pattern[0]); mDictionary.Add(newPattern); currentEntrySize = CurrentEntrySize; if (currentEntrySize == 13) { currentEntrySize = 12; } } if (result != ClrConstant) { nextDictionaryEntry = pattern; } } } private static void ReadApplicationExtensionBlock(BinaryReader reader) { byte blockSize = reader.ReadByte(); char[] identifier = reader.ReadChars(8); byte[] authentCode = reader.ReadBytes(3); byte howManyBytes = reader.ReadByte(); while (howManyBytes != 0) { reader.ReadBytes(howManyBytes); howManyBytes = reader.ReadByte(); } } private static void ReadCommonExtensionBlock(BinaryReader reader) { byte howManyBytes = reader.ReadByte(); while (howManyBytes != 0) { reader.ReadBytes(howManyBytes); howManyBytes = reader.ReadByte(); } } private static void ReadGraphicsControlExtension(BinaryReader reader) { byte blockSize = reader.ReadByte(); if (blockSize != 4) { throw new Exception("The block size for graphics control extension is not 4. Something's wrong."); } //Bit 0 Transparent Color Flag //Bit 1 User Input Flag //Bits 2-4 Disposal Method //Bits 5-7 Reserved byte packed = reader.ReadByte(); mGifInfo.HasTransparency = (packed & 1) == 1; Int16 delayTime = reader.ReadInt16(); mGifInfo.DelayTimes.Add(delayTime); byte transparentColorIndex = reader.ReadByte(); byte terminator = reader.ReadByte(); mGifInfo.TransparentIndex = transparentColorIndex; } private static void ReadImageDescriptor(BinaryReader reader) { mGifInfo.CurrentBlockLeft = reader.ReadInt16(); mGifInfo.CurrentBlockTop = reader.ReadInt16(); mGifInfo.CurrentBlockWidth = reader.ReadInt16(); mGifInfo.CurrentBlockHeight = reader.ReadInt16(); Byte packed = reader.ReadByte(); if (packed != 0) { mGifInfo.IsInterlaced = (packed & 1) == 1; bool sorted = (packed & 2) == 2; int sizeofLocalColorTableEntry = packed >> 5; if (sizeofLocalColorTableEntry != 0) { throw new Exception("The GIF has a local color entry. That's currently not supported"); } mGifInfo.IsInterlaced = true;/* throw new InvalidDataException( "The image descriptor indicates the gif is interlaced, sorted, or uses a local color table. Not currently supported.");*/ } mGifInfo.LzwMin = reader.ReadByte(); int currentEntrySize = mGifInfo.LzwMin + 1; FillDictionary(); // TODO: Fill with number of pixels to reduce GC mUncompressedColorIndexBuffer = new List<byte>(); bool firstRead = true; MemoryStream memoryStream = new MemoryStream(); byte dataBlockSize = reader.ReadByte(); while (dataBlockSize != 0) { byte[] data = reader.ReadBytes(dataBlockSize); memoryStream.Write(data, 0, data.Length); dataBlockSize = reader.ReadByte(); } FillUncompressedColorIndexBuffer(memoryStream.ToArray(), ref currentEntrySize, ref firstRead); } private static void TryReadGlobalColorTable(BinaryReader reader) { if (mGifInfo.HasGlobalColorTable) { mGifInfo.PaletteInfo = new PaletteInfo(); mGifInfo.PaletteInfo.Entries = new RGB[mGifInfo.NumberOfColorEntries]; for (int i = 0; i < mGifInfo.NumberOfColorEntries; i++) { mGifInfo.PaletteInfo.Entries[i].R = reader.ReadByte(); mGifInfo.PaletteInfo.Entries[i].G = reader.ReadByte(); mGifInfo.PaletteInfo.Entries[i].B = reader.ReadByte(); mGifInfo.PaletteInfo.Entries[i].A = 255;// Default to opaque for now } } } #endregion #endregion } #region BitReader class BitReader { int mByteIndex = 0; int mBitIndex = 0; byte[] mBuffer; public int BitPosition { get { return mBitIndex + mByteIndex * 8; } } public int BitLength { get { return mBuffer.Length * 8; } } public BitReader(byte[] buffer) { mBuffer = buffer; } public int Read(int bits) { const int maximumSize = 32; if (bits > maximumSize) { throw new ArgumentException("Too many bits for BitReader"); } if ((this.BitPosition + bits) > this.BitLength) { throw new InvalidOperationException("Reading past the end of the buffer."); } int result = 0; int bitsRead = 0; while (bits > 0) { int bitsToRead = System.Math.Min(bits, 8 - mBitIndex); // only read up to 8 bits at a time result += ((mBuffer[mByteIndex] >> mBitIndex) & ((1 << bitsToRead) - 1)) << bitsRead; bits -= bitsToRead; bitsRead += bitsToRead; mBitIndex += bitsToRead; if (mBitIndex >= 8) { mBitIndex = 0; ++mByteIndex; } } return result; } } #endregion }
/* * draws a basic mini map overview slide set ofr an ns 2 map * Lee Brunjes 2013 * uses: * http://www.codeproject.com/Articles/31702/NET-Targa-Image-Reader * TODO: * draw techpoints/location names onto minimap. * fonts */ using System; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Drawing.Drawing2D; using System.Collections.Generic; namespace NS2MapLoadScreenGenerator { class MainClass { #region varaibles const string configFile="loadscreens.ini"; public static String instructions = @" Generates loading screens from and ns2 map. use: loadscreens.exe ns2_map_name [font] [refreshMinimap] [fontSize] "; static string fontDir = "core\\fonts\\"; static string mapsDir = "ns2\\maps\\"; static string overviewDir= "ns2\\maps/overviews\\"; static string screensDir = "ns2\\screens\\"; static string screenSrcDir = "\\src\\"; static float bigFontSize = 72f; static float minimapFontSize = 24f; static Font bigFont = new Font (FontFamily.GenericSansSerif, bigFontSize); static Font minimapFont = new Font(FontFamily.GenericSansSerif,minimapFontSize); static int minimapxoffset = 1120; static int minimapyoffset = 0; static int minimapsize =640; static int bigTextX = 640; static int bigTextY = 64; static String tpIconPath=""; static String rpIconPath=""; static String defaultFont = ""; static bool refreshMinimap = false; static Bitmap tp_icon; static Bitmap rt_icon; #endregion /// <summary> /// The entry point of the program, where the program control starts and ends. /// </summary> /// <param name="args">The command-line arguments.</param> public static void Main (string[] args) { //Read config file ReadConfigFile (); String map = "ns2_test"; String path = Environment.CurrentDirectory+"\\"; String font = defaultFont; Bitmap overview; #region parse command line args & load things if (args.Length > 0) { map= args[0].Replace(".level",""); } if (args.Length > 1) { font= args[1].ToLower(); } if(args.Length > 2){ refreshMinimap = args[2].ToLower() == "true" || args[2].ToLower()=="yes"; } if( args.Length >3){ float.TryParse(args[3], out minimapFontSize); } Console.WriteLine (String.Format(@"NS2 Map Load Screen generator --------------------------------- {0} Level:{1} font :{2} update minimap:{3} fontSize: {4} ---------------------------------", instructions, map, font, refreshMinimap, minimapFontSize)); // if we aint got a mp no point in going forward. if(map == ""){ return; } if(File.Exists("icon_techpoint.png")){ tp_icon = new Bitmap ("icon_techpoint.png"); } else{ Console.WriteLine ("WARNING: Cannot load techpoint Icon"); tp_icon = new Bitmap(20,20); Graphics g = Graphics.FromImage(tp_icon); g.FillRectangle(Brushes.Orange, 0,0,19,19); } tp_icon.MakeTransparent (); #endregion #region check fonts bool fontFound = false; string installedFonts = ""; InstalledFontCollection ifc = new InstalledFontCollection (); foreach (FontFamily fontfamily in ifc.Families) { if (fontfamily.Name.ToLower() == font) { bigFont = new Font (fontfamily, bigFontSize); minimapFont = new Font (fontfamily, minimapFontSize); fontFound = true; } installedFonts += fontfamily.Name+"\n"; } if (!fontFound) { PrivateFontCollection pfc = new PrivateFontCollection (); if (File.Exists (path+fontDir+font+".ttf")) { pfc.AddFontFile (path+fontDir+font+".ttf"); bigFont = new Font (pfc.Families [0], bigFontSize); minimapFont = new Font (pfc.Families [0], minimapFontSize); } else { Console.WriteLine ("Cannot find font, using default\nInstalled font list:"); Console.WriteLine(installedFonts); Console.WriteLine(); } } #endregion #region Find and generate anotated overview //find the minimap file first if(File.Exists(path +overviewDir+ map+".tga")){ overview = Paloma.TargaImage.LoadTargaImage(path +overviewDir+ map+".tga"); overview.MakeTransparent (overview.GetPixel(1,1)); AnnotateOverview (ref overview, path+mapsDir+map+".level"); //Check to make sure the map has not been saved since the minimap was created if(File.GetLastWriteTimeUtc(path +overviewDir+ map+".tga") < File.GetLastWriteTimeUtc(path+ mapsDir+map+".level")){ Console.WriteLine ("WARNING: Level file updated more recently than overview"); if (refreshMinimap && File.Exists("Overview.exe")) { Console.WriteLine("running: Overview.exe "+ path +mapsDir+map+".level "+path+overviewDir); System.Diagnostics.Process oProc =System.Diagnostics.Process.Start("Overview.exe", string.Format("\"{0}\" \"{1}\"", path+mapsDir+map+".level" ,"ns2")); oProc.WaitForExit(); } else{ if(refreshMinimap){ Console.WriteLine("Not in same directory as overview generator. Ignoring"); } } } } else{ Console.WriteLine("Cannot locate overview at:\n "+path +overviewDir+ map+".tga\n Are you sure it exists?"); return; } #endregion //find the output dir if(!Directory.Exists(path+screensDir+map)){ Directory.CreateDirectory(path+screensDir+map); } //list of files to read String[] toUse; if(!Directory.Exists(path+screensDir+map+screenSrcDir)){ Console.WriteLine("Using generic screenshots"); toUse = Directory.GetFiles(path+screensDir,"*.jpg"); Randomizer r = new Randomizer (); toUse = r.shuffle (toUse); } else{ toUse = Directory.GetFiles(path+screensDir+map+screenSrcDir,"*.jpg"); } Console.WriteLine ("found "+toUse.Length); //draw the data you want if (toUse.Length > 0) { for (int i =0; i < 4; i++) { CreateAndSaveLoadScreen (i+1, path + screensDir + map, ref overview, toUse [i%toUse.Length], map); } } else { Console.WriteLine ("no .jpgs found"); return; } Console.WriteLine ("Complete."); } /// <summary> /// Creates a single loading slide /// </summary> /// <param name="id">Identifier.</param> /// <param name="path">Path.</param> /// <param name="overview">Overview.</param> /// <param name="infile">Infile.</param> /// <param name="mapname">Mapname.</param> private static void CreateAndSaveLoadScreen( int id, string path, ref Bitmap overview, string infile,String mapname){ //Read the file in Bitmap tmp = new Bitmap (infile); //ensure that the file is big enough; if(tmp.Width < 1920){ tmp = resizeImage (tmp,1920); } else { if(tmp.Width ==0){ Console.WriteLine (infile+" Width was 0..."); return; } } //show the overview Graphics g = Graphics.FromImage (tmp); g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; g.DrawImage (overview, new Rectangle (minimapxoffset, minimapyoffset, minimapsize, minimapsize)); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; //draw the name of the map drawString (mapname.Replace("ns2_","").ToUpper(), g, bigFont, 320, 64,2.1f,6); //draw the hint box at teh bottom Color semitransparent = Color.FromArgb (128, 0, 0, 0); g.FillRectangle (new SolidBrush(semitransparent), new Rectangle (0, tmp.Height - 100, tmp.Width, 99)); //draw teh vingette effect LinearGradientBrush gradientbrush1 = new LinearGradientBrush ( new Rectangle (0, 0, 101, tmp.Height), Color.FromArgb (255, 0, 0, 0), Color.FromArgb (0, 0, 0, 0), LinearGradientMode.Horizontal); LinearGradientBrush gradientbrush2 = new LinearGradientBrush ( new Rectangle (tmp.Width-150, 0, 150, tmp.Height), Color.FromArgb (0, 0, 0, 0), Color.FromArgb (255, 0, 0, 0), LinearGradientMode.Horizontal); LinearGradientBrush gradientbrush3 = new LinearGradientBrush ( new Rectangle (0, 0, tmp.Width,51), Color.FromArgb (255, 0, 0, 0), Color.FromArgb (0, 0, 0, 0), LinearGradientMode.Vertical); g.FillRectangle (gradientbrush1, 0, 0, 100, tmp.Height); g.FillRectangle (gradientbrush2, tmp.Width-150, 0, 150, tmp.Height); g.FillRectangle (gradientbrush3, 0, 0, tmp.Width, 50); g.Flush (); g.Flush(); //save the output. tmp.Save (String.Format("{0}/{1}.jpg",path,id)); Console.Write (id +"..."); } /// <summary> /// Resizes the image to match targeted sizes /// </summary> /// <returns>The image.</returns> /// <param name="img">Image.</param> /// <param name="width">Width.</param> public static Bitmap resizeImage(Bitmap img, int width){ if (img.Width == 0) { return img; } double scale = 1/((double)img.Width / width); Bitmap outImg = new Bitmap(width, (int)(img.Height*scale),System.Drawing.Imaging.PixelFormat.Format32bppArgb); Graphics g = Graphics.FromImage(outImg); g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; //draw the tip window g.FillRectangle(new SolidBrush(Color.Black), new Rectangle(0, 0, outImg.Width, outImg.Height)); g.DrawImage(img, new Rectangle(0,0, outImg.Width, outImg.Height)); return outImg; } /// <summary> /// Adds things to overview /// </summary> /// <param name="overview">Overview.</param> /// <param name="file">File.</param> static void AnnotateOverview (ref Bitmap overview, string file) { List<RectangleF> textBlocks= new List<RectangleF>(); //TODO /* * to get this working we need to open the map file, get the minimap exetents, map that to the minimap.tga * * iterate teh tech points, * iterate the resource towers, * then we need to iterate the locations and draw the names */ NS2.Tools.Level lvl = new NS2.Tools.Level (file); Console.WriteLine (lvl.minimap_extents); Console.WriteLine (lvl.Textures.Length+" TEXTures"); Console.WriteLine (lvl.TechPoints.Count+" TP"); Console.WriteLine (lvl.Resources.Count+" RT"); Console.WriteLine (lvl.Locations.Count+" loc"); Graphics g = Graphics.FromImage (overview); g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias; g.TranslateTransform (overview.Width/2f , overview.Height/2f); g.RotateTransform (-90f); Console.WriteLine ("Scale:"+(overview.Width/lvl.minimap_extents.Scale.X)+"\n"+overview.Height/lvl.minimap_extents.Scale.Z); //ahhhh if(Math.Abs(lvl.minimap_extents.Scale.X - lvl.minimap_extents.Scale.Z) > 10){ if(lvl.minimap_extents.Scale.Z >lvl.minimap_extents.Scale.X){ g.ScaleTransform(lvl.minimap_extents.Scale.X/lvl.minimap_extents.Scale.Z,1); } else{ g.ScaleTransform(1,lvl.minimap_extents.Scale.Z/lvl.minimap_extents.Scale.X); } } NS2.Tools.Vector3 vec; g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceOver; //Draw techpoints foreach (NS2.Tools.Entity e in lvl.TechPoints) { vec = lvl.minimapLocation (e.Origin, overview.Width); // //g.FillRectangle(Brushes.Gold, e.Origin.X, e.Origin.Z, 8f,8f); // g.FillRectangle(Brushes.Blue, vec.X-16, vec.Z-16, 32f,32f); g.DrawImage (tp_icon, new RectangleF(vec.X-16f, vec.Z-16f, 32f, 32f)); } //Draw Rts //REMOVED FOR NOW. /* foreach (NS2.Tools.Entity e in lvl.Resources) { vec = lvl.minimapLocation (e.Origin, overview.Width); // Console.WriteLine (e.Origin + " =>" + vec); g.FillEllipse(Brushes.Red, vec.X-16, vec.Z-16, 32f,32f); // g.FillRectangle }*/ g.RotateTransform (90); //Draw location names foreach (NS2.Tools.Entity e in lvl.Locations) { vec = lvl.minimapLocation (e.Origin, overview.Width); var size = g.MeasureString (e.Text,minimapFont); int startX=(int)(vec.Z-size.Width/2); int startY=(int)( -vec.X - size.Height / 2); int lastAdjust = 0; RectangleF box = new RectangleF (startX,startY, size.Width, size.Height); for(int i = 0; i <textBlocks.Count ;i++) { if (textBlocks[i].IntersectsWith (box)) { if (lastAdjust == 0) { box.Y -= 1; } else if (lastAdjust == 1) { box.Y += 1; } else if (lastAdjust == 2) { box.X -= 1; } else if (lastAdjust>=3){ box.X+=1; } i = 0; if(lastAdjust == 0 && startY > box.Y + box.Height) { lastAdjust =1; box.Y = startY; } if(lastAdjust == 1 && startY < box.Y - box.Height) { lastAdjust =2; box.Y = startY; } if(lastAdjust == 2 && startX > box.X - box.Height) { lastAdjust =3; box.X = startY; } if(lastAdjust == 3 && startX < box.X - box.Height) { lastAdjust =4; i += textBlocks.Count; box.X=startX; box.Y= startY; Console.WriteLine("I hope "+e.Text+" is not overlapping"); } } } //g.DrawRectangle (Pens.Red, box.X, box.Y, box.Width, box.Height); drawString (e.Text, g, minimapFont, box.X, box.Y,1,0); textBlocks.Add (box); } g.Flush (); } /// <summary> /// Draws the string using ana outline and supposts basic eeffects /// </summary> /// <param name="text">Text.</param> /// <param name="g">The green component.</param> /// <param name="f">F.</param> /// <param name="centerx">Centerx.</param> /// <param name="centery">Centery.</param> /// <param name="margin">Margin.</param> /// <param name="glowWidth">Glow width.</param> public static void drawString(String text, Graphics g, Font f, float centerx, float centery, float margin, float glowWidth){ float scalingfortext = 395f / 300f; g.SmoothingMode = SmoothingMode.AntiAlias; GraphicsPath gp = new GraphicsPath (); gp.AddString(text, f.FontFamily, (int)FontStyle.Regular, f.Size*scalingfortext, new PointF(centerx, centery), new StringFormat()); if (glowWidth > 0) { for (int i = 0; i < glowWidth*2; i++) { g.DrawPath (new Pen (Color.FromArgb(16,255,255,255), i),gp); } } if (margin >= 1) { g.DrawPath (new Pen(Color.Black, margin*2), gp); g.FillPath (Brushes.Black, gp); } g.FillPath (Brushes.White, gp); /*g.DrawString (text, new Font(f.FontFamily, f.Size+margin), Brushes.Black, new PointF (centerx-margin, centery)); g.DrawString (text, f, Brushes.White, new PointF (centerx-1, centery));*/ } static void ReadConfigFile () { string key = ""; string data = ""; String[] configData=null; int idx; try{ configData = File.ReadAllLines (configFile); } catch(Exception ex){ Console.WriteLine ("WARNING: cannot load config, "+ex.Message+", using defaults"); return; } foreach (String line in configData) { idx = line.IndexOf ("#"); if ( idx>= 0) { key = line.Substring(0, idx); } idx = key.IndexOf ("="); if (key.Length > 3 & idx >= 0) { data = key.Substring (idx+1).Trim(); key = key.Substring (0, idx).Trim().ToLower(); ProcessConfig(key,data); } } } static void ProcessConfig(string key, string data){ //TODO data validation? switch(key){ case "fontdir": fontDir = data; break; case "mapsdir": mapsDir = data; break; case "overviewdir": overviewDir = data; break; case "screensdir": screensDir = data; break; case "screensrcdir": screenSrcDir = data; break; case "bigfontsize": float.TryParse (data, out bigFontSize); break; case "minimapfontsize": float.TryParse (data, out minimapFontSize); break; case "icon_tp": tpIconPath = data; break; case "icon_rp": rpIconPath = data; break; case "refreshminimap": refreshMinimap = data == "true"; break; case "minimapxoffset": int.TryParse (data, out minimapxoffset); break; case "minimapyoffset": int.TryParse (data, out minimapyoffset); break; case "minimapsize": int.TryParse (data, out minimapsize); break; case "bigtexty": int.TryParse (data, out bigTextY); break; case "bigtextx": int.TryParse (data, out bigTextX); break; default: Console.WriteLine ("Invalid Config key: "+key); break; } } } }
using System; namespace azmon.formatters.cef { public class CefEvent { public CefEvent() { this.CustomProperties = new CefCustomProperties(); } public DateTime Timestamp { get; set; } /// <summary> /// Identifier for the host (source of the event) /// </summary> /// <value>The host.</value> public string Host { get; set; } /// <summary> /// Version is an integer and identifies the version of the CEF format. Event /// consumers use this information to determine what the following fields /// represent. The current CEF version is 0 (CEF:0). /// </summary> /// <value>CEF:0</value> public string CefVersion { get; set; } /// <summary> /// Device Vendor, Device Product and Device Version are strings that /// uniquely identify the type of sending device. No two products may /// use the same device-vendor and device-product pair. There is /// no central authority managing these pairs. Event producers must /// ensure that they assign unique name pairs. /// </summary> /// <value>The device vendor.</value> public string DeviceVendor { get; set; } /// <summary> /// Device Vendor, Device Product and Device Version are strings that /// uniquely identify the type of sending device. No two products may /// use the same device-vendor and device-product pair. There is /// no central authority managing these pairs. Event producers must /// ensure that they assign unique name pairs. /// </summary> /// <value>The device product.</value> public string DeviceProduct { get; set; } /// <summary> /// Device Vendor, Device Product and Device Version are strings that /// uniquely identify the type of sending device. No two products may /// use the same device-vendor and device-product pair. There is /// no central authority managing these pairs. Event producers must /// ensure that they assign unique name pairs. /// </summary> /// <value>The device version.</value> public string DeviceVersion { get; set; } /// <summary> /// Device Event Class ID is a unique identifier per event-type. This /// can be a string or an integer. Device Event Class ID identifies the /// type of event reported. In the intrusion detection system (IDS) world, /// each signature or rule that detects certain activity has a unique /// Device Event Class ID assigned. This is a requirement for other /// types of devices as well, and helps correlation engines process /// the events. Also known as Signature ID. /// </summary> /// <value>The device event class identifier.</value> public string DeviceEventClassID { get; set; } /// <summary> /// Name is a string representing a human-readable and understandable /// description of the event. The event name should not contain /// information that is specifically mentioned in other fields. /// For example: "Port scan from 10.0.0.1 targeting 20.1.1.1" is not a /// good event name. It should be: "Port scan". The other information /// is redundant and can be picked up from the other fields. /// </summary> /// <value>The name.</value> public string Name { get; set; } /// <summary> /// Severity is a string or integer and reflects the importance of the /// event. The valid string values are Unknown, Low, Medium, High, and /// Very-High. The valid integer values are 0-3=Low, 4-6=Medium, /// 7- 8=High, and 9-10=Very-High. /// </summary> /// <value>The severity.</value> public string Severity { get; set; } public CefCustomProperties CustomProperties { get; private set; } } public class CefCustomProperties { [CefField(KeyName = "act", FieldName = "deviceAction", DataType = CefDataType.String, Length = 63)] public string act { get; set; } [CefField(KeyName = "app", FieldName = "applicationProtocol", DataType = CefDataType.String, Length = 31)] public string app { get; set; } [CefField(KeyName = "c6a1", FieldName = "deviceCustomIPv6Address1", DataType = CefDataType.IPv6Address)] public string c6a1 { get; set; } [CefField(KeyName = "c6a1Label", FieldName = "deviceCustomIPv6Address1Label", DataType = CefDataType.String, Length = 1023)] public string c6a1Label { get; set; } [CefField(KeyName = "c6a3", FieldName = "deviceCustomIPv6Address3", DataType = CefDataType.IPv6Address)] public string c6a3 { get; set; } [CefField(KeyName = "c6a4", FieldName = "deviceCustomIPv6Address4", DataType = CefDataType.IPv6Address)] public string c6a4 { get; set; } [CefField(KeyName = "C6a4Label", FieldName = "deviceCustomIPv6Address4Label", DataType = CefDataType.String, Length = 1023)] public string C6a4Label { get; set; } [CefField(KeyName = "cat", FieldName = "deviceEventCategory", DataType = CefDataType.String, Length = 1023)] public string cat { get; set; } [CefField(KeyName = "cfp1", FieldName = "deviceCustomFloatingPoint1", DataType = CefDataType.FloatingPoint)] public string cfp1 { get; set; } [CefField(KeyName = "cfp1Label", FieldName = "deviceCustomFloatingPoint1Label", DataType = CefDataType.String, Length = 1023)] public string cfp1Label { get; set; } [CefField(KeyName = "cfp2", FieldName = "deviceCustomFloatingPoint2", DataType = CefDataType.FloatingPoint)] public string cfp2 { get; set; } [CefField(KeyName = "cfp2Label", FieldName = "deviceCustomFloatingPoint2Label", DataType = CefDataType.String, Length = 1023)] public string cfp2Label { get; set; } [CefField(KeyName = "cfp3", FieldName = "deviceCustomFloatingPoint3", DataType = CefDataType.FloatingPoint)] public string cfp3 { get; set; } [CefField(KeyName = "cfp3Label", FieldName = "deviceCustomFloatingPoint3Label", DataType = CefDataType.String, Length = 1023)] public string cfp3Label { get; set; } [CefField(KeyName = "cfp4", FieldName = "deviceCustomFloatingPoint4", DataType = CefDataType.FloatingPoint)] public string cfp4 { get; set; } [CefField(KeyName = "cfp4Label", FieldName = "deviceCustomFloatingPoint4Label", DataType = CefDataType.String, Length = 1023)] public string cfp4Label { get; set; } [CefField(KeyName = "cn1", FieldName = "deviceCustomNumber1", DataType = CefDataType.Long)] public string cn1 { get; set; } [CefField(KeyName = "cn1Label", FieldName = "deviceCustomNumber1Label", DataType = CefDataType.String, Length = 1023)] public string cn1Label { get; set; } [CefField(KeyName = "cn2", FieldName = "DeviceCustomNumber2", DataType = CefDataType.Long)] public string cn2 { get; set; } [CefField(KeyName = "cn2Label", FieldName = "deviceCustomNumber2Label", DataType = CefDataType.String, Length = 1023)] public string cn2Label { get; set; } [CefField(KeyName = "cn3", FieldName = "deviceCustomNumber3", DataType = CefDataType.Long)] public string cn3 { get; set; } [CefField(KeyName = "cn3Label", FieldName = "deviceCustomNumber3Label", DataType = CefDataType.String, Length = 1023)] public string cn3Label { get; set; } [CefField(KeyName = "cnt", FieldName = "baseEventCount", DataType = CefDataType.Integer)] public int? cnt { get; set; } [CefField(KeyName = "cs1", FieldName = "deviceCustomString1", DataType = CefDataType.String, Length = 4000)] public string cs1 { get; set; } [CefField(KeyName = "cs1Label", FieldName = "deviceCustomString1Label", DataType = CefDataType.String, Length = 1023)] public string cs1Label { get; set; } [CefField(KeyName = "cs2", FieldName = "deviceCustomString2", DataType = CefDataType.String, Length = 4000)] public string cs2 { get; set; } [CefField(KeyName = "cs2Label", FieldName = "deviceCustomString2Label", DataType = CefDataType.String, Length = 1023)] public string cs2Label { get; set; } [CefField(KeyName = "cs3Label", FieldName = "deviceCustomString3Label", DataType = CefDataType.String, Length = 1023)] public string cs3Label { get; set; } [CefField(KeyName = "cs4", FieldName = "deviceCustomString4", DataType = CefDataType.String, Length = 4000)] public string cs4 { get; set; } [CefField(KeyName = "cs4Label", FieldName = "deviceCustomString4Label", DataType = CefDataType.String, Length = 1023)] public string cs4Label { get; set; } [CefField(KeyName = "cs5", FieldName = "deviceCustomString5", DataType = CefDataType.String, Length = 4000)] public string cs5 { get; set; } [CefField(KeyName = "cs5Label", FieldName = "deviceCustomString5Label", DataType = CefDataType.String, Length = 1023)] public string cs5Label { get; set; } [CefField(KeyName = "cs6", FieldName = "deviceCustomString6", DataType = CefDataType.String, Length = 4000)] public string cs6 { get; set; } [CefField(KeyName = "cs6Label", FieldName = "deviceCustomString6Label", DataType = CefDataType.String, Length = 1023)] public string cs6Label { get; set; } [CefField(KeyName = "destinationDnsDomain", FieldName = "destinationDnsDomain", DataType = CefDataType.String, Length = 255)] public string destinationDnsDomain { get; set; } [CefField(KeyName = "destinationServiceName", FieldName = "destinationServiceName", DataType = CefDataType.String, Length = 1023)] public string destinationServiceName { get; set; } [CefField(KeyName = "destinationTranslatedAddress", FieldName = "destinationTranslatedAddress", DataType = CefDataType.IPv4Address)] public string destinationTranslatedAddress { get; set; } [CefField(KeyName = "destinationTranslatedPort", FieldName = "destinationTranslatedPort", DataType = CefDataType.Integer)] public int? destinationTranslatedPort { get; set; } [CefField(KeyName = "deviceCustomDate1", FieldName = "deviceCustomDate1", DataType = CefDataType.TimeStamp)] public string deviceCustomDate1 { get; set; } [CefField(KeyName = "deviceCustomDate1Label", FieldName = "deviceCustomDate1Label", DataType = CefDataType.String, Length = 1023)] public string deviceCustomDate1Label { get; set; } [CefField(KeyName = "deviceCustomDate2", FieldName = "deviceCustomDate2", DataType = CefDataType.TimeStamp)] public string deviceCustomDate2 { get; set; } [CefField(KeyName = "deviceCustomDate2Label", FieldName = "deviceCustomDate2Label", DataType = CefDataType.String, Length = 1023)] public string deviceCustomDate2Label { get; set; } [CefField(KeyName = "deviceDirection", FieldName = "deviceDirection", DataType = CefDataType.Integer)] public int? deviceDirection { get; set; } [CefField(KeyName = "deviceDnsDomain", FieldName = "deviceDnsDomain", DataType = CefDataType.String, Length = 255)] public string deviceDnsDomain { get; set; } [CefField(KeyName = "deviceExternalId", FieldName = "deviceExternalId", DataType = CefDataType.String, Length = 255)] public string deviceExternalId { get; set; } [CefField(KeyName = "deviceFacility", FieldName = "deviceFacility", DataType = CefDataType.String, Length = 1023)] public string deviceFacility { get; set; } [CefField(KeyName = "deviceInboundInterface", FieldName = "deviceInboundInterface", DataType = CefDataType.String, Length = 128)] public string deviceInboundInterface { get; set; } [CefField(KeyName = "deviceNtDomain", FieldName = "deviceNtDomain", DataType = CefDataType.String, Length = 255)] public string deviceNtDomain { get; set; } [CefField(KeyName = "DeviceOutboundInterface", FieldName = "deviceOutboundInterface", DataType = CefDataType.String, Length = 128)] public string DeviceOutboundInterface { get; set; } [CefField(KeyName = "DevicePayloadId", FieldName = "devicePayloadId", DataType = CefDataType.String, Length = 128)] public string DevicePayloadId { get; set; } [CefField(KeyName = "deviceProcessName", FieldName = "deviceProcessName", DataType = CefDataType.String, Length = 1023)] public string deviceProcessName { get; set; } [CefField(KeyName = "dhost", FieldName = "destinationHostName", DataType = CefDataType.String, Length = 1023)] public string dhost { get; set; } [CefField(KeyName = "dmac", FieldName = "destinationMacAddress", DataType = CefDataType.MACAddress)] public string dmac { get; set; } [CefField(KeyName = "dntdom", FieldName = "destinationNtDomain", DataType = CefDataType.String, Length = 255)] public string dntdom { get; set; } [CefField(KeyName = "dpid", FieldName = "destinationProcessId", DataType = CefDataType.Integer)] public int? dpid { get; set; } [CefField(KeyName = "dpriv", FieldName = "destinationUserPrivileges", DataType = CefDataType.String, Length = 1023)] public string dpriv { get; set; } [CefField(KeyName = "dproc", FieldName = "destinationProcessName", DataType = CefDataType.String, Length = 1023)] public string dproc { get; set; } [CefField(KeyName = "dpt", FieldName = "destinationPort", DataType = CefDataType.Integer)] public int? dpt { get; set; } [CefField(KeyName = "dst", FieldName = "destinationAddress", DataType = CefDataType.IPv4Address)] public string dst { get; set; } [CefField(KeyName = "duid", FieldName = "destinationUserId", DataType = CefDataType.String, Length = 1023)] public string duid { get; set; } [CefField(KeyName = "duser", FieldName = "destinationUserName", DataType = CefDataType.String, Length = 1023)] public string duser { get; set; } [CefField(KeyName = "dvc", FieldName = "deviceAddress", DataType = CefDataType.IPv4Address)] public string dvc { get; set; } [CefField(KeyName = "dvchost", FieldName = "deviceHostName", DataType = CefDataType.String, Length = 100)] public string dvchost { get; set; } [CefField(KeyName = "dvcmac", FieldName = "deviceMacAddress", DataType = CefDataType.MACAddress)] public string dvcmac { get; set; } [CefField(KeyName = "dvcpid", FieldName = "deviceProcessId", DataType = CefDataType.Integer)] public int? dvcpid { get; set; } [CefField(KeyName = "end", FieldName = "endTime", DataType = CefDataType.TimeStamp)] public string end { get; set; } [CefField(KeyName = "externalId", FieldName = "externalId", DataType = CefDataType.String, Length = 40)] public string externalId { get; set; } [CefField(KeyName = "fileCreateTime", FieldName = "fileCreateTime", DataType = CefDataType.TimeStamp)] public string fileCreateTime { get; set; } [CefField(KeyName = "fileHash", FieldName = "fileHash", DataType = CefDataType.String, Length = 255)] public string fileHash { get; set; } [CefField(KeyName = "fileModificationTime", FieldName = "fileModificationTime", DataType = CefDataType.TimeStamp)] public string fileModificationTime { get; set; } [CefField(KeyName = "filePath", FieldName = "filePath", DataType = CefDataType.String, Length = 1023)] public string filePath { get; set; } [CefField(KeyName = "filePermission", FieldName = "filePermission", DataType = CefDataType.String, Length = 1023)] public string filePermission { get; set; } [CefField(KeyName = "fileType", FieldName = "fileType", DataType = CefDataType.String, Length = 1023)] public string fileType { get; set; } [CefField(KeyName = "flexDate1", FieldName = "flexDate1", DataType = CefDataType.TimeStamp)] public string flexDate1 { get; set; } [CefField(KeyName = "flexDate1Label", FieldName = "flexDate1Label", DataType = CefDataType.String, Length = 128)] public string flexDate1Label { get; set; } [CefField(KeyName = "flexString1", FieldName = "flexString1", DataType = CefDataType.String, Length = 1023)] public string flexString1 { get; set; } [CefField(KeyName = "flexString1Label", FieldName = "flexString2Label", DataType = CefDataType.String, Length = 128)] public string flexString1Label { get; set; } [CefField(KeyName = "flexString2Label", FieldName = "flexString2Label", DataType = CefDataType.String, Length = 128)] public string flexString2Label { get; set; } [CefField(KeyName = "fname", FieldName = "filename", DataType = CefDataType.String, Length = 1023)] public string fname { get; set; } [CefField(KeyName = "fsize", FieldName = "fileSize", DataType = CefDataType.Integer)] public int? fsize { get; set; } [CefField(KeyName = "in", FieldName = "bytesIn", DataType = CefDataType.Integer)] public int? inb { get; set; } [CefField(KeyName = "msg", FieldName = "message", DataType = CefDataType.String, Length = 1023)] public string msg { get; set; } [CefField(KeyName = "oldFileCreateTime", FieldName = "oldFileCreateTime", DataType = CefDataType.TimeStamp)] public string oldFileCreateTime { get; set; } [CefField(KeyName = "oldFileHash", FieldName = "oldFileHash", DataType = CefDataType.String, Length = 255)] public string oldFileHash { get; set; } [CefField(KeyName = "oldFileId", FieldName = "oldFileId", DataType = CefDataType.String, Length = 1023)] public string oldFileId { get; set; } [CefField(KeyName = "oldFileModificationTime", FieldName = "oldFileModificationTime", DataType = CefDataType.TimeStamp)] public string oldFileModificationTime { get; set; } [CefField(KeyName = "oldFileName", FieldName = "oldFileName", DataType = CefDataType.String, Length = 1023)] public string oldFileName { get; set; } [CefField(KeyName = "oldFilePath", FieldName = "oldFilePath", DataType = CefDataType.String, Length = 1023)] public string oldFilePath { get; set; } [CefField(KeyName = "oldFilePermission", FieldName = "oldFilePermission", DataType = CefDataType.String, Length = 1023)] public string oldFilePermission { get; set; } [CefField(KeyName = "oldFileSize", FieldName = "oldFileSize", DataType = CefDataType.Integer)] public int? oldFileSize { get; set; } [CefField(KeyName = "out", FieldName = "bytesOut", DataType = CefDataType.Integer)] public int? outb { get; set; } [CefField(KeyName = "outcome", FieldName = "eventOutcome", DataType = CefDataType.String, Length = 63)] public string outcome { get; set; } [CefField(KeyName = "proto", FieldName = "transportProtocol", DataType = CefDataType.String, Length = 31)] public string proto { get; set; } [CefField(KeyName = "reason", FieldName = "Reason", DataType = CefDataType.String, Length = 1023)] public string reason { get; set; } [CefField(KeyName = "request", FieldName = "requestUrl", DataType = CefDataType.String, Length = 1023)] public string request { get; set; } [CefField(KeyName = "requestClientApplication", FieldName = "requestClientApplication", DataType = CefDataType.String, Length = 1023)] public string requestClientApplication { get; set; } [CefField(KeyName = "requestContext", FieldName = "requestContext", DataType = CefDataType.String, Length = 2048)] public string requestContext { get; set; } [CefField(KeyName = "requestCookies", FieldName = "requestCookies", DataType = CefDataType.String, Length = 1023)] public string requestCookies { get; set; } [CefField(KeyName = "requestMethod", FieldName = "requestMethod", DataType = CefDataType.String, Length = 1023)] public string requestMethod { get; set; } [CefField(KeyName = "rt", FieldName = "deviceReceiptTime", DataType = CefDataType.TimeStamp)] public string rt { get; set; } [CefField(KeyName = "shost", FieldName = "sourceHostName", DataType = CefDataType.String, Length = 1023)] public string shost { get; set; } [CefField(KeyName = "smac", FieldName = "sourceMacAddress", DataType = CefDataType.MACAddress)] public string smac { get; set; } [CefField(KeyName = "sntdom", FieldName = "sourceNtDomain", DataType = CefDataType.String, Length = 255)] public string sntdom { get; set; } [CefField(KeyName = "sourceDnsDomain", FieldName = "sourceDnsDomain", DataType = CefDataType.String, Length = 255)] public string sourceDnsDomain { get; set; } [CefField(KeyName = "sourceServiceName", FieldName = "sourceServiceName", DataType = CefDataType.String, Length = 1023)] public string sourceServiceName { get; set; } [CefField(KeyName = "sourceTranslatedAddress", FieldName = "sourceTranslatedAddress", DataType = CefDataType.IPv4Address)] public string sourceTranslatedAddress { get; set; } [CefField(KeyName = "sourceTranslatedPort", FieldName = "sourceTranslatedPort", DataType = CefDataType.Integer)] public int? sourceTranslatedPort { get; set; } [CefField(KeyName = "spid", FieldName = "sourceProcessId", DataType = CefDataType.Integer)] public int? spid { get; set; } [CefField(KeyName = "spriv", FieldName = "sourceUserPrivileges", DataType = CefDataType.String, Length = 1023)] public string spriv { get; set; } [CefField(KeyName = "sproc", FieldName = "sourceProcessName", DataType = CefDataType.String, Length = 1023)] public string sproc { get; set; } [CefField(KeyName = "spt", FieldName = "sourcePort", DataType = CefDataType.Integer)] public int? spt { get; set; } [CefField(KeyName = "src", FieldName = "sourceAddress", DataType = CefDataType.IPv4Address)] public string src { get; set; } [CefField(KeyName = "start", FieldName = "startTime", DataType = CefDataType.TimeStamp)] public string start { get; set; } [CefField(KeyName = "suid", FieldName = "sourceUserId", DataType = CefDataType.String, Length = 1023)] public string suid { get; set; } [CefField(KeyName = "suser", FieldName = "sourceUserName", DataType = CefDataType.String, Length = 1023)] public string suser { get; set; } [CefField(KeyName = "type", FieldName = "type", DataType = CefDataType.Integer)] public int? type { get; set; } } }
/* * Exchange Web Services Managed API * * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ namespace Microsoft.Exchange.WebServices.Data { using System.Collections.Generic; /// <summary> /// Represents a permission on a folder. /// </summary> public sealed class FolderPermission : ComplexProperty { #region Default permissions private static LazyMember<Dictionary<FolderPermissionLevel, FolderPermission>> defaultPermissions = new LazyMember<Dictionary<FolderPermissionLevel, FolderPermission>>( delegate() { Dictionary<FolderPermissionLevel, FolderPermission> result = new Dictionary<FolderPermissionLevel, FolderPermission>(); FolderPermission permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = false; permission.readItems = FolderPermissionReadAccess.None; result.Add(FolderPermissionLevel.None, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.None; result.Add(FolderPermissionLevel.Contributor, permission); permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.Reviewer, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.Owned; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.NoneditingAuthor, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.Owned; permission.editItems = PermissionScope.Owned; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.Author, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = true; permission.deleteItems = PermissionScope.Owned; permission.editItems = PermissionScope.Owned; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.PublishingAuthor, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.All; permission.editItems = PermissionScope.All; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.Editor, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = true; permission.deleteItems = PermissionScope.All; permission.editItems = PermissionScope.All; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.PublishingEditor, permission); permission = new FolderPermission(); permission.canCreateItems = true; permission.canCreateSubFolders = true; permission.deleteItems = PermissionScope.All; permission.editItems = PermissionScope.All; permission.isFolderContact = true; permission.isFolderOwner = true; permission.isFolderVisible = true; permission.readItems = FolderPermissionReadAccess.FullDetails; result.Add(FolderPermissionLevel.Owner, permission); permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = false; permission.readItems = FolderPermissionReadAccess.TimeOnly; result.Add(FolderPermissionLevel.FreeBusyTimeOnly, permission); permission = new FolderPermission(); permission.canCreateItems = false; permission.canCreateSubFolders = false; permission.deleteItems = PermissionScope.None; permission.editItems = PermissionScope.None; permission.isFolderContact = false; permission.isFolderOwner = false; permission.isFolderVisible = false; permission.readItems = FolderPermissionReadAccess.TimeAndSubjectAndLocation; result.Add(FolderPermissionLevel.FreeBusyTimeAndSubjectAndLocation, permission); return result; }); #endregion /// <summary> /// Variants of pre-defined permission levels that Outlook also displays with the same levels. /// </summary> private static LazyMember<List<FolderPermission>> levelVariants = new LazyMember<List<FolderPermission>>( delegate() { List<FolderPermission> results = new List<FolderPermission>(); FolderPermission permissionNone = FolderPermission.defaultPermissions.Member[FolderPermissionLevel.None]; FolderPermission permissionOwner = FolderPermission.defaultPermissions.Member[FolderPermissionLevel.Owner]; // PermissionLevelNoneOption1 FolderPermission permission = permissionNone.Clone(); permission.isFolderVisible = true; results.Add(permission); // PermissionLevelNoneOption2 permission = permissionNone.Clone(); permission.isFolderContact = true; results.Add(permission); // PermissionLevelNoneOption3 permission = permissionNone.Clone(); permission.isFolderContact = true; permission.isFolderVisible = true; results.Add(permission); // PermissionLevelOwnerOption1 permission = permissionOwner.Clone(); permission.isFolderContact = false; results.Add(permission); return results; }); private UserId userId; private bool canCreateItems; private bool canCreateSubFolders; private bool isFolderOwner; private bool isFolderVisible; private bool isFolderContact; private PermissionScope editItems; private PermissionScope deleteItems; private FolderPermissionReadAccess readItems; private FolderPermissionLevel permissionLevel; /// <summary> /// Determines whether the specified folder permission is the same as this one. The comparison /// does not take UserId and PermissionLevel into consideration. /// </summary> /// <param name="permission">The folder permission to compare with this folder permission.</param> /// <returns> /// True is the specified folder permission is equal to this one, false otherwise. /// </returns> private bool IsEqualTo(FolderPermission permission) { return this.CanCreateItems == permission.CanCreateItems && this.CanCreateSubFolders == permission.CanCreateSubFolders && this.IsFolderContact == permission.IsFolderContact && this.IsFolderVisible == permission.IsFolderVisible && this.IsFolderOwner == permission.IsFolderOwner && this.EditItems == permission.EditItems && this.DeleteItems == permission.DeleteItems && this.ReadItems == permission.ReadItems; } /// <summary> /// Create a copy of this FolderPermission instance. /// </summary> /// <returns> /// Clone of this instance. /// </returns> private FolderPermission Clone() { return (FolderPermission)this.MemberwiseClone(); } /// <summary> /// Determines the permission level of this folder permission based on its individual settings, /// and sets the PermissionLevel property accordingly. /// </summary> private void AdjustPermissionLevel() { foreach (KeyValuePair<FolderPermissionLevel, FolderPermission> keyValuePair in defaultPermissions.Member) { if (this.IsEqualTo(keyValuePair.Value)) { this.permissionLevel = keyValuePair.Key; return; } } this.permissionLevel = FolderPermissionLevel.Custom; } /// <summary> /// Copies the values of the individual permissions of the specified folder permission /// to this folder permissions. /// </summary> /// <param name="permission">The folder permission to copy the values from.</param> private void AssignIndividualPermissions(FolderPermission permission) { this.canCreateItems = permission.CanCreateItems; this.canCreateSubFolders = permission.CanCreateSubFolders; this.isFolderContact = permission.IsFolderContact; this.isFolderOwner = permission.IsFolderOwner; this.isFolderVisible = permission.IsFolderVisible; this.editItems = permission.EditItems; this.deleteItems = permission.DeleteItems; this.readItems = permission.ReadItems; } /// <summary> /// Initializes a new instance of the <see cref="FolderPermission"/> class. /// </summary> public FolderPermission() : base() { this.UserId = new UserId(); } /// <summary> /// Initializes a new instance of the <see cref="FolderPermission"/> class. /// </summary> /// <param name="userId">The Id of the user the permission applies to.</param> /// <param name="permissionLevel">The level of the permission.</param> public FolderPermission(UserId userId, FolderPermissionLevel permissionLevel) { EwsUtilities.ValidateParam(userId, "userId"); this.userId = userId; this.PermissionLevel = permissionLevel; } /// <summary> /// Initializes a new instance of the <see cref="FolderPermission"/> class. /// </summary> /// <param name="primarySmtpAddress">The primary SMTP address of the user the permission applies to.</param> /// <param name="permissionLevel">The level of the permission.</param> public FolderPermission(string primarySmtpAddress, FolderPermissionLevel permissionLevel) { this.userId = new UserId(primarySmtpAddress); this.PermissionLevel = permissionLevel; } /// <summary> /// Initializes a new instance of the <see cref="FolderPermission"/> class. /// </summary> /// <param name="standardUser">The standard user the permission applies to.</param> /// <param name="permissionLevel">The level of the permission.</param> public FolderPermission(StandardUser standardUser, FolderPermissionLevel permissionLevel) { this.userId = new UserId(standardUser); this.PermissionLevel = permissionLevel; } /// <summary> /// Validates this instance. /// </summary> /// <param name="isCalendarFolder">if set to <c>true</c> calendar permissions are allowed.</param> /// <param name="permissionIndex">Index of the permission.</param> internal void Validate(bool isCalendarFolder, int permissionIndex) { // Check UserId if (!this.UserId.IsValid()) { throw new ServiceValidationException( string.Format( Strings.FolderPermissionHasInvalidUserId, permissionIndex)); } // If this permission is to be used for a non-calendar folder make sure that read access and permission level aren't set to Calendar-only values if (!isCalendarFolder) { if ((this.readItems == FolderPermissionReadAccess.TimeAndSubjectAndLocation) || (this.readItems == FolderPermissionReadAccess.TimeOnly)) { throw new ServiceLocalException( string.Format( Strings.ReadAccessInvalidForNonCalendarFolder, this.readItems)); } if ((this.permissionLevel == FolderPermissionLevel.FreeBusyTimeAndSubjectAndLocation) || (this.permissionLevel == FolderPermissionLevel.FreeBusyTimeOnly)) { throw new ServiceLocalException( string.Format( Strings.PermissionLevelInvalidForNonCalendarFolder, this.permissionLevel)); } } } /// <summary> /// Gets the Id of the user the permission applies to. /// </summary> public UserId UserId { get { return this.userId; } set { if (this.userId != null) { this.userId.OnChange -= this.PropertyChanged; } this.SetFieldValue<UserId>(ref this.userId, value); if (this.userId != null) { this.userId.OnChange += this.PropertyChanged; } } } /// <summary> /// Gets or sets a value indicating whether the user can create new items. /// </summary> public bool CanCreateItems { get { return this.canCreateItems; } set { this.SetFieldValue<bool>(ref this.canCreateItems, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets a value indicating whether the user can create sub-folders. /// </summary> public bool CanCreateSubFolders { get { return this.canCreateSubFolders; } set { this.SetFieldValue<bool>(ref this.canCreateSubFolders, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets a value indicating whether the user owns the folder. /// </summary> public bool IsFolderOwner { get { return this.isFolderOwner; } set { this.SetFieldValue<bool>(ref this.isFolderOwner, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets a value indicating whether the folder is visible to the user. /// </summary> public bool IsFolderVisible { get { return this.isFolderVisible; } set { this.SetFieldValue<bool>(ref this.isFolderVisible, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets a value indicating whether the user is a contact for the folder. /// </summary> public bool IsFolderContact { get { return this.isFolderContact; } set { this.SetFieldValue<bool>(ref this.isFolderContact, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets a value indicating if/how the user can edit existing items. /// </summary> public PermissionScope EditItems { get { return this.editItems; } set { this.SetFieldValue<PermissionScope>(ref this.editItems, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets a value indicating if/how the user can delete existing items. /// </summary> public PermissionScope DeleteItems { get { return this.deleteItems; } set { this.SetFieldValue<PermissionScope>(ref this.deleteItems, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets the read items access permission. /// </summary> public FolderPermissionReadAccess ReadItems { get { return this.readItems; } set { this.SetFieldValue<FolderPermissionReadAccess>(ref this.readItems, value); this.AdjustPermissionLevel(); } } /// <summary> /// Gets or sets the permission level. /// </summary> public FolderPermissionLevel PermissionLevel { get { return this.permissionLevel; } set { if (this.permissionLevel != value) { if (value == FolderPermissionLevel.Custom) { throw new ServiceLocalException(Strings.CannotSetPermissionLevelToCustom); } this.AssignIndividualPermissions(defaultPermissions.Member[value]); this.SetFieldValue<FolderPermissionLevel>(ref this.permissionLevel, value); } } } /// <summary> /// Gets the permission level that Outlook would display for this folder permission. /// </summary> public FolderPermissionLevel DisplayPermissionLevel { get { // If permission level is set to Custom, see if there's a variant // that Outlook would map to the same permission level. if (this.permissionLevel == FolderPermissionLevel.Custom) { foreach (FolderPermission variant in FolderPermission.levelVariants.Member) { if (this.IsEqualTo(variant)) { return variant.PermissionLevel; } } } return this.permissionLevel; } } /// <summary> /// Property was changed. /// </summary> /// <param name="complexProperty">The complex property.</param> private void PropertyChanged(ComplexProperty complexProperty) { this.Changed(); } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.UserId: this.UserId = new UserId(); this.UserId.LoadFromXml(reader, reader.LocalName); return true; case XmlElementNames.CanCreateItems: this.canCreateItems = reader.ReadValue<bool>(); return true; case XmlElementNames.CanCreateSubFolders: this.canCreateSubFolders = reader.ReadValue<bool>(); return true; case XmlElementNames.IsFolderOwner: this.isFolderOwner = reader.ReadValue<bool>(); return true; case XmlElementNames.IsFolderVisible: this.isFolderVisible = reader.ReadValue<bool>(); return true; case XmlElementNames.IsFolderContact: this.isFolderContact = reader.ReadValue<bool>(); return true; case XmlElementNames.EditItems: this.editItems = reader.ReadValue<PermissionScope>(); return true; case XmlElementNames.DeleteItems: this.deleteItems = reader.ReadValue<PermissionScope>(); return true; case XmlElementNames.ReadItems: this.readItems = reader.ReadValue<FolderPermissionReadAccess>(); return true; case XmlElementNames.PermissionLevel: case XmlElementNames.CalendarPermissionLevel: this.permissionLevel = reader.ReadValue<FolderPermissionLevel>(); return true; default: return false; } } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal override void LoadFromXml( EwsServiceXmlReader reader, XmlNamespace xmlNamespace, string xmlElementName) { base.LoadFromXml(reader, xmlNamespace, xmlElementName); this.AdjustPermissionLevel(); } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="isCalendarFolder">If true, this permission is for a calendar folder.</param> internal void WriteElementsToXml(EwsServiceXmlWriter writer, bool isCalendarFolder) { if (this.UserId != null) { this.UserId.WriteToXml(writer, XmlElementNames.UserId); } if (this.PermissionLevel == FolderPermissionLevel.Custom) { writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.CanCreateItems, this.CanCreateItems); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.CanCreateSubFolders, this.CanCreateSubFolders); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsFolderOwner, this.IsFolderOwner); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsFolderVisible, this.IsFolderVisible); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.IsFolderContact, this.IsFolderContact); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.EditItems, this.EditItems); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.DeleteItems, this.DeleteItems); writer.WriteElementValue( XmlNamespace.Types, XmlElementNames.ReadItems, this.ReadItems); } writer.WriteElementValue( XmlNamespace.Types, isCalendarFolder ? XmlElementNames.CalendarPermissionLevel : XmlElementNames.PermissionLevel, this.PermissionLevel); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlElementName">Name of the XML element.</param> /// <param name="isCalendarFolder">If true, this permission is for a calendar folder.</param> internal void WriteToXml( EwsServiceXmlWriter writer, string xmlElementName, bool isCalendarFolder) { writer.WriteStartElement(this.Namespace, xmlElementName); this.WriteAttributesToXml(writer); this.WriteElementsToXml(writer, isCalendarFolder); writer.WriteEndElement(); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gagr = Google.Api.Gax.ResourceNames; using gcov = Google.Cloud.OsConfig.V1; using sys = System; namespace Google.Cloud.OsConfig.V1 { /// <summary>Resource name for the <c>PatchDeployment</c> resource.</summary> public sealed partial class PatchDeploymentName : gax::IResourceName, sys::IEquatable<PatchDeploymentName> { /// <summary>The possible contents of <see cref="PatchDeploymentName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/patchDeployments/{patch_deployment}</c>. /// </summary> ProjectPatchDeployment = 1, } private static gax::PathTemplate s_projectPatchDeployment = new gax::PathTemplate("projects/{project}/patchDeployments/{patch_deployment}"); /// <summary>Creates a <see cref="PatchDeploymentName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="PatchDeploymentName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static PatchDeploymentName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new PatchDeploymentName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="PatchDeploymentName"/> with the pattern /// <c>projects/{project}/patchDeployments/{patch_deployment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="patchDeploymentId">The <c>PatchDeployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="PatchDeploymentName"/> constructed from the provided ids.</returns> public static PatchDeploymentName FromProjectPatchDeployment(string projectId, string patchDeploymentId) => new PatchDeploymentName(ResourceNameType.ProjectPatchDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), patchDeploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(patchDeploymentId, nameof(patchDeploymentId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="PatchDeploymentName"/> with pattern /// <c>projects/{project}/patchDeployments/{patch_deployment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="patchDeploymentId">The <c>PatchDeployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PatchDeploymentName"/> with pattern /// <c>projects/{project}/patchDeployments/{patch_deployment}</c>. /// </returns> public static string Format(string projectId, string patchDeploymentId) => FormatProjectPatchDeployment(projectId, patchDeploymentId); /// <summary> /// Formats the IDs into the string representation of this <see cref="PatchDeploymentName"/> with pattern /// <c>projects/{project}/patchDeployments/{patch_deployment}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="patchDeploymentId">The <c>PatchDeployment</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="PatchDeploymentName"/> with pattern /// <c>projects/{project}/patchDeployments/{patch_deployment}</c>. /// </returns> public static string FormatProjectPatchDeployment(string projectId, string patchDeploymentId) => s_projectPatchDeployment.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(patchDeploymentId, nameof(patchDeploymentId))); /// <summary> /// Parses the given resource name string into a new <see cref="PatchDeploymentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/patchDeployments/{patch_deployment}</c></description></item> /// </list> /// </remarks> /// <param name="patchDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="PatchDeploymentName"/> if successful.</returns> public static PatchDeploymentName Parse(string patchDeploymentName) => Parse(patchDeploymentName, false); /// <summary> /// Parses the given resource name string into a new <see cref="PatchDeploymentName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/patchDeployments/{patch_deployment}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="patchDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="PatchDeploymentName"/> if successful.</returns> public static PatchDeploymentName Parse(string patchDeploymentName, bool allowUnparsed) => TryParse(patchDeploymentName, allowUnparsed, out PatchDeploymentName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PatchDeploymentName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/patchDeployments/{patch_deployment}</c></description></item> /// </list> /// </remarks> /// <param name="patchDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="PatchDeploymentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string patchDeploymentName, out PatchDeploymentName result) => TryParse(patchDeploymentName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="PatchDeploymentName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/patchDeployments/{patch_deployment}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="patchDeploymentName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="PatchDeploymentName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string patchDeploymentName, bool allowUnparsed, out PatchDeploymentName result) { gax::GaxPreconditions.CheckNotNull(patchDeploymentName, nameof(patchDeploymentName)); gax::TemplatedResourceName resourceName; if (s_projectPatchDeployment.TryParseName(patchDeploymentName, out resourceName)) { result = FromProjectPatchDeployment(resourceName[0], resourceName[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(patchDeploymentName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private PatchDeploymentName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string patchDeploymentId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; PatchDeploymentId = patchDeploymentId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="PatchDeploymentName"/> class from the component parts of pattern /// <c>projects/{project}/patchDeployments/{patch_deployment}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="patchDeploymentId">The <c>PatchDeployment</c> ID. Must not be <c>null</c> or empty.</param> public PatchDeploymentName(string projectId, string patchDeploymentId) : this(ResourceNameType.ProjectPatchDeployment, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), patchDeploymentId: gax::GaxPreconditions.CheckNotNullOrEmpty(patchDeploymentId, nameof(patchDeploymentId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>PatchDeployment</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource /// name. /// </summary> public string PatchDeploymentId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.ProjectPatchDeployment: return s_projectPatchDeployment.Expand(ProjectId, PatchDeploymentId); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as PatchDeploymentName); /// <inheritdoc/> public bool Equals(PatchDeploymentName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(PatchDeploymentName a, PatchDeploymentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(PatchDeploymentName a, PatchDeploymentName b) => !(a == b); } public partial class PatchDeployment { /// <summary> /// <see cref="gcov::PatchDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::PatchDeploymentName PatchDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcov::PatchDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class CreatePatchDeploymentRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class GetPatchDeploymentRequest { /// <summary> /// <see cref="gcov::PatchDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::PatchDeploymentName PatchDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcov::PatchDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } public partial class ListPatchDeploymentsRequest { /// <summary> /// <see cref="gagr::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gagr::ProjectName ParentAsProjectName { get => string.IsNullOrEmpty(Parent) ? null : gagr::ProjectName.Parse(Parent, allowUnparsed: true); set => Parent = value?.ToString() ?? ""; } } public partial class DeletePatchDeploymentRequest { /// <summary> /// <see cref="gcov::PatchDeploymentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcov::PatchDeploymentName PatchDeploymentName { get => string.IsNullOrEmpty(Name) ? null : gcov::PatchDeploymentName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Collections; using System.IO; using l2pvp; namespace l2pvp { public partial class BuffForm : Form { protected Client c; protected GameServer gs; public BuffForm(Client _c, GameServer _gs) { c = _c; gs = _gs; InitializeComponent(); c.doafterskill.Clear(); c.doonskill.Clear(); foreach (skillmap s in gs.skills.Values) { cbOn.Items.Add(s); cbAfter.Items.Add(s); } } private void Form2_Load(object sender, EventArgs e) { } private void btn_cancel_Click(object sender, EventArgs e) { this.Hide(); } private void btn_ok_Click(object sender, EventArgs e) { try { c.doonskill.Clear(); foreach (ListViewItem item in listView1.Items) { evtSkill s = (evtSkill)item.Tag; c.doonskill.Add(s.evt.id, s); } c.doafterskill.Clear(); foreach (ListViewItem item in listView2.Items) { evtSkill s = (evtSkill)item.Tag; c.doafterskill.Add(s.evt.id, s); } this.Hide(); } catch (Exception ex) { //MessageBox.Show(ex.ToString(), "Error in setting buffs"); Console.WriteLine("Error in setting buffs {0}", ex.ToString()); this.Hide(); } } public void populateskilllist_d(List<skill> skilllist) { try { if (this.InvokeRequired) Invoke(new poplist(populateskilllist), new object[] { skilllist }); else populateskilllist(skilllist); } catch { } } public delegate void poplist(List<skill> skilllist); public void populateskilllist(List<skill> skilllist) { cbBuffOn.Items.Clear(); cbBuffAfter.Items.Clear(); foreach (skill i in skilllist) { //found skill cbBuffAfter.Items.Add(i); cbBuffOn.Items.Add(i); } } private void button1_Click(object sender, EventArgs e) { string fname = textBox1.Text; fname = "dance-" + fname; saveConfig(fname); } public void saveConfig(string fname) { try { StreamWriter writefile = new StreamWriter(new FileStream(fname, FileMode.Create), Encoding.UTF8); foreach (ListViewItem i in listView1.Items) { evtSkill s = (evtSkill)i.Tag; writefile.WriteLine("On, {0}, {1}", s.evt.id, s.act.id); } foreach (ListViewItem i2 in listView2.Items) { evtSkill s = (evtSkill)i2.Tag; writefile.WriteLine("After, {0}, {1}", s.evt.id, s.act.id); } writefile.Flush(); writefile.Close(); } catch { } } private void button2_Click(object sender, EventArgs e) { string fname = textBox1.Text; fname = "dance-" + fname; loadConfig(fname); } public void loadConfig(string fname) { StreamReader readfile; try { readfile = new StreamReader(new FileStream(fname, FileMode.Open), Encoding.UTF8); if (readfile == null) return; } catch { MessageBox.Show("couldn't open file {0} for reading", fname); return; } string line; int on = 0, after = 0; listView1.Items.Clear(); listView2.Items.Clear(); while ((line = readfile.ReadLine()) != null) { char[] sep = new char[1]; sep[0] = ','; char[] trim = new char[1]; trim[0] = ' '; string[] split = line.Split(sep, StringSplitOptions.RemoveEmptyEntries); if (split[0] == "On" && on < 6) { if (split[1] == "null" || split[2] == "null") { } else { uint evtid = Convert.ToUInt32(split[1].TrimStart(trim)); uint actid = Convert.ToUInt32(split[2].TrimStart(trim)); skillmap evt = gs.skills[evtid]; skill act = null; foreach (skill sk in c.skilllist) { if (actid == sk.id) { act = sk; break; } } if (act == null) continue; evtSkill s = new evtSkill(); s.evt = evt; s.act = act; ListViewItem item = new ListViewItem(evt.name); item.SubItems.Add(act.name); item.Tag = s; listView1.Items.Add(item); } } else if (split[0] == "After" && after < 6) { if (split[1] == "null" || split[2] == "null") { } else { uint evtid = Convert.ToUInt32(split[1].TrimStart(trim)); uint actid = Convert.ToUInt32(split[2].TrimStart(trim)); skillmap evt = gs.skills[evtid]; skill act = null; foreach (skill sk in c.skilllist) { if (actid == sk.id) { act = sk; break; } } if (act == null) continue; evtSkill s = new evtSkill(); s.evt = evt; s.act = act; ListViewItem item = new ListViewItem(evt.name); item.SubItems.Add(act.name); item.Tag = s; listView2.Items.Add(item); } } } readfile.Close(); c.doonskill.Clear(); foreach (ListViewItem item in listView1.Items) { evtSkill s = (evtSkill)item.Tag; c.doonskill.Add(s.evt.id, s); } c.doafterskill.Clear(); foreach (ListViewItem item in listView2.Items) { evtSkill s = (evtSkill)item.Tag; c.doafterskill.Add(s.evt.id, s); } } private void button3_Click(object sender, EventArgs e) { //Add for onbuff skillmap evt = (skillmap)cbOn.SelectedItem; if (evt == null) return; skill act = (skill)cbBuffOn.SelectedItem; if (act == null) return; if (c.doonskill.ContainsKey(evt.id)) { MessageBox.Show("Cannot have multiple skills launch from one skill"); return; } evtSkill s = new evtSkill(); s.evt = evt; s.act = act; ListViewItem item = new ListViewItem(evt.name); item.SubItems.Add(act.name); item.Tag = s; listView1.Items.Add(item); //c.doonskill.Add(s.evt.id, s); } private void cbON_SelectedIndexChanged(object sender, EventArgs e) { } private void button4_Click(object sender, EventArgs e) { //delete for onbuff ListView.SelectedListViewItemCollection ic = listView1.SelectedItems; foreach (ListViewItem i in ic) { listView1.Items.Remove(i); } } private void button6_Click(object sender, EventArgs e) { skillmap evt = (skillmap)cbAfter.SelectedItem; if (evt == null) return; skill act = (skill)cbBuffAfter.SelectedItem; if (act == null) return; if (c.doafterskill.ContainsKey(evt.id)) { MessageBox.Show("Cannot have multiple skills launch from one skill"); return; } evtSkill s = new evtSkill(); s.evt = evt; s.act = act; ListViewItem item = new ListViewItem(evt.name); item.SubItems.Add(act.name); item.Tag = s; listView2.Items.Add(item); } private void button5_Click(object sender, EventArgs e) { ListView.SelectedListViewItemCollection ic = listView2.SelectedItems; foreach (ListViewItem i in ic) { listView2.Items.Remove(i); } } public void loadconfig_d(string fname) { if (this.InvokeRequired) Invoke(new loadconfig(loadConfig), new object[] { fname }); else loadConfig(fname); } public delegate void loadconfig(string fname); } public class skillmap { public uint id; public string name; public override string ToString() { return name; } } public class evtSkill { public skillmap evt; public skill act; public System.Threading.ManualResetEvent mre; public bool succeed = false; public evtSkill() { mre = new System.Threading.ManualResetEvent(false); } } }
using UnityEngine; using System.Collections; using System.Runtime.InteropServices; /// <summary> /// TestFlight SDK Unity binding. For most use cases calling TestFlightBinding.TakeOff("<app_token>"); /// during your application initialization phase is sufficient to use TestFlight. If you require more /// configuration or management the functions listed below. /// /// Your TestFlight App Token is available from testflightapp.com. /// /// Copyright (C) 2013, Red Finch Software. All rights reserved. /// </summary> public class TestFlightBinding { #region Objective-C Bindings [DllImport("__Internal")] private static extern bool _AddCustomEnvironmentInformation (string information, string key); [DllImport("__Internal")] private static extern bool _TakeOff(string applicationToken); [DllImport("__Internal")] private static extern bool _PassCheckpoint(string checkpoint); [DllImport("__Internal")] private static extern bool _SubmitFeedback(string feedback); [DllImport("__Internal")] private static extern bool _Log(string message); [DllImport("__Internal")] private static extern bool _DisableInAppUpdates(bool enabled); [DllImport("__Internal")] private static extern bool _FlushSecondsInterval(int seconds); [DllImport("__Internal")] private static extern bool _LogOnCheckpoint(bool enabled); [DllImport("__Internal")] private static extern bool _EnableLogToConsole(bool enabled); [DllImport("__Internal")] private static extern bool _EnableSTDErrLogger(bool enabled); [DllImport("__Internal")] private static extern bool _ReportCrashes(bool enabled); [DllImport("__Internal")] private static extern bool _SendLogOnlyOnCrash(bool enabled); [DllImport("__Internal")] private static extern bool _SessionKeepAliveTimeout(int seconds); #endregion #region Unity Bindings /// <summary> /// Adds custom environment information to the current session. /// If you want to track custom information such as a user name from your application you can add it here. /// </summary> /// <param name='information'> /// A string containing the information you are storing. /// </param> /// <param name='key'> /// The key to store the information with. /// </param> public static void AddCustomEnvironmentInformation (string information, string key) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _AddCustomEnvironmentInformation(information, key); } /// <summary> /// Starts a TestFlight session using the Application Token for this Application. /// </summary> /// <param name='applicationToken'> /// Will be the application token for the current application.. /// </param> public static void TakeOff(string applicationToken) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _TakeOff(applicationToken); } /// <summary> /// Track when a user has passed a checkpoint after a TestFlight session has started. /// </summary> /// <param name='checkpoint'> /// The name of the checkpoint. /// </param> public static void PassCheckpoint(string checkpoint) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _PassCheckpoint(checkpoint); } /// <summary> /// Submits custom feedback to the site. Sends the data in feedback to the site. This is to be used as the method to submit /// feedback from custom feedback forms. /// </summary> /// <param name='feedback'> /// Your users feedback, method does nothing if feedback is null. /// </param> public static void SubmitFeedback(string feedback) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _SubmitFeedback(feedback); } /// <summary> /// Log the specified message using remote logging. /// </summary> /// <param name='message'> /// The message to log. /// </param> public static void Log(string message) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _Log(message); } /// <summary> /// Defaults to false. Setting to true disables the in app update screen shown in BETA apps /// when there is a new version available on TestFlight. /// </summary> /// <param name='enabled'> /// Enable or disable in app updates. /// </param> public static void DisableInAppUpdates(bool enabled) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _DisableInAppUpdates(enabled); } /// <summary> /// Defaults to 60. 0 turns off the flush timer. 30 seconds is the minimum flush interval. /// </summary> /// <param name='seconds'> /// The interval where all logs and data are written out to disk. /// </param> public static void FlushSecondsInterval(int seconds) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _FlushSecondsInterval(seconds); } /// <summary> /// Defaults to true. Log to disk when passing a checkpoint. /// </summary> /// <param name='enabled'> /// Enable or disable logging at checkpoints. /// </param> public static void LogOnCheckpoint(bool enabled) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _LogOnCheckpoint(enabled); } /// <summary> /// Defaults to true. Prints remote logs to Apple System Log. /// </summary> /// <param name='enabled'> /// Enable or disable logging to the console. /// </param> public static void EnableLogToConsole(bool enabled) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _EnableLogToConsole(enabled); } /// <summary> /// Defaults to true. Sends remote logs to STDERR when debugger is attached. /// </summary> /// <param name='enabled'> /// Enable or disable logging to STDERR. /// </param> public static void EnableSTDErrLogger(bool enabled) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _EnableSTDErrLogger(enabled); } /// <summary> /// Defaults to true. If set to false, crash handlers are never installed. /// </summary> /// <param name='enabled'> /// Enable or disable crash reporting. /// </param> public static void ReportCrashes(bool enabled) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _ReportCrashes(enabled); } /// <summary> /// Defaults to false. Setting to true stops remote logs from being sent when sessions end. /// They would only be sent in the event of a crash. /// </summary> /// <param name='enabled'> /// Enable or disable sending of logs. /// </param> public static void SendLogOnlyOnCrash(bool enabled) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _SendLogOnlyOnCrash(enabled); } /// <summary> /// Defaults to 30. This is the amount of time a user can leave the app for and still continue /// the same session when they come back. If they are away from the app for longer, a new session /// is created when they come back. Change to 0 to turn off. /// </summary> /// <param name='seconds'> /// Number of seconds to keep the current session alive. /// </param> public static void SessionKeepAliveTimeout(int seconds) { if ( Application.platform == RuntimePlatform.IPhonePlayer ) _SessionKeepAliveTimeout(seconds); } #endregion }
// 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.Maintainability.Analyzers.UnitTests { public class ReviewUnusedParametersTests : DiagnosticAnalyzerTestBase { #region Unit tests for no analyzer diagnostic [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticSimpleCasesTest() { VerifyCSharp(@" using System; public class NeatCode { // Used parameter methods public void UsedParameterMethod1(string use) { Console.WriteLine(this); Console.WriteLine(use); } public void UsedParameterMethod2(string use) { UsedParameterMethod3(ref use); } public void UsedParameterMethod3(ref string use) { use = null; } } "); VerifyBasic(@" Imports System Public Class NeatCode ' Used parameter methods Public Sub UsedParameterMethod1(use As String) Console.WriteLine(Me) Console.WriteLine(use) End Sub Public Sub UsedParameterMethod2(use As String) UsedParameterMethod3(use) End Sub Public Sub UsedParameterMethod3(ByRef use As String) use = Nothing End Sub End Class "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticDelegateTest() { VerifyCSharp(@" using System; public class NeatCode { // Used parameter methods public void UsedParameterMethod1(Action a) { a(); } public void UsedParameterMethod2(Action a1, Action a2) { try { a1(); } catch(Exception) { a2(); } } } "); VerifyBasic(@" Imports System Public Class NeatCode ' Used parameter methods Public Sub UsedParameterMethod1(a As Action) a() End Sub Public Sub UsedParameterMethod2(a1 As Action, a2 As Action) Try a1() Catch generatedExceptionName As Exception a2() End Try End Sub End Class "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/8884")] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticDelegateTest2_CSharp() { VerifyCSharp(@" using System; public class NeatCode { // Used parameter methods public void UsedParameterMethod1(Action a) { Action a2 = new Action(() => { a(); }); } "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticDelegateTest2_VB() { VerifyBasic(@" Imports System Public Class NeatCode ' Used parameter methods Public Sub UsedParameterMethod1(a As Action) Dim a2 As New Action(Sub() a() End Sub) End Sub End Class "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/8884")] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticUsingTest_CSharp() { VerifyCSharp(@" using System; class C { void F(int x, IDisposable o) { using (o) { int y = x; } } } "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/8884")] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticUsingTest_VB() { VerifyBasic(@" Imports System Class C Private Sub F(x As Integer, o As IDisposable) Using o Dim y As Integer = x End Using End Sub End Class "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/8884")] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticLinqTest_CSharp() { VerifyCSharp(@" using System; using System.Linq; using System.Reflection; class C { private object F(Assembly assembly) { var type = (from t in assembly.GetTypes() select t.Attributes).FirstOrDefault(); return type; } } "); } [Fact(Skip = "https://github.com/dotnet/roslyn/issues/8884")] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticLinqTest_VB() { VerifyBasic(@" Imports System Imports System.Linq Imports System.Reflection Class C Private Function F(assembly As Assembly) As Object Dim type = (From t In assembly.DefinedTypes() Select t.Attributes).FirstOrDefault() Return type End Function End Class "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticSpecialCasesTest() { VerifyCSharp(@" using System; public abstract class Derived : Base, I { // Override public override void VirtualMethod(int param) { } // Abstract public abstract void AbstractMethod(int param); // Implicit interface implementation public void Method1(int param) { } // Explicit interface implementation void I.Method2(int param) { } // Event handlers public void MyEventHandler(object o, EventArgs e) { } public void MyEventHandler2(object o, MyEventArgs e) { } public class MyEventArgs : EventArgs { } } public class Base { // Virtual public virtual void VirtualMethod(int param) { } } public interface I { void Method1(int param); void Method2(int param); } "); VerifyBasic(@" Imports System Public MustInherit Class Derived Inherits Base Implements I ' Override Public Overrides Sub VirtualMethod(param As Integer) End Sub ' Abstract Public MustOverride Sub AbstractMethod(param As Integer) ' Explicit interface implementation - VB has no implicit interface implementation. Public Sub Method1(param As Integer) Implements I.Method1 End Sub ' Explicit interface implementation Private Sub I_Method2(param As Integer) Implements I.Method2 End Sub ' Event handlers Public Sub MyEventHandler(o As Object, e As EventArgs) End Sub Public Sub MyEventHandler2(o As Object, e As MyEventArgs) End Sub Public Class MyEventArgs Inherits EventArgs End Class End Class Public Class Base ' Virtual Public Overridable Sub VirtualMethod(param As Integer) End Sub End Class Public Interface I Sub Method1(param As Integer) Sub Method2(param As Integer) End Interface "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticForMethodsWithSpecialAttributesTest() { VerifyCSharp(@" #define CONDITION_1 using System; using System.Diagnostics; using System.Runtime.Serialization; public class ConditionalMethodsClass { [Conditional(""CONDITION_1"")] private static void ConditionalMethod(int a) { AnotherConditionalMethod(a); } [Conditional(""CONDITION_2"")] private static void AnotherConditionalMethod(int b) { Console.WriteLine(b); } } public class SerializableMethodsClass { [OnSerializing] private void OnSerializingCallback(StreamingContext context) { Console.WriteLine(this); } [OnSerialized] private void OnSerializedCallback(StreamingContext context) { Console.WriteLine(this); } [OnDeserializing] private void OnDeserializingCallback(StreamingContext context) { Console.WriteLine(this); } [OnDeserialized] private void OnDeserializedCallback(StreamingContext context) { Console.WriteLine(this); } } "); VerifyBasic(@" #Const CONDITION_1 = 5 Imports System Imports System.Diagnostics Imports System.Runtime.Serialization Public Class ConditionalMethodsClass <Conditional(""CONDITION_1"")> _ Private Shared Sub ConditionalMethod(a As Integer) AnotherConditionalMethod(a) End Sub <Conditional(""CONDITION_2"")> _ Private Shared Sub AnotherConditionalMethod(b As Integer) Console.WriteLine(b) End Sub End Class Public Class SerializableMethodsClass <OnSerializing> _ Private Sub OnSerializingCallback(context As StreamingContext) Console.WriteLine(Me) End Sub <OnSerialized> _ Private Sub OnSerializedCallback(context As StreamingContext) Console.WriteLine(Me) End Sub <OnDeserializing> _ Private Sub OnDeserializingCallback(context As StreamingContext) Console.WriteLine(Me) End Sub <OnDeserialized> _ Private Sub OnDeserializedCallback(context As StreamingContext) Console.WriteLine(Me) End Sub End Class "); } #endregion #region Unit tests for analyzer diagnostic(s) [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void DiagnosticForSimpleCasesTest() { VerifyCSharp(@" using System; class C { public C(int param) { } public void UnusedParamMethod(int param) { } public static void UnusedParamStaticMethod(int param1) { } public void UnusedDefaultParamMethod(int defaultParam = 1) { } public void UnusedParamsArrayParamMethod(params int[] paramsArr) { } public void MultipleUnusedParamsMethod(int param1, int param2) { } private void UnusedRefParamMethod(ref int param1) { } public void UnusedErrorTypeParamMethod(UndefinedType param1) // error CS0246: The type or namespace name 'UndefinedType' could not be found. { } } ", TestValidationMode.AllowCompileErrors, // Test0.cs(6,18): warning CA1801: Parameter param of method .ctor is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(6, 18, "param", ".ctor"), // Test0.cs(10,39): warning CA1801: Parameter param of method UnusedParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(10, 39, "param", "UnusedParamMethod"), // Test0.cs(14,52): warning CA1801: Parameter param1 of method UnusedParamStaticMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(14, 52, "param1", "UnusedParamStaticMethod"), // Test0.cs(18,46): warning CA1801: Parameter defaultParam of method UnusedDefaultParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(18, 46, "defaultParam", "UnusedDefaultParamMethod"), // Test0.cs(22,59): warning CA1801: Parameter paramsArr of method UnusedParamsArrayParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(22, 59, "paramsArr", "UnusedParamsArrayParamMethod"), // Test0.cs(26,48): warning CA1801: Parameter param1 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(26, 48, "param1", "MultipleUnusedParamsMethod"), // Test0.cs(26,60): warning CA1801: Parameter param2 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(26, 60, "param2", "MultipleUnusedParamsMethod"), // Test0.cs(30,47): warning CA1801: Parameter param1 of method UnusedRefParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(30, 47, "param1", "UnusedRefParamMethod"), // Test0.cs(34,58): warning CA1801: Parameter param1 of method UnusedErrorTypeParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(34, 58, "param1", "UnusedErrorTypeParamMethod")); VerifyBasic(@" Class C Public Sub New(param As Integer) End Sub Public Sub UnusedParamMethod(param As Integer) End Sub Public Shared Sub UnusedParamStaticMethod(param1 As Integer) End Sub Public Sub UnusedDefaultParamMethod(Optional defaultParam As Integer = 1) End Sub Public Sub UnusedParamsArrayParamMethod(ParamArray paramsArr As Integer()) End Sub Public Sub MultipleUnusedParamsMethod(param1 As Integer, param2 As Integer) End Sub Private Sub UnusedRefParamMethod(ByRef param1 As Integer) End Sub Public Sub UnusedErrorTypeParamMethod(param1 As UndefinedType) ' error BC30002: Type 'UndefinedType' is not defined. End Sub End Class ", TestValidationMode.AllowCompileErrors, // Test0.vb(3,20): warning CA1801: Parameter param of method .ctor is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(3, 20, "param", ".ctor"), // Test0.vb(6,34): warning CA1801: Parameter param of method UnusedParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(6, 34, "param", "UnusedParamMethod"), // Test0.vb(9,47): warning CA1801: Parameter param1 of method UnusedParamStaticMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(9, 47, "param1", "UnusedParamStaticMethod"), // Test0.vb(12,50): warning CA1801: Parameter defaultParam of method UnusedDefaultParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(12, 50, "defaultParam", "UnusedDefaultParamMethod"), // Test0.vb(15,56): warning CA1801: Parameter paramsArr of method UnusedParamsArrayParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(15, 56, "paramsArr", "UnusedParamsArrayParamMethod"), // Test0.vb(18,43): warning CA1801: Parameter param1 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(18, 43, "param1", "MultipleUnusedParamsMethod"), // Test0.vb(18,62): warning CA1801: Parameter param2 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(18, 62, "param2", "MultipleUnusedParamsMethod"), // Test0.vb(21,44): warning CA1801: Parameter param1 of method UnusedRefParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(21, 44, "param1", "UnusedRefParamMethod"), // Test0.vb(24,43): warning CA1801: Parameter param1 of method UnusedErrorTypeParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(24, 43, "param1", "UnusedErrorTypeParamMethod")); } #endregion #region Helpers protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new ReviewUnusedParametersAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new ReviewUnusedParametersAnalyzer(); } private static DiagnosticResult GetCSharpUnusedParameterResultAt(int line, int column, string parameterName, string methodName) { string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.ReviewUnusedParametersMessage, parameterName, methodName); return GetCSharpResultAt(line, column, ReviewUnusedParametersAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicUnusedParameterResultAt(int line, int column, string parameterName, string methodName) { string message = string.Format(MicrosoftMaintainabilityAnalyzersResources.ReviewUnusedParametersMessage, parameterName, methodName); return GetBasicResultAt(line, column, ReviewUnusedParametersAnalyzer.RuleId, message); } #endregion } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion License using System.Collections.Generic; using System.Linq.Expressions; using Irony.Ast; using Irony.Parsing; namespace Irony.Interpreter.Ast { public static class CustomExpressionTypes { public const ExpressionType NotAnExpression = (ExpressionType) (-1); } /// <summary> /// Base AST node class /// </summary> public partial class AstNode : IAstNodeInit, IBrowsableAstNode, IVisitableNode { /// <summary> /// List of child nodes /// </summary> public readonly AstNodeList ChildNodes = new AstNodeList(); /// <summary> /// Used for pointing to error location. For most nodes it would be the location of the node itself. /// One exception is BinExprNode: when we get "Division by zero" error evaluating /// x = (5 + 3) / (2 - 2) /// it is better to point to "/" as error location, rather than the first "(" - which is the start /// location of binary expression. /// </summary> public SourceLocation ErrorAnchor; /// <summary> /// Reference to Evaluate method implementation. Initially set to DoEvaluate virtual method. /// </summary> public EvaluateMethod Evaluate; public AstNodeFlags Flags; public AstNode Parent; /// <summary> /// Role is a free-form string used as prefix in ToString() representation of the node. /// Node's parent can set it to "property name" or role of the child node in parent's node currentFrame.Context. /// </summary> public string Role; public ValueSetterMethod SetValue; public BnfTerm Term; /// <summary> /// UseType is set by parent /// </summary> public NodeUseType UseType = NodeUseType.Unknown; protected ExpressionType ExpressionType = CustomExpressionTypes.NotAnExpression; protected object LockObject = new object(); /// <summary> /// ModuleNode - computed on demand /// </summary> private AstNode moduleNode; /// <summary> /// Public default constructor /// </summary> public AstNode() { this.Evaluate = DoEvaluate; this.SetValue = DoSetValue; } /// <summary> /// Default AstNode.ToString() returns 'Role: AsString', which is used for showing node in AST tree. /// </summary> public virtual string AsString { get; protected set; } public SourceLocation Location { get { return Span.Location; } } /// <summary> /// ModuleNode - computed on demand /// </summary> public AstNode ModuleNode { get { if (this.moduleNode == null) { this.moduleNode = (this.Parent == null) ? this : this.Parent.ModuleNode; } return this.moduleNode; } set { this.moduleNode = value; } } public SourceSpan Span { get; set; } #region IAstNodeInit Members public virtual void Init(AstContext context, ParseTreeNode treeNode) { this.Term = treeNode.Term; this.Span = treeNode.Span; this.ErrorAnchor = this.Location; treeNode.AstNode = this; this.AsString = (this.Term == null ? this.GetType().Name : this.Term.Name); } #endregion IAstNodeInit Members #region virtual methods: DoEvaluate, SetValue, IsConstant, SetIsTail, GetDependentScopeInfo private ScopeInfo dependentScope; /// <summary> /// Dependent scope is a scope produced by the node. For ex, FunctionDefNode defines a scope /// </summary> public virtual ScopeInfo DependentScopeInfo { get { return this.dependentScope; } set { this.dependentScope = value; } } public virtual void DoSetValue(ScriptThread thread, object value) { // Place the prolog/epilog lines in every implementation of SetValue method (see DoEvaluate above) } public virtual bool IsConstant() { return false; } public virtual void Reset() { this.moduleNode = null; this.Evaluate = this.DoEvaluate; foreach (var child in this.ChildNodes) { child.Reset(); } } /// <summary> /// Sets a flag indicating that the node is in tail position. The value is propagated from parent to children. /// Should propagate this call to appropriate children. /// </summary> public virtual void SetIsTail() { this.Flags |= AstNodeFlags.IsTail; } /// <summary> /// By default the Evaluate field points to this method. /// </summary> /// <param name="thread"></param> /// <returns></returns> protected virtual object DoEvaluate(ScriptThread thread) { // These 2 lines are standard prolog/epilog statements. // Place them in every Evaluate and SetValue implementations. // Standard prolog thread.CurrentNode = this; // tandard epilog thread.CurrentNode = this.Parent; return null; } #endregion virtual methods: DoEvaluate, SetValue, IsConstant, SetIsTail, GetDependentScopeInfo #region IBrowsableAstNode Members public int Position { get { return this.Span.Location.Position; } } public virtual System.Collections.IEnumerable GetChildNodes() { return this.ChildNodes; } #endregion IBrowsableAstNode Members #region Visitors, Iterators /// <summary> /// The first primitive Visitor facility /// </summary> /// <param name="visitor"></param> public virtual void AcceptVisitor(IAstVisitor visitor) { visitor.BeginVisit(this); if (this.ChildNodes.Count > 0) { foreach (AstNode node in this.ChildNodes) { node.AcceptVisitor(visitor); } } visitor.EndVisit(this); } public IEnumerable<AstNode> GetAll() { var result = new AstNodeList(); this.AddAll(result); return result; } private void AddAll(AstNodeList list) { list.Add(this); foreach (AstNode child in this.ChildNodes) { if (child != null) child.AddAll(list); } } #endregion Visitors, Iterators #region overrides: ToString public override string ToString() { return string.IsNullOrEmpty(Role) ? this.AsString : this.Role + ": " + this.AsString; } #endregion overrides: ToString #region Utility methods: AddChild, HandleError protected AstNode AddChild(string role, ParseTreeNode childParseNode) { return AddChild(NodeUseType.Unknown, role, childParseNode); } protected AstNode AddChild(NodeUseType useType, string role, ParseTreeNode childParseNode) { var child = (AstNode) childParseNode.AstNode; if (child == null) // Put a stub to throw an exception with clear message on attempt to evaluate. child = new NullNode(childParseNode.Term); child.Role = role; child.Parent = this; this.ChildNodes.Add(child); return child; } #endregion Utility methods: AddChild, HandleError } public class AstNodeList : List<AstNode> { } }
namespace BitmapResizer { partial class MainWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWindow)); this.statusStrip1 = new System.Windows.Forms.StatusStrip(); this.filenameLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.widthLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.heightLabel = new System.Windows.Forms.ToolStripStatusLabel(); this.menuBar = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.openToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.exitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ofDialog = new System.Windows.Forms.OpenFileDialog(); this.saveDialog = new System.Windows.Forms.SaveFileDialog(); this.picBox = new System.Windows.Forms.PictureBox(); this.resizeQualityComboBox = new System.Windows.Forms.ComboBox(); this.saveButton = new System.Windows.Forms.Button(); this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.label1 = new System.Windows.Forms.Label(); this.widthSpinner = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.heightSpinner = new System.Windows.Forms.NumericUpDown(); this.bw = new System.ComponentModel.BackgroundWorker(); this.progressBar = new BitmapResizer.IndeterminateProgressBar(this.components); this.statusStrip1.SuspendLayout(); this.menuBar.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.picBox)).BeginInit(); this.tableLayoutPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.widthSpinner)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.heightSpinner)).BeginInit(); this.SuspendLayout(); // // statusStrip1 // this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.filenameLabel, this.widthLabel, this.heightLabel}); this.statusStrip1.Location = new System.Drawing.Point(0, 226); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new System.Drawing.Size(522, 22); this.statusStrip1.TabIndex = 0; this.statusStrip1.Text = "statusStrip1"; // // filenameLabel // this.filenameLabel.Name = "filenameLabel"; this.filenameLabel.Size = new System.Drawing.Size(287, 17); this.filenameLabel.Spring = true; this.filenameLabel.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // widthLabel // this.widthLabel.AutoSize = false; this.widthLabel.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; this.widthLabel.BorderStyle = System.Windows.Forms.Border3DStyle.Etched; this.widthLabel.Name = "widthLabel"; this.widthLabel.Size = new System.Drawing.Size(110, 17); // // heightLabel // this.heightLabel.AutoSize = false; this.heightLabel.BorderSides = System.Windows.Forms.ToolStripStatusLabelBorderSides.Left; this.heightLabel.BorderStyle = System.Windows.Forms.Border3DStyle.Etched; this.heightLabel.Name = "heightLabel"; this.heightLabel.Size = new System.Drawing.Size(110, 17); // // menuBar // this.menuBar.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.helpToolStripMenuItem}); this.menuBar.Location = new System.Drawing.Point(0, 0); this.menuBar.Name = "menuBar"; this.menuBar.Size = new System.Drawing.Size(522, 24); this.menuBar.TabIndex = 1; this.menuBar.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.openToolStripMenuItem, this.exitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20); this.fileToolStripMenuItem.Text = "&File"; // // openToolStripMenuItem // this.openToolStripMenuItem.Image = global::BitmapResizer.Properties.Resources.openHS; this.openToolStripMenuItem.Name = "openToolStripMenuItem"; this.openToolStripMenuItem.Size = new System.Drawing.Size(111, 22); this.openToolStripMenuItem.Text = "&Open"; this.openToolStripMenuItem.Click += new System.EventHandler(this.openToolStripMenuItem_Click); // // exitToolStripMenuItem // this.exitToolStripMenuItem.Name = "exitToolStripMenuItem"; this.exitToolStripMenuItem.Size = new System.Drawing.Size(111, 22); this.exitToolStripMenuItem.Text = "E&xit"; this.exitToolStripMenuItem.Click += new System.EventHandler(this.exitToolStripMenuItem_Click); // // helpToolStripMenuItem // this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.aboutToolStripMenuItem}); this.helpToolStripMenuItem.Name = "helpToolStripMenuItem"; this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20); this.helpToolStripMenuItem.Text = "&Help"; // // aboutToolStripMenuItem // this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem"; this.aboutToolStripMenuItem.Size = new System.Drawing.Size(114, 22); this.aboutToolStripMenuItem.Text = "&About"; this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click); // // ofDialog // this.ofDialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.JPEG;*.GIF;*.png|All files (*.*)|*.*" + ""; this.ofDialog.Title = "Select Image"; // // saveDialog // this.saveDialog.Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.JPEG;*.GIF;*.png|All files (*.*)|*.*" + ""; this.saveDialog.Title = "Save Resized Image"; // // picBox // this.picBox.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.picBox.Location = new System.Drawing.Point(13, 28); this.picBox.Name = "picBox"; this.picBox.Size = new System.Drawing.Size(192, 192); this.picBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.picBox.TabIndex = 2; this.picBox.TabStop = false; // // resizeQualityComboBox // this.resizeQualityComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.resizeQualityComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.resizeQualityComboBox.FormattingEnabled = true; this.resizeQualityComboBox.Location = new System.Drawing.Point(212, 88); this.resizeQualityComboBox.Name = "resizeQualityComboBox"; this.resizeQualityComboBox.Size = new System.Drawing.Size(299, 21); this.resizeQualityComboBox.TabIndex = 3; // // saveButton // this.saveButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.saveButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.saveButton.Image = global::BitmapResizer.Properties.Resources.FormRunHS; this.saveButton.ImageAlign = System.Drawing.ContentAlignment.TopCenter; this.saveButton.Location = new System.Drawing.Point(435, 115); this.saveButton.Name = "saveButton"; this.saveButton.Size = new System.Drawing.Size(75, 45); this.saveButton.TabIndex = 4; this.saveButton.Text = "Process"; this.saveButton.TextAlign = System.Drawing.ContentAlignment.BottomCenter; this.saveButton.UseVisualStyleBackColor = true; this.saveButton.Click += new System.EventHandler(this.saveButton_Click); // // tableLayoutPanel1 // this.tableLayoutPanel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tableLayoutPanel1.ColumnCount = 2; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Absolute, 105F)); this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.tableLayoutPanel1.Controls.Add(this.label1, 0, 0); this.tableLayoutPanel1.Controls.Add(this.widthSpinner, 1, 0); this.tableLayoutPanel1.Controls.Add(this.label2, 0, 1); this.tableLayoutPanel1.Controls.Add(this.heightSpinner, 1, 1); this.tableLayoutPanel1.Location = new System.Drawing.Point(212, 28); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 25F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(217, 54); this.tableLayoutPanel1.TabIndex = 5; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(3, 0); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(99, 25); this.label1.TabIndex = 0; this.label1.Text = "Maximum Width"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // widthSpinner // this.widthSpinner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.widthSpinner.Location = new System.Drawing.Point(108, 3); this.widthSpinner.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); this.widthSpinner.Maximum = new decimal(new int[] { 32768, 0, 0, 0}); this.widthSpinner.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.widthSpinner.Name = "widthSpinner"; this.widthSpinner.Size = new System.Drawing.Size(109, 20); this.widthSpinner.TabIndex = 2; this.widthSpinner.Value = new decimal(new int[] { 640, 0, 0, 0}); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(3, 25); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(99, 29); this.label2.TabIndex = 3; this.label2.Text = "Maximum Height"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // heightSpinner // this.heightSpinner.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.heightSpinner.Location = new System.Drawing.Point(108, 28); this.heightSpinner.Margin = new System.Windows.Forms.Padding(3, 3, 0, 3); this.heightSpinner.Maximum = new decimal(new int[] { 32768, 0, 0, 0}); this.heightSpinner.Minimum = new decimal(new int[] { 1, 0, 0, 0}); this.heightSpinner.Name = "heightSpinner"; this.heightSpinner.Size = new System.Drawing.Size(109, 20); this.heightSpinner.TabIndex = 4; this.heightSpinner.Value = new decimal(new int[] { 480, 0, 0, 0}); // // bw // this.bw.WorkerReportsProgress = true; // // progressBar // this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.BorderDark = System.Drawing.Color.Black; this.progressBar.BorderLight = System.Drawing.Color.White; this.progressBar.ColorFrom = System.Drawing.Color.LimeGreen; this.progressBar.ColorTo = System.Drawing.Color.FromArgb(((int)(((byte)(5)))), ((int)(((byte)(149)))), ((int)(((byte)(20))))); this.progressBar.Location = new System.Drawing.Point(212, 115); this.progressBar.Name = "progressBar"; this.progressBar.Pips = 10; this.progressBar.Size = new System.Drawing.Size(217, 20); this.progressBar.TabIndex = 6; // // MainWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(522, 248); this.Controls.Add(this.progressBar); this.Controls.Add(this.tableLayoutPanel1); this.Controls.Add(this.saveButton); this.Controls.Add(this.resizeQualityComboBox); this.Controls.Add(this.picBox); this.Controls.Add(this.statusStrip1); this.Controls.Add(this.menuBar); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuBar; this.MaximumSize = new System.Drawing.Size(32768, 275); this.MinimumSize = new System.Drawing.Size(530, 275); this.Name = "MainWindow"; this.Text = "Bitmap Resizer"; this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.menuBar.ResumeLayout(false); this.menuBar.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.picBox)).EndInit(); this.tableLayoutPanel1.ResumeLayout(false); this.tableLayoutPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.widthSpinner)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.heightSpinner)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.StatusStrip statusStrip1; private System.Windows.Forms.MenuStrip menuBar; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem openToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem exitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem helpToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem aboutToolStripMenuItem; private System.Windows.Forms.OpenFileDialog ofDialog; private System.Windows.Forms.SaveFileDialog saveDialog; private System.Windows.Forms.PictureBox picBox; private System.Windows.Forms.ComboBox resizeQualityComboBox; private System.Windows.Forms.Button saveButton; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1; private System.Windows.Forms.Label label1; private System.Windows.Forms.NumericUpDown widthSpinner; private System.Windows.Forms.Label label2; private System.Windows.Forms.NumericUpDown heightSpinner; private System.Windows.Forms.ToolStripStatusLabel filenameLabel; private System.Windows.Forms.ToolStripStatusLabel widthLabel; private System.Windows.Forms.ToolStripStatusLabel heightLabel; private System.ComponentModel.BackgroundWorker bw; private IndeterminateProgressBar progressBar; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.TeamFoundation.Client; using Microsoft.TeamFoundation.WorkItemTracking.Client; using Microsoft.TeamFoundation.Server; using System.Net; using Microsoft.TeamFoundation.ProcessConfiguration.Client; using System.Linq; using System.Xml; namespace AreaImportExportTool { public partial class MainForm : Form { public MainForm() { InitializeComponent(); chkIterationStructure_CheckedChanged(this, EventArgs.Empty); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); } private void chkIterationStructure_CheckedChanged(object sender, EventArgs e) { cmdExport.Enabled = cmdImport.Enabled = (chkAreaStructure.Checked || chkIterationStructure.Checked) && (!(String.IsNullOrEmpty(txtCollectionUri.Text) || txtCollectionUri.Text.Trim().Length == 0) || !Uri.IsWellFormedUriString(txtCollectionUri.Text, UriKind.Absolute)) && (!(String.IsNullOrEmpty(txtTeamProject.Text) || txtTeamProject.Text.Trim().Length == 0)); } private void cmdExport_Click(object sender, EventArgs e) { Uri collectionUri = new Uri(txtCollectionUri.Text); string teamProject = txtTeamProject.Text; SaveFileDialog dlg = new SaveFileDialog(); dlg.CheckPathExists = true; dlg.Title = "Export Area/Iteration structure"; dlg.DefaultExt = ".nodes"; dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes"; if (dlg.ShowDialog(this) == DialogResult.OK) { string filename = dlg.FileName; var networkCredential = new NetworkCredential("username", "password"); var basicAuthCredential = new BasicAuthCredential(networkCredential); var tfsCredential = new TfsClientCredentials(basicAuthCredential); using(var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential)) //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri)) using (WaitState waitState = new WaitState(this)) { tfs.Authenticate(); tfs.EnsureAuthenticated(); // get the configuration server var svr = tfs.ConfigurationServer; // get the configuration service var svc = tfs.GetService<TeamSettingsConfigurationService>(); // get the common structure service var css = tfs.GetService<ICommonStructureService4>(); // get the spotlabs project var prj = css.GetProjectFromName(txtTeamProject.Text); // get the configurations var cfg = svc.GetTeamConfigurationsForUser(new[] { prj.Uri }).Single<TeamConfiguration>(); // get the settings var opt = cfg.TeamSettings; // get the iteration schedule var schedule = css.GetIterationDates(prj.Uri); Console.WriteLine(opt.ToString()); var store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); var proj = store.Projects[teamProject]; using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write)) using (StreamWriter writer = new StreamWriter(fs)) { writer.WriteLine("NODES"); writer.WriteLine(String.Format("{0}, Version {1}", Application.ProductName, Application.ProductVersion)); writer.WriteLine("Copyright (C) 2010 " + Application.CompanyName); if (chkAreaStructure.Checked) { WriteNodes(proj.AreaRootNodes, writer, "A"); } if (chkIterationStructure.Checked) { WriteNodes(proj.IterationRootNodes, writer, "I"); } writer.Close(); } } MessageBox.Show("Export successful."); } } private static void WriteNodes(NodeCollection nodes, StreamWriter writer, string prefix) { foreach (Node node in nodes) { writer.Write(prefix); writer.WriteLine(node.Path.Substring(node.Path.IndexOf(@"\"))); if (node.ChildNodes.Count > 0) { WriteNodes(node.ChildNodes, writer, prefix); } } } private void cmdImport_Click(object sender, EventArgs e) { Uri collectionUri = new Uri(txtCollectionUri.Text); string teamProject = txtTeamProject.Text; OpenFileDialog dlg = new OpenFileDialog(); dlg.CheckFileExists = true; dlg.Title = "Import Area/Iteration structure"; dlg.DefaultExt = ".nodes"; dlg.Filter = "TFS Node Structure (*.nodes)|*.nodes"; if (dlg.ShowDialog(this) == DialogResult.OK) { string filename = dlg.FileName; var networkCredential = new NetworkCredential("username", "password"); var basicAuthCredential = new BasicAuthCredential(networkCredential); var tfsCredential = new TfsClientCredentials(basicAuthCredential); using (var tfs = new TfsTeamProjectCollection(collectionUri, tfsCredential)) //using (var tfs = TfsTeamProjectCollectionFactory.GetTeamProjectCollection(collectionUri, new UICredentialsProvider())) using (WaitState waitState = new WaitState(this)) { tfs.Authenticate(); tfs.EnsureAuthenticated(); WorkItemStore store = (WorkItemStore)tfs.GetService(typeof(WorkItemStore)); Project proj = store.Projects[teamProject]; NodeInfo rootAreaNode = null; NodeInfo rootIterationNode = null; var css = (ICommonStructureService4)tfs.GetService(typeof(ICommonStructureService4)); foreach (NodeInfo info in css.ListStructures(proj.Uri.ToString())) { if (info.StructureType == "ProjectModelHierarchy") { rootAreaNode = info; } else if (info.StructureType == "ProjectLifecycle") { rootIterationNode = info; } } using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read)) using (StreamReader reader = new StreamReader(fs)) { string nextLine = reader.ReadLine(); if (nextLine != "NODES") { MessageBox.Show("Wrong file format!"); return; } reader.ReadLine(); reader.ReadLine(); while (!reader.EndOfStream) { nextLine = reader.ReadLine(); if (nextLine.StartsWith("A") && chkAreaStructure.Checked) { CreateNode(css, nextLine.Substring(2), rootAreaNode); } else if (nextLine.StartsWith("I") && chkIterationStructure.Checked) { CreateNode(css, nextLine.Substring(2), rootIterationNode); } else { // Ignore other lines } } reader.Close(); } MessageBox.Show("Import successful."); } } } private void CreateNode(ICommonStructureService4 css, string nodeName, NodeInfo rootNode) { char _delimeter = '|'; var name = String.Empty; DateTime? startDate = null; DateTime? endDate = null; if (nodeName.Contains(_delimeter)) { var parts = nodeName.Split(_delimeter); name = parts[0]; startDate = DateTime.Parse(parts[1]); endDate = DateTime.Parse(parts[2]); } else { name = nodeName; } if (!name.Contains("\\")) { try { var iterationUri = css.CreateNode(name, rootNode.Uri); css.SetIterationDates(iterationUri, startDate, endDate); } catch(Exception ex) when (ex.ToString().Contains("TF200020")) { Console.WriteLine("Node Exists. Skipping..."); } } else { int lastBackslash = name.LastIndexOf("\\"); NodeInfo info = css.GetNodeFromPath(rootNode.Path + "\\" + name.Substring(0, lastBackslash)); var iterationUri = css.CreateNode(name.Substring(lastBackslash + 1), info.Uri); css.SetIterationDates(iterationUri, startDate, endDate); } } private void cmdClose_Click(object sender, EventArgs e) { this.Close(); } private class WaitState : IDisposable { private Form parent; public WaitState(Form parent) { parent.Cursor = Cursors.WaitCursor; parent.Enabled = false; this.parent = parent; } void IDisposable.Dispose() { parent.Cursor = Cursors.Default; parent.Enabled = true; } } } }