context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Collections.Immutable; using Microsoft.CodeAnalysis; namespace Microsoft.DotNet.CodeFormatting.Rules { [SyntaxRule(SyntaxRuleOrder.CopyrightHeaderRule)] internal sealed partial class CopyrightHeaderRule : SyntaxFormattingRule, ISyntaxFormattingRule { private abstract class CommonRule { /// <summary> /// This is the normalized copyright header that has no comment delimiters. /// </summary> private readonly ImmutableArray<string> _header; protected CommonRule(ImmutableArray<string> header) { _header = header; } internal SyntaxNode Process(SyntaxNode syntaxNode) { if (_header.IsDefaultOrEmpty) { return syntaxNode; } if (HasCopyrightHeader(syntaxNode)) return syntaxNode; return AddCopyrightHeader(syntaxNode); } private bool HasCopyrightHeader(SyntaxNode syntaxNode) { var existingHeader = GetExistingHeader(syntaxNode.GetLeadingTrivia()); return SequnceStartsWith(_header, existingHeader); } private bool SequnceStartsWith(ImmutableArray<string> header, List<string> existingHeader) { // Only try if the existing header is at least as long as the new copyright header if (existingHeader.Count >= header.Count()) { return !header.Where((headerLine, i) => existingHeader[i] != headerLine).Any(); } return false; } private SyntaxNode AddCopyrightHeader(SyntaxNode syntaxNode) { var list = new List<SyntaxTrivia>(); foreach (var headerLine in _header) { list.Add(CreateLineComment(headerLine)); list.Add(CreateNewLine()); } list.Add(CreateNewLine()); var triviaList = RemoveExistingHeader(syntaxNode.GetLeadingTrivia()); var i = 0; MovePastBlankLines(triviaList, ref i); while (i < triviaList.Count) { list.Add(triviaList[i]); i++; } return syntaxNode.WithLeadingTrivia(CreateTriviaList(list)); } private List<string> GetExistingHeader(SyntaxTriviaList triviaList) { var i = 0; MovePastBlankLines(triviaList, ref i); var headerList = new List<string>(); while (i < triviaList.Count && IsLineComment(triviaList[i])) { headerList.Add(GetCommentText(triviaList[i].ToFullString())); i++; MoveToNextLineOrTrivia(triviaList, ref i); } return headerList; } /// <summary> /// Remove any copyright header that already exists. /// </summary> private SyntaxTriviaList RemoveExistingHeader(SyntaxTriviaList oldList) { var foundHeader = false; var i = 0; MovePastBlankLines(oldList, ref i); while (i < oldList.Count && IsLineComment(oldList[i])) { if (oldList[i].ToFullString().IndexOf("copyright", StringComparison.OrdinalIgnoreCase) >= 0) { foundHeader = true; } i++; } if (!foundHeader) { return oldList; } MovePastBlankLines(oldList, ref i); return CreateTriviaList(oldList.Skip(i)); } private void MovePastBlankLines(SyntaxTriviaList list, ref int index) { while (index < list.Count && (IsWhitespace(list[index]) || IsNewLine(list[index]))) { index++; } } private void MoveToNextLineOrTrivia(SyntaxTriviaList list, ref int index) { MovePastWhitespaces(list, ref index); if (index < list.Count && IsNewLine(list[index])) { index++; } } private void MovePastWhitespaces(SyntaxTriviaList list, ref int index) { while (index < list.Count && IsWhitespace(list[index])) { index++; } } protected abstract SyntaxTriviaList CreateTriviaList(IEnumerable<SyntaxTrivia> e); protected abstract bool IsLineComment(SyntaxTrivia trivia); protected abstract bool IsWhitespace(SyntaxTrivia trivia); protected abstract bool IsNewLine(SyntaxTrivia trivia); protected abstract SyntaxTrivia CreateLineComment(string commentText); protected abstract SyntaxTrivia CreateNewLine(); } private readonly Options _options; private ImmutableArray<string> _cachedHeader; private ImmutableArray<string> _cachedHeaderSource; [ImportingConstructor] internal CopyrightHeaderRule(Options options) { _options = options; } private ImmutableArray<string> GetHeader() { if (_cachedHeaderSource != _options.CopyrightHeader) { _cachedHeaderSource = _options.CopyrightHeader; _cachedHeader = _options.CopyrightHeader.Select(GetCommentText).ToImmutableArray(); } return _cachedHeader; } private static string GetCommentText(string line) { if (line.StartsWith("'")) { return line.Substring(1).TrimStart(); } if (line.StartsWith("//")) { return line.Substring(2).TrimStart(); } return line; } public override bool SupportsLanguage(string languageName) { return languageName == LanguageNames.CSharp || languageName == LanguageNames.VisualBasic; } public override SyntaxNode ProcessCSharp(SyntaxNode syntaxNode) { return (new CSharpRule(GetHeader())).Process(syntaxNode); } public override SyntaxNode ProcessVisualBasic(SyntaxNode syntaxNode) { return (new VisualBasicRule(GetHeader())).Process(syntaxNode); } } }
// Copyright (C) 2009-2015 Luca Piccioni // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; namespace OpenGL.Objects { public class Query : GraphicsResource { #region Constructors /// <summary> /// Construct a QueryObject specify its target. /// </summary> /// <param name="target"></param> public Query(QueryTarget target) { mTarget = target; } #endregion #region Query Method public QueryTarget Target { get { return (mTarget); } } public void Begin(GraphicsContext ctx) { Gl.BeginQuery(mTarget, ObjectName); } public void End(GraphicsContext ctx) { Gl.EndQuery(mTarget); } public bool IsAvailable(GraphicsContext ctx) { int availability = 0; Gl.GetQueryObject(ObjectName, QueryObjectParameterName.QueryResultAvailable , out availability); return (availability != 0); } public void GetResult(GraphicsContext ctx, out int result) { if (ctx == null) throw new ArgumentNullException("ctx"); Gl.GetQueryObject(ObjectName, QueryObjectParameterName.QueryResult, out result); } public void GetResult(GraphicsContext ctx, out uint result) { if (ctx == null) throw new ArgumentNullException("ctx"); Gl.GetQueryObject(ObjectName, QueryObjectParameterName.QueryResult, out result); } public void GetResult(GraphicsContext ctx, out long result) { if (ctx == null) throw new ArgumentNullException("ctx"); if (ctx.Extensions.TimerQuery_ARB) { Gl.GetQueryObject(ObjectName, QueryObjectParameterName.QueryResult, out result); } else { int intResult; GetResult(ctx, out intResult); result = intResult; } } public void GetResult(GraphicsContext ctx, out ulong result) { if (ctx == null) throw new ArgumentNullException("ctx"); if (ctx.Extensions.TimerQuery_ARB) { Gl.GetQueryObject(ObjectName, QueryObjectParameterName.QueryResult, out result); } else { uint uintResult; GetResult(ctx, out uintResult); result = uintResult; } } private readonly QueryTarget mTarget; #endregion #region GraphicsResource Overrides /// <summary> /// Buffer object class. /// </summary> internal static readonly Guid ThisObjectClass = new Guid("E36CF107-AEC3-47B5-AC4E-184CDEC29053"); /// <summary> /// Buffer object class. /// </summary> public override Guid ObjectClass { get { return (ThisObjectClass); } } /// <summary> /// Determine whether this BufferObject really exists for a specific context. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> that would have created (or a sharing one) the object. This context shall be current to /// the calling thread. /// </param> /// <returns> /// It returns a boolean value indicating whether this BufferObject exists in the object space of <paramref name="ctx"/>. /// </returns> /// <remarks> /// <para> /// The object existence is done by checking a valid object by its name <see cref="IGraphicsResource.ObjectName"/>. This routine will test whether /// <paramref name="ctx"/> has created this BufferObject (or is sharing with the creator). /// </para> /// </remarks> /// <exception cref="ArgumentNullException"> /// Exception thrown if <paramref name="ctx"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// Exception thrown if <paramref name="ctx"/> is not current to the calling thread. /// </exception> public override bool Exists(GraphicsContext ctx) { if (ctx == null) throw new ArgumentNullException("ctx"); if (ctx.IsCurrent == false) throw new ArgumentException("not current", "ctx"); // Object name space test (and 'ctx' sanity checks) if (base.Exists(ctx) == false) return (false); return (Gl.IsQuery(ObjectName)); } /// <summary> /// Create a BufferObject name. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for creating this buffer object name. /// </param> /// <returns> /// It returns a valid object name for this BufferObject. /// </returns> protected override uint CreateName(GraphicsContext ctx) { switch (mTarget) { #if !MONODROID case QueryTarget.SamplesPassed: if (!ctx.Extensions.OcclusionQuery_ARB) throw new InvalidOperationException("occlusion query not available"); break; #endif case QueryTarget.TimeElapsed: if (!ctx.Extensions.TimerQuery_ARB) throw new InvalidOperationException("timer query not available"); break; case QueryTarget.PrimitivesGenerated: case QueryTarget.TransformFeedbackPrimitivesWritten: if (!ctx.Extensions.TransformFeedback_EXT && !Gl.CurrentExtensions.TransformFeedback_NV) throw new InvalidOperationException("timer query not available"); break; case QueryTarget.AnySamplesPassed: if (!ctx.Extensions.OcclusionQuery2_ARB) throw new InvalidOperationException("(any) occlusion query not available"); break; default: throw new InvalidOperationException(String.Format("unknown query target {0}", mTarget)); } // Create buffer object; return (Gl.GenQuery()); } /// <summary> /// Delete a BufferObject name. /// </summary> /// <param name="ctx"> /// A <see cref="GraphicsContext"/> used for deleting this buffer object name. /// </param> /// <param name="name"> /// A <see cref="UInt32"/> that specify the object name to delete. /// </param> protected override void DeleteName(GraphicsContext ctx, uint name) { // Delete buffer object Gl.DeleteQueries(name); } #endregion } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; using IdentityServer.UnitTests.Common; using IdentityServer4; using IdentityServer4.Models; using static IdentityServer4.IdentityServerConstants; namespace IdentityServer.UnitTests.Validation.Setup { internal static class ClientValidationTestClients { public static List<Client> Get() { return new List<Client> { new Client { ClientName = "Disabled client", ClientId = "disabled_client", Enabled = false, ClientSecrets = new List<Secret> { new Secret("secret") } }, new Client { ClientName = "Client with no secret set", ClientId = "no_secret_client", Enabled = true }, new Client { ClientName = "Client with null secret set", ClientId = "null_secret_client", Enabled = true, ClientSecrets = { new Secret(null) } }, new Client { ClientName = "Client with single secret, no protection, no expiration", ClientId = "single_secret_no_protection_no_expiration", Enabled = true, ClientSecrets = new List<Secret> { new Secret("secret") } }, new Client { ClientName = "Client with X509 Certificate", ClientId = "certificate_valid", Enabled = true, ClientSecrets = new List<Secret> { new Secret { Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint, Value = TestCert.Load().Thumbprint } } }, new Client { ClientName = "Client with X509 Certificate", ClientId = "certificate_invalid", Enabled = true, ClientSecrets = new List<Secret> { new Secret { Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint, Value = "invalid" } } }, new Client { ClientName = "Client with Base64 encoded X509 Certificate", ClientId = "certificate_base64_valid", Enabled = true, ClientSecrets = new List<Secret> { new Secret { Type = IdentityServerConstants.SecretTypes.X509CertificateBase64, Value = Convert.ToBase64String(TestCert.Load().Export(X509ContentType.Cert)) } } }, new Client { ClientName = "Client with Base64 encoded X509 Certificate", ClientId = "certificate_base64_invalid", Enabled = true, ClientSecrets = new List<Secret> { new Secret { Type = IdentityServerConstants.SecretTypes.X509CertificateBase64, Value = "invalid" } } }, new Client { ClientName = "Client with single secret, hashed, no expiration", ClientId = "single_secret_hashed_no_expiration", Enabled = true, ClientSecrets = new List<Secret> { // secret new Secret("secret".Sha256()) } }, new Client { ClientName = "Client with multiple secrets, no protection", ClientId = "multiple_secrets_no_protection", Enabled = true, ClientSecrets = new List<Secret> { new Secret("secret"), new Secret("foobar", "some description"), new Secret("quux"), new Secret("notexpired", DateTime.UtcNow.AddDays(1)), new Secret("expired", DateTime.UtcNow.AddDays(-1)) } }, new Client { ClientName = "Client with multiple secrets, hashed", ClientId = "multiple_secrets_hashed", Enabled = true, ClientSecrets = new List<Secret> { // secret new Secret("secret".Sha256()), // foobar new Secret("foobar".Sha256(), "some description"), // quux new Secret("quux".Sha512()), // notexpired new Secret("notexpired".Sha256(), DateTime.UtcNow.AddDays(1)), // expired new Secret("expired".Sha512(), DateTime.UtcNow.AddDays(-1)) }, }, new Client { ClientName = "MTLS Client with invalid secrets", ClientId = "mtls_client_invalid", Enabled = true, ClientSecrets = new List<Secret> { new Secret(@"CN=invalid", "mtls.test") { Type = SecretTypes.X509CertificateName }, new Secret("invalid", "mtls.test") { Type = SecretTypes.X509CertificateThumbprint }, } }, new Client { ClientName = "MTLS Client with valid secrets", ClientId = "mtls_client_valid", Enabled = true, ClientSecrets = new List<Secret> { new Secret(@"CN=identityserver_testing", "mtls.test") { Type = SecretTypes.X509CertificateName }, new Secret("4B5FE072C7AD8A9B5DCFDD1A20608BB54DE0954F", "mtls.test") { Type = SecretTypes.X509CertificateThumbprint }, } } }; } } }
using Microsoft.AspNetCore.Identity; using Raven.Client.Documents; using Raven.Client.Documents.Operations; using Raven.Client.Documents.Operations.CompareExchange; using Raven.Client.Documents.Session; using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Raven.Client.Documents.Operations.Backups; using System.Diagnostics; using Newtonsoft.Json.Converters; namespace Raven.Identity { /// <summary> /// UserStore for entities in a RavenDB database. /// </summary> /// <typeparam name="TUser"></typeparam> /// <typeparam name="TRole"></typeparam> public class UserStore<TUser, TRole> : IUserStore<TUser>, IUserLoginStore<TUser>, IUserClaimStore<TUser>, IUserRoleStore<TUser>, IUserPasswordStore<TUser>, IUserSecurityStampStore<TUser>, IUserEmailStore<TUser>, IUserLockoutStore<TUser>, IUserTwoFactorStore<TUser>, IUserPhoneNumberStore<TUser>, IUserAuthenticatorKeyStore<TUser>, IUserAuthenticationTokenStore<TUser>, IUserTwoFactorRecoveryCodeStore<TUser>, IQueryableUserStore<TUser> where TUser : IdentityUser where TRole : IdentityRole, new() { private bool _disposed; private readonly Func<IAsyncDocumentSession>? getSessionFunc; private IAsyncDocumentSession? session; private readonly ILogger logger; /// <summary> /// Creates a new user store that uses the Raven document session returned from the specified session fetcher. /// </summary> /// <param name="getSession">The function that gets the Raven document session.</param> /// <param name="logger"></param> public UserStore(Func<IAsyncDocumentSession> getSession, ILogger<UserStore<TUser, TRole>> logger) { this.getSessionFunc = getSession; this.logger = logger; } /// <summary> /// Creates a new user store that uses the specified Raven document session. /// </summary> /// <param name="session"></param> /// <param name="logger"></param> public UserStore(IAsyncDocumentSession session, ILogger<UserStore<TUser, TRole>> logger) { this.session = session; this.logger = logger; } #region IDisposable implementation /// <summary> /// Disposes the user store. /// </summary> public virtual void Dispose() { _disposed = true; } #endregion #region IUserStore implementation /// <inheritdoc /> public virtual Task<string?> GetUserIdAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.Id); /// <inheritdoc /> public virtual Task<string> GetUserNameAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.UserName); /// <inheritdoc /> public virtual Task SetUserNameAsync(TUser user, string userName, CancellationToken cancellationToken) { user.UserName = userName; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string> GetNormalizedUserNameAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.UserName); /// <inheritdoc /> public virtual Task SetNormalizedUserNameAsync(TUser user, string normalizedName, CancellationToken cancellationToken) { user.UserName = normalizedName.ToLowerInvariant(); return Task.CompletedTask; } /// <inheritdoc /> public virtual async Task<IdentityResult> CreateAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); // Make sure we have a valid email address, as we use this for uniqueness. var email = user.Email?.ToLowerInvariant() ?? string.Empty; if (string.IsNullOrWhiteSpace(email)) { throw new ArgumentException("The user's email address can't be null or empty.", nameof(user)); } // Normalize the email and user name. user.Email = email; user.UserName = user.UserName?.ToLowerInvariant() ?? email ?? string.Empty; // See if the email address is already taken. // We do this using Raven's compare/exchange functionality, which works cluster-wide. // https://ravendb.net/docs/article-page/4.1/csharp/client-api/operations/compare-exchange/overview#creating-a-key // // User creation is done in 3 steps: // 1. Reserve the email address, pointing to an empty user ID. // 2. Store the user and save it. // 3. Update the email address reservation to point to the new user's email. // 1. Reserve the email address. logger.LogDebug("Creating email reservation for {UserEmail}", email); var reserveEmailResult = await CreateEmailReservationAsync(email!, string.Empty); // Empty string: Just reserve it for now while we create the user and assign the user's ID. if (!reserveEmailResult.Successful) { logger.LogError("Error creating email reservation for {email}", email); return IdentityResult.Failed(new IdentityErrorDescriber().DuplicateEmail(email)); } // 2. Store the user in the database and save it. try { await DbSession.StoreAsync(user, cancellationToken); await DbSession.SaveChangesAsync(cancellationToken); // 3. Update the email reservation to point to the saved user. var updateReservationResult = await UpdateEmailReservationAsync(email!, user.Id!); if (!updateReservationResult.Successful) { logger.LogError("Error updating email reservation for {email} to {id}", email, user.Id); throw new Exception("Unable to update the email reservation"); } } catch (Exception createUserError) { // The compare/exchange email reservation is cluster-wide, outside of the session scope. // We need to manually roll it back. logger.LogError("Error during user creation", createUserError); DbSession.Delete(user); // It's possible user is already saved to the database. If so, delete him. try { await this.DeleteEmailReservation(user.Email!); } catch (Exception e) { logger.LogError(e, "Caught an exception trying to remove user email reservation for {email} after save failed. An admin must manually delete the compare exchange key {compareExchangeKey}.", user.Email, Conventions.CompareExchangeKeyFor(user.Email!)); } return IdentityResult.Failed(new IdentityErrorDescriber().DefaultError()); } return IdentityResult.Success; } /// <inheritdoc /> public virtual async Task<IdentityResult> UpdateAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); // Make sure we have a valid email address. if (string.IsNullOrWhiteSpace(user.Email)) { throw new ArgumentException("The user's email address can't be null or empty.", nameof(user)); } if (string.IsNullOrWhiteSpace(user.Id)) { throw new ArgumentException("The user can't have a null ID."); } // If nothing changed we have no work to do var changes = DbSession.Advanced.WhatChanged(); var hasUserChanged = changes.TryGetValue(user.Id, out var userChange); if (!hasUserChanged) { logger.LogWarning("UserStore UpdateAsync called without any changes to the User {UserId}", user.Id); // No changes to this document return IdentityResult.Success; } // Check if their changed their email. If not, the rest of the code is unnecessary var emailChange = userChange.FirstOrDefault(x => string.Equals(x.FieldName, nameof(user.Email))); if (emailChange == null) { logger.LogTrace("User {UserId} did not have modified Email, saving normally", user.Id); // Email didn't change, so no reservation to update. Just save the user data return IdentityResult.Success; } // If the user changed their email, we need to update the email compare/exchange reservation. // Get the previous value for their email var oldEmail = emailChange.FieldOldValue.ToString(); if (string.Equals(user.UserName, oldEmail, StringComparison.InvariantCultureIgnoreCase)) { logger.LogTrace("Updating username to match modified email for {UserId}", user.Id); // The username was set to their email so we should update user name as well. user.UserName = user.Email; } // See if the email change was only due to case sensitivity. if (string.Equals(user.Email, oldEmail, StringComparison.InvariantCultureIgnoreCase)) { return IdentityResult.Success; } // Create the new email reservation. var emailReservation = await CreateEmailReservationAsync(user.Email, user.Id); if (!emailReservation.Successful) { DbSession.Advanced.IgnoreChangesFor(user); return IdentityResult.Failed(new IdentityErrorDescriber().DuplicateEmail(user.Email)); } await TryRemoveMigratedEmailReservation(oldEmail, user.Email); return IdentityResult.Success; } /// <inheritdoc /> public virtual async Task<IdentityResult> DeleteAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); cancellationToken.ThrowIfCancellationRequested(); // Delete the user and save it. We must save it because deleting is a cluster-wide operation. // Only if the deletion succeeds will we remove the cluster-wide compare/exchange key. this.DbSession.Delete(user); await this.DbSession.SaveChangesAsync(cancellationToken); // Delete was successful, remove the cluster-wide compare/exchange key. var deletionResult = await DeleteEmailReservation(user.Email); if (!deletionResult.Successful) { logger.LogWarning("User was deleted, but there was an error deleting email reservation for {email}. The compare/exchange value for this should be manually deleted.", user.Email); } return IdentityResult.Success; } /// <inheritdoc /> public virtual Task<TUser> FindByIdAsync(string userId, CancellationToken cancellationToken) => this.DbSession.LoadAsync<TUser>(userId, cancellationToken); /// <inheritdoc /> public virtual Task<TUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken) { return DbSession.Query<TUser>() .SingleOrDefaultAsync(u => u.UserName == normalizedUserName, cancellationToken); } #endregion #region IUserLoginStore implementation /// <inheritdoc /> public virtual Task AddLoginAsync(TUser user, UserLoginInfo login, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); if (login == null) { throw new ArgumentNullException(nameof(login)); } user.Logins.Add(login); return Task.CompletedTask; } /// <inheritdoc /> public virtual Task RemoveLoginAsync(TUser user, string loginProvider, string providerKey, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.Logins.RemoveAll(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey); return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<IList<UserLoginInfo>> GetLoginsAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.Logins as IList<UserLoginInfo>); } /// <inheritdoc /> public virtual Task<TUser> FindByLoginAsync(string loginProvider, string providerKey, CancellationToken cancellationToken) { return DbSession.Query<TUser>() .FirstOrDefaultAsync(u => u.Logins.Any(l => l.LoginProvider == loginProvider && l.ProviderKey == providerKey)); } #endregion #region IUserClaimStore implementation /// <inheritdoc /> public virtual Task<IList<Claim>> GetClaimsAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); IList<Claim> result = user.Claims .Select(c => new Claim(c.ClaimType, c.ClaimValue)) .ToList(); return Task.FromResult(result); } /// <inheritdoc /> public virtual Task AddClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.Claims.AddRange(claims.Select(c => new IdentityUserClaim { ClaimType = c.Type, ClaimValue = c.Value })); return Task.CompletedTask; } /// <inheritdoc /> public virtual async Task ReplaceClaimAsync(TUser user, Claim claim, Claim newClaim, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); var indexOfClaim = user.Claims.FindIndex(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value); if (indexOfClaim != -1) { user.Claims.RemoveAt(indexOfClaim); await this.AddClaimsAsync(user, new[] { newClaim }, cancellationToken); } } /// <inheritdoc /> public virtual Task RemoveClaimsAsync(TUser user, IEnumerable<Claim> claims, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.Claims.RemoveAll(identityClaim => claims.Any(c => c.Type == identityClaim.ClaimType && c.Value == identityClaim.ClaimValue)); return Task.CompletedTask; } /// <inheritdoc /> public virtual async Task<IList<TUser>> GetUsersForClaimAsync(Claim claim, CancellationToken cancellationToken) { ThrowIfDisposedOrCancelled(cancellationToken); if (claim == null) { throw new ArgumentNullException(nameof(claim)); } var list = await DbSession.Query<TUser>() .Where(u => u.Claims.Any(c => c.ClaimType == claim.Type && c.ClaimValue == claim.Value)) .ToListAsync(); return list; } #endregion #region IUserRoleStore implementation /// <inheritdoc /> public virtual async Task AddToRoleAsync(TUser user, string roleName, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); // See if we have an IdentityRole with that name. var roleId = Conventions.RoleIdFor<TRole>(roleName, DbSession.Advanced.DocumentStore); var existingRoleOrNull = await this.DbSession.LoadAsync<IdentityRole>(roleId, cancellationToken); if (existingRoleOrNull == null) { ThrowIfDisposedOrCancelled(cancellationToken); existingRoleOrNull = new TRole { Name = roleName.ToLowerInvariant() }; await this.DbSession.StoreAsync(existingRoleOrNull, roleId, cancellationToken); } // Use the real name (not normalized/uppered/lowered) of the role, as specified by the user. var roleRealName = existingRoleOrNull.Name; if (!user.Roles.Contains(roleRealName, StringComparer.InvariantCultureIgnoreCase)) { user.GetRolesList().Add(roleRealName); } if (user.Id != null && !existingRoleOrNull.Users.Contains(user.Id, StringComparer.InvariantCultureIgnoreCase)) { existingRoleOrNull.Users.Add(user.Id); } } /// <inheritdoc /> public virtual async Task RemoveFromRoleAsync(TUser user, string roleName, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.GetRolesList().RemoveAll(r => string.Equals(r, roleName, StringComparison.InvariantCultureIgnoreCase)); var roleId = RoleStore<TRole>.GetRavenIdFromRoleName(roleName, DbSession.Advanced.DocumentStore); var roleOrNull = await DbSession.LoadAsync<IdentityRole>(roleId, cancellationToken); if (roleOrNull != null && user.Id != null) { roleOrNull.Users.Remove(user.Id); } } /// <inheritdoc /> public virtual Task<IList<string>> GetRolesAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult<IList<string>>(new List<string>(user.Roles)); } /// <inheritdoc /> public virtual Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken) { if (string.IsNullOrEmpty(roleName)) { throw new ArgumentNullException(nameof(roleName)); } return Task.FromResult(user.Roles.Contains(roleName, StringComparer.InvariantCultureIgnoreCase)); } /// <inheritdoc /> public virtual async Task<IList<TUser>> GetUsersInRoleAsync(string roleName, CancellationToken cancellationToken) { ThrowIfDisposedOrCancelled(cancellationToken); if (string.IsNullOrEmpty(roleName)) { throw new ArgumentNullException(nameof(roleName)); } var users = await DbSession.Query<TUser>() .Where(u => u.Roles.Contains(roleName, StringComparer.InvariantCultureIgnoreCase)) .Take(1024) .ToListAsync(); return users; } #endregion #region IUserPasswordStore implementation /// <inheritdoc /> public virtual Task SetPasswordHashAsync(TUser user, string passwordHash, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.PasswordHash = passwordHash; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string?> GetPasswordHashAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.PasswordHash); } /// <inheritdoc /> public virtual Task<bool> HasPasswordAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.PasswordHash != null); } #endregion #region IUserSecurityStampStore implementation /// <inheritdoc /> public virtual Task SetSecurityStampAsync(TUser user, string stamp, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.SecurityStamp = stamp; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string?> GetSecurityStampAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.SecurityStamp); } #endregion #region IUserEmailStore implementation /// <inheritdoc /> public virtual Task SetEmailAsync(TUser user, string email, CancellationToken cancellationToken) { ThrowIfDisposedOrCancelled(cancellationToken); user.Email = email?.ToLowerInvariant() ?? throw new ArgumentNullException(nameof(email)); return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string> GetEmailAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.Email); /// <inheritdoc /> public virtual Task<bool> GetEmailConfirmedAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.EmailConfirmed); /// <inheritdoc /> public virtual Task SetEmailConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken) { user.EmailConfirmed = confirmed; return Task.CompletedTask; } /// <inheritdoc /> #pragma warning disable CS8613 // Nullability of reference types in return type doesn't match implicitly implemented member. public virtual async Task<TUser?> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) #pragma warning restore CS8613 // Nullability of reference types in return type doesn't match implicitly implemented member. { // While we could just do an index query here: DbSession.Query<TUser>().FirstOrDefaultAsync(u => u.Email == normalizedEmail) // We decided against this because indexes can be stale. // Instead, we're going to go straight to the compare/exchange values and find the user for the email. var key = Conventions.CompareExchangeKeyFor(normalizedEmail); var readResult = await DbSession.Advanced.DocumentStore.Operations.ForDatabase(((AsyncDocumentSession)DbSession).DatabaseName).SendAsync(new GetCompareExchangeValueOperation<string>(key)); if (readResult == null || string.IsNullOrEmpty(readResult.Value)) { return null; } return await DbSession.LoadAsync<TUser>(readResult.Value); } /// <inheritdoc /> public virtual Task<string> GetNormalizedEmailAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.Email); /// <inheritdoc /> public virtual Task SetNormalizedEmailAsync(TUser user, string normalizedEmail, CancellationToken cancellationToken) { user.Email = normalizedEmail.ToLowerInvariant(); // I don't like the ALL CAPS default. We're going all lower. return Task.CompletedTask; } #endregion #region IUserLockoutStore implementation /// <inheritdoc /> public virtual Task<DateTimeOffset?> GetLockoutEndDateAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.LockoutEnd); } /// <inheritdoc /> public virtual Task SetLockoutEndDateAsync(TUser user, DateTimeOffset? lockoutEnd, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.LockoutEnd = lockoutEnd; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<int> IncrementAccessFailedCountAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.AccessFailedCount++; return Task.FromResult(user.AccessFailedCount); } /// <inheritdoc /> public virtual Task ResetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.AccessFailedCount = 0; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<int> GetAccessFailedCountAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.AccessFailedCount); } /// <inheritdoc /> public virtual Task<bool> GetLockoutEnabledAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.LockoutEnabled); } /// <inheritdoc /> public virtual Task SetLockoutEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.LockoutEnabled = enabled; return Task.CompletedTask; } #endregion #region IUserTwoFactorStore implementation /// <inheritdoc /> public virtual Task SetTwoFactorEnabledAsync(TUser user, bool enabled, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); user.TwoFactorEnabled = enabled; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<bool> GetTwoFactorEnabledAsync(TUser user, CancellationToken cancellationToken) { ThrowIfNullDisposedCancelled(user, cancellationToken); return Task.FromResult(user.TwoFactorEnabled); } #endregion #region IUserPhoneNumberStore implementation /// <inheritdoc /> public virtual Task SetPhoneNumberAsync(TUser user, string phoneNumber, CancellationToken cancellationToken) { user.PhoneNumber = phoneNumber; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string?> GetPhoneNumberAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.PhoneNumber); /// <inheritdoc /> public virtual Task<bool> GetPhoneNumberConfirmedAsync(TUser user, CancellationToken cancellationToken) => Task.FromResult(user.PhoneNumberConfirmed); /// <inheritdoc /> public virtual Task SetPhoneNumberConfirmedAsync(TUser user, bool confirmed, CancellationToken cancellationToken) { user.PhoneNumberConfirmed = confirmed; return Task.CompletedTask; } #endregion #region IUserAuthenticatorKeyStore implementation /// <inheritdoc /> public virtual Task SetAuthenticatorKeyAsync(TUser user, string key, CancellationToken cancellationToken) { user.TwoFactorAuthenticatorKey = key; return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string?> GetAuthenticatorKeyAsync(TUser user, CancellationToken cancellationToken) { return Task.FromResult(user.TwoFactorAuthenticatorKey); } #endregion #region IUserAuthenticationTokenStore /// <inheritdoc /> public virtual Task SetTokenAsync(TUser user, string loginProvider, string name, string value, CancellationToken cancellationToken) { var existingToken = user.Tokens.FirstOrDefault(t => t.LoginProvider == loginProvider && t.Name == name); if (existingToken != null) { existingToken.Value = value; } else { user.Tokens.Add(new IdentityUserAuthToken { LoginProvider = loginProvider, Name = name, Value = value }); } return Task.CompletedTask; } /// <inheritdoc /> public virtual Task RemoveTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken) { user.Tokens.RemoveAll(t => t.LoginProvider == loginProvider && t.Name == name); return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<string?> GetTokenAsync(TUser user, string loginProvider, string name, CancellationToken cancellationToken) { var tokenOrNull = user.Tokens.FirstOrDefault(t => t.LoginProvider == loginProvider && t.Name == name); return Task.FromResult(tokenOrNull?.Value); } /// <inheritdoc /> public virtual Task ReplaceCodesAsync(TUser user, IEnumerable<string> recoveryCodes, CancellationToken cancellationToken) { user.TwoFactorRecoveryCodes = new List<string>(recoveryCodes); return Task.CompletedTask; } /// <inheritdoc /> public virtual Task<bool> RedeemCodeAsync(TUser user, string code, CancellationToken cancellationToken) { return Task.FromResult(user.TwoFactorRecoveryCodes.Remove(code)); } /// <inheritdoc /> public virtual Task<int> CountCodesAsync(TUser user, CancellationToken cancellationToken) { return Task.FromResult(user.TwoFactorRecoveryCodes.Count); } #endregion #region IQueryableUserStore /// <summary> /// Gets the users as an IQueryable. /// </summary> public virtual IQueryable<TUser> Users => this.DbSession.Query<TUser>(); #endregion /// <summary> /// Gets access to current session being used by this store. /// </summary> protected IAsyncDocumentSession DbSession { get { if (session == null) { session = getSessionFunc!(); } return session; } } private void ThrowIfNullDisposedCancelled(TUser user, CancellationToken token) { if (_disposed) { throw new ObjectDisposedException(this.GetType().Name); } if (user == null) { throw new ArgumentNullException(nameof(user)); } token.ThrowIfCancellationRequested(); } private void ThrowIfDisposedOrCancelled(CancellationToken token) { if (_disposed) { throw new ObjectDisposedException(this.GetType().Name); } token.ThrowIfCancellationRequested(); } /// <summary> /// Create a new email reservation with the given id value /// </summary> /// <param name="email"></param> /// <param name="id"></param> /// <returns></returns> protected virtual Task<CompareExchangeResult<string>> CreateEmailReservationAsync(string email, string id) { var compareExchangeKey = Conventions.CompareExchangeKeyFor(email); var reserveEmailOperation = new PutCompareExchangeValueOperation<string>(compareExchangeKey, id, 0); return DbSession.Advanced.DocumentStore.Operations.ForDatabase(((AsyncDocumentSession)DbSession).DatabaseName).SendAsync(reserveEmailOperation); } /// <summary> /// Update an existing reservation to point to a new UserId /// </summary> /// <param name="email"></param> /// <param name="id"></param> /// <returns></returns> protected virtual async Task<CompareExchangeResult<string>> UpdateEmailReservationAsync(string email, string id) { var key = Conventions.CompareExchangeKeyFor(email); var store = DbSession.Advanced.DocumentStore; var readResult = await store.Operations.ForDatabase(((AsyncDocumentSession)DbSession).DatabaseName).SendAsync(new GetCompareExchangeValueOperation<string>(key)); if (readResult == null) { logger.LogError("Failed to get current index for {EmailReservation} to update it to {ReservedFor}", key, id); return new CompareExchangeResult<string>() { Successful = false }; } var updateEmailUserIdOperation = new PutCompareExchangeValueOperation<string>(key, id, readResult.Index); return await store.Operations.ForDatabase(((AsyncDocumentSession)DbSession).DatabaseName).SendAsync(updateEmailUserIdOperation); } /// <summary> /// Removes email reservation. /// </summary> /// <param name="email"></param> /// <returns></returns> protected virtual async Task<CompareExchangeResult<string>> DeleteEmailReservation(string email) { var key = Conventions.CompareExchangeKeyFor(email); var store = DbSession.Advanced.DocumentStore; var readResult = await store.Operations.ForDatabase(((AsyncDocumentSession)DbSession).DatabaseName).SendAsync(new GetCompareExchangeValueOperation<string>(key)); if (readResult == null) { logger.LogError("Failed to get current index for {EmailReservation} to delete it", key); return new CompareExchangeResult<string>() { Successful = false }; } var deleteEmailOperation = new DeleteCompareExchangeValueOperation<string>(key, readResult.Index); return await DbSession.Advanced.DocumentStore.Operations.ForDatabase(((AsyncDocumentSession)DbSession).DatabaseName).SendAsync(deleteEmailOperation); } /// <summary> /// Attempts to remove an old email reservation as part of a migration from one email to another. /// If unsuccessful, a warning will be logged, but no exception will be thrown. /// </summary> private async Task TryRemoveMigratedEmailReservation(string oldEmail, string newEmail) { var deleteEmailResult = await DeleteEmailReservation(oldEmail); if (!deleteEmailResult.Successful) { // If this happens, it's not critical: the user still changed their email successfully. // They just won't be able to register again with their old email. Log a warning. logger.LogWarning("When user changed email from {oldEmail} to {newEmail}, there was an error removing the old email reservation. The compare exchange key {compareExchangeChange} should be removed manually by an admin.", oldEmail, newEmail, Conventions.CompareExchangeKeyFor(oldEmail)); } } } }
using System; using System.Xml; using System.Collections.Generic; using System.IO; using NDesk.Options; namespace PipelineWSClient { /* * Run the EXE from directly within Windows, e.g.: PipelineWSClient.exe jobs * or * From Mac/Linux via Mono, e.g.: mono PipelineWSClient.exe jobs */ class MainClass { private static List<string> commands = new List<string>{"scripts", "script", "jobs", "job", "log", "result", "delete-job", "new-job"}; public static void Main (string[] args) { string id = null; bool help = false; string jobRequestFile = null; string jobDataFile = null; OptionSet opts = new OptionSet () { { "id=", "ID of Job or Script", v => id = v }, { "job-request=", "XML file representing the job request", v => jobRequestFile = v}, { "job-data=", "Zip file containing the job data", v => jobDataFile = v}, { "help", "Show this message", v => help = v != null }, }; List<string> cmds = opts.Parse(args); //PostJob ("/Users/marisa/Projects/pipeline2/pipeline-framework/webservice/samples/clients/testdata/job3.request.localmode.xml", null); //return; if (help || cmds.Count == 0) { ShowUsage(opts); return; } string command = cmds[0]; if (id == null && (command == "script" || command == "job" || command == "log" || command == "result" || command == "delete-job")) { Console.WriteLine(String.Format("The command {0} must have an id parameter.", command)); ShowUsage(opts); return; } if (jobRequestFile == null && command == "new-job") { Console.WriteLine(String.Format("The command {0} must have a job-request parameter, and may also have a job-data parameter.", command)); ShowUsage(opts); return; } if (command == "scripts") { GetScripts(); } else if (command == "script") { GetScript(id); } else if (command == "jobs") { GetJobs(); } else if (command == "job") { GetJob(id); } else if (command == "log") { GetLog(id); } else if (command == "result") { GetResult(id); } else if (command == "delete-job") { DeleteJob(id); } else if (command == "new-job") { if (jobDataFile == null) { PostJob(jobRequestFile); } else { PostJob(jobRequestFile, jobDataFile); } } else if (command == "alive") { Alive(); } else if (command == "halt") { Halt(); } else { Console.WriteLine ("Command not recognized."); ShowUsage(opts); return; } } private static void ShowUsage(OptionSet opts) { Console.WriteLine("Usage: PipelineWSClient [COMMAND] [OPTIONS]+ "); Console.WriteLine(); Console.WriteLine("Commands:"); foreach (string s in commands) { Console.WriteLine(String.Format("\t{0}", s)); } Console.WriteLine(); Console.WriteLine("Options:"); opts.WriteOptionDescriptions(Console.Out); Console.WriteLine(); Console.WriteLine("Examples:"); Console.WriteLine("Show all scripts: \n\tPipelineWSClient.exe scripts"); Console.WriteLine("Show a specific script: \n\tPipelineWSClient.exe script --id=http://www.daisy.org/pipeline/modules/dtbook-to-zedai/dtbook-to-zedai.xpl"); Console.WriteLine("Show a specific job: \n\tPipelineWSClient.exe job --id=873ce8d7-0b92-42f6-a2ed-b5e6a13b8cd7"); Console.WriteLine("Create a job: \n\tPipelineWSClient.exe new-job --job-request=../../../testdata/job1.request.xml"); Console.WriteLine("Create a job: \n\tPipelineWSClient.exe new-job --job-request=../../../testdata/job2.request.xml --job-data=../../../testdata/job2.data.zip"); } public static void GetScripts() { XmlDocument doc = Resources.GetScripts(); PrintDoc (doc); } public static void GetScript(string id) { XmlDocument doc = Resources.GetScript(id); PrintDoc (doc); } public static void PostJob(string jobRequestFilepath, string jobDataFilepath = null) { StreamReader reader = new StreamReader(jobRequestFilepath); string doc = reader.ReadToEnd(); reader.Close(); FileInfo data = null; if (jobDataFilepath != null) { data = new FileInfo(jobDataFilepath); } XmlDocument jobDoc = Resources.PostJob (doc, data); if (jobDoc == null) { Console.WriteLine("Job not created."); return; } Console.WriteLine("Job created:"); PrettyPrint (jobDoc); } public static void GetJobs() { XmlDocument doc = Resources.GetJobs(); PrintDoc (doc); } public static void GetJob(string id) { XmlDocument doc = Resources.GetJob(id); PrintDoc(doc); } public static void GetLog(string id) { string status = Resources.GetJobStatus(id); if (status != "DONE") { Console.WriteLine (String.Format("Cannot get log until job is done. Job status: {0}.", status)); return; } string log = Resources.GetLog(id); if (log.Length == 0) { Console.WriteLine("No data returned."); return; } Console.WriteLine(log); } public static void GetResult(string id) { string status = Resources.GetJobStatus(id); if (status != "DONE") { Console.WriteLine (String.Format("Cannot get result until job is done. Job status: {0}.", status)); return; } string filepath = String.Format("/tmp/{0}.zip", id); Resources.GetResult(id, filepath); Console.WriteLine(String.Format("Saved to {0}", filepath)); } public static void DeleteJob(string id) { string status = Resources.GetJobStatus(id); if (status != "DONE") { Console.WriteLine (String.Format("Cannot delete until job is done. Job status: {0}.", status)); return; } bool result = Resources.DeleteJob(id); if (!result) { Console.WriteLine("Error deleting job."); } else { Console.WriteLine ("Job deleted."); } } public static void Halt() { Resources.Halt(); } public static void Alive() { XmlDocument doc = Resources.Alive (); PrintDoc (doc); } public static void PrintDoc(XmlDocument doc) { if (doc == null) { Console.WriteLine("No data."); return; } PrettyPrint(doc); } public static void PrettyPrint(XmlDocument doc) { using (StringWriter stringWriter = new StringWriter()) { XmlNodeReader xmlReader = new XmlNodeReader(doc); XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter); xmlWriter.Formatting = Formatting.Indented; xmlWriter.Indentation = 1; xmlWriter.IndentChar = '\t'; xmlWriter.WriteNode(xmlReader, true); Console.WriteLine(stringWriter.ToString()); } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests.Services { using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Reflection; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Impl.Memory; using Apache.Ignite.Core.Impl.Services; using Apache.Ignite.Core.Services; using NUnit.Framework; /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality. /// </summary> public class ServiceProxyTest { /** */ private TestIgniteService _svc; /** */ private readonly Marshaller _marsh = new Marshaller(new BinaryConfiguration { TypeConfigurations = new[] { new BinaryTypeConfiguration(typeof (TestBinarizableClass)), new BinaryTypeConfiguration(typeof (CustomExceptionBinarizable)) } }); /** */ protected readonly IBinary Binary; /** */ private readonly PlatformMemoryManager _memory = new PlatformMemoryManager(1024); /** */ protected bool KeepBinary; /** */ protected bool SrvKeepBinary; /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTest"/> class. /// </summary> public ServiceProxyTest() { Binary = new Binary(_marsh); } /// <summary> /// Tests object class methods proxying. /// </summary> [Test] public void TestObjectClassMethods() { var prx = GetProxy(); prx.IntProp = 12345; Assert.AreEqual("12345", prx.ToString()); Assert.AreEqual("12345", _svc.ToString()); Assert.AreEqual(12345, prx.GetHashCode()); Assert.AreEqual(12345, _svc.GetHashCode()); } /// <summary> /// Tests properties proxying. /// </summary> [Test] [SuppressMessage("ReSharper", "PossibleNullReferenceException")] public void TestProperties() { var prx = GetProxy(); prx.IntProp = 10; Assert.AreEqual(10, prx.IntProp); Assert.AreEqual(10, _svc.IntProp); _svc.IntProp = 15; Assert.AreEqual(15, prx.IntProp); Assert.AreEqual(15, _svc.IntProp); prx.ObjProp = "prop1"; Assert.AreEqual("prop1", prx.ObjProp); Assert.AreEqual("prop1", _svc.ObjProp); prx.ObjProp = null; Assert.IsNull(prx.ObjProp); Assert.IsNull(_svc.ObjProp); prx.ObjProp = new TestClass {Prop = "prop2"}; var propVal = KeepBinary ? ((IBinaryObject) prx.ObjProp).Deserialize<TestClass>().Prop : ((TestClass) prx.ObjProp).Prop; Assert.AreEqual("prop2", propVal); Assert.AreEqual("prop2", ((TestClass) _svc.ObjProp).Prop); } /// <summary> /// Tests void methods proxying. /// </summary> [Test] public void TestVoidMethods() { var prx = GetProxy(); prx.VoidMethod(); Assert.AreEqual("VoidMethod", prx.InvokeResult); Assert.AreEqual("VoidMethod", _svc.InvokeResult); prx.VoidMethod(10); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); prx.VoidMethod(10, "string", "arg"); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); prx.VoidMethod(10, "string", "arg", "arg1", 2, 3, "arg4"); Assert.AreEqual(_svc.InvokeResult, prx.InvokeResult); } /// <summary> /// Tests object methods proxying. /// </summary> [Test] public void TestObjectMethods() { var prx = GetProxy(); Assert.AreEqual("ObjectMethod", prx.ObjectMethod()); Assert.AreEqual("ObjectMethod987", prx.ObjectMethod(987)); Assert.AreEqual("ObjectMethod987str123TestClass", prx.ObjectMethod(987, "str123", new TestClass())); Assert.AreEqual("ObjectMethod987str123TestClass34arg5arg6", prx.ObjectMethod(987, "str123", new TestClass(), 3, 4, "arg5", "arg6")); } /// <summary> /// Tests methods that exist in proxy interface, but do not exist in the actual service. /// </summary> [Test] public void TestMissingMethods() { var prx = GetProxy(); var ex = Assert.Throws<InvalidOperationException>(() => prx.MissingMethod()); Assert.AreEqual("Failed to invoke proxy: there is no method 'MissingMethod'" + " in type 'Apache.Ignite.Core.Tests.Services.ServiceProxyTest+TestIgniteService'" + " with 0 arguments", ex.Message); } /// <summary> /// Tests ambiguous methods handling (multiple methods with the same signature). /// </summary> [Test] public void TestAmbiguousMethods() { var prx = GetProxy(); var ex = Assert.Throws<InvalidOperationException>(() => prx.AmbiguousMethod(1)); Assert.AreEqual("Failed to invoke proxy: there are 2 methods 'AmbiguousMethod' in type " + "'Apache.Ignite.Core.Tests.Services.ServiceProxyTest+TestIgniteService' with (Int32) arguments, " + "can't resolve ambiguity.", ex.Message); } /// <summary> /// Tests the exception. /// </summary> [Test] public void TestException() { var prx = GetProxy(); var err = Assert.Throws<ServiceInvocationException>(prx.ExceptionMethod); if (KeepBinary) { Assert.IsNotNull(err.BinaryCause); Assert.AreEqual("Expected exception", err.BinaryCause.Deserialize<Exception>().Message); } else { Assert.IsNotNull(err.InnerException); Assert.AreEqual("Expected exception", err.InnerException.Message); } Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionMethod()); } [Test] public void TestBinarizableMarshallingException() { var prx = GetProxy(); var ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionBinarizableMethod(false, false)); if (KeepBinary) { Assert.AreEqual("Proxy method invocation failed with a binary error. " + "Examine BinaryCause for details.", ex.Message); Assert.IsNotNull(ex.BinaryCause); Assert.IsNull(ex.InnerException); } else { Assert.AreEqual("Proxy method invocation failed with an exception. " + "Examine InnerException for details.", ex.Message); Assert.IsNull(ex.BinaryCause); Assert.IsNotNull(ex.InnerException); } ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionBinarizableMethod(true, false)); Assert.IsTrue(ex.ToString().Contains( "Call completed with error, but error serialization failed [errType=CustomExceptionBinarizable, " + "serializationErrMsg=Expected exception in CustomExceptionBinarizable.WriteBinary]")); ex = Assert.Throws<ServiceInvocationException>(() => prx.CustomExceptionBinarizableMethod(true, true)); Assert.IsTrue(ex.ToString().Contains( "Call completed with error, but error serialization failed [errType=CustomExceptionBinarizable, " + "serializationErrMsg=Expected exception in CustomExceptionBinarizable.WriteBinary]")); } /// <summary> /// Creates the proxy. /// </summary> protected ITestIgniteServiceProxyInterface GetProxy() { return GetProxy<ITestIgniteServiceProxyInterface>(); } /// <summary> /// Creates the proxy. /// </summary> private T GetProxy<T>() { _svc = new TestIgniteService(Binary); var prx = ServiceProxyFactory<T>.CreateProxy(InvokeProxyMethod); Assert.IsFalse(ReferenceEquals(_svc, prx)); return prx; } /// <summary> /// Invokes the proxy. /// </summary> /// <param name="method">Method.</param> /// <param name="args">Arguments.</param> /// <returns> /// Invocation result. /// </returns> private object InvokeProxyMethod(MethodBase method, object[] args) { using (var inStream = new PlatformMemoryStream(_memory.Allocate())) using (var outStream = new PlatformMemoryStream(_memory.Allocate())) { // 1) Write to a stream inStream.WriteBool(SrvKeepBinary); // WriteProxyMethod does not do this, but Java does ServiceProxySerializer.WriteProxyMethod(_marsh.StartMarshal(inStream), method.Name, method, args, PlatformType.DotNet); inStream.SynchronizeOutput(); inStream.Seek(0, SeekOrigin.Begin); // 2) call InvokeServiceMethod string mthdName; object[] mthdArgs; ServiceProxySerializer.ReadProxyMethod(inStream, _marsh, out mthdName, out mthdArgs); var result = ServiceProxyInvoker.InvokeServiceMethod(_svc, mthdName, mthdArgs); ServiceProxySerializer.WriteInvocationResult(outStream, _marsh, result.Key, result.Value); var writer = _marsh.StartMarshal(outStream); writer.WriteString("unused"); // fake Java exception details writer.WriteString("unused"); // fake Java exception details outStream.SynchronizeOutput(); outStream.Seek(0, SeekOrigin.Begin); return ServiceProxySerializer.ReadInvocationResult(outStream, _marsh, KeepBinary); } } /// <summary> /// Test service interface. /// </summary> public interface ITestIgniteServiceProperties { /** */ int IntProp { get; set; } /** */ object ObjProp { get; set; } /** */ string InvokeResult { get; } } /// <summary> /// Test service interface to check ambiguity handling. /// </summary> public interface ITestIgniteServiceAmbiguity { /** */ int AmbiguousMethod(int arg); } /// <summary> /// Test service interface. /// </summary> public interface ITestIgniteService : ITestIgniteServiceProperties { /** */ void VoidMethod(); /** */ void VoidMethod(int arg); /** */ void VoidMethod(int arg, string arg1, object arg2 = null); /** */ void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args); /** */ object ObjectMethod(); /** */ object ObjectMethod(int arg); /** */ object ObjectMethod(int arg, string arg1, object arg2 = null); /** */ object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args); /** */ void ExceptionMethod(); /** */ void CustomExceptionMethod(); /** */ void CustomExceptionBinarizableMethod(bool throwOnWrite, bool throwOnRead); /** */ TestBinarizableClass BinarizableArgMethod(int arg1, IBinaryObject arg2); /** */ IBinaryObject BinarizableResultMethod(int arg1, TestBinarizableClass arg2); /** */ IBinaryObject BinarizableArgAndResultMethod(int arg1, IBinaryObject arg2); /** */ int AmbiguousMethod(int arg); } /// <summary> /// Test service interface. Does not derive from actual interface, but has all the same method signatures. /// </summary> public interface ITestIgniteServiceProxyInterface { /** */ int IntProp { get; set; } /** */ object ObjProp { get; set; } /** */ string InvokeResult { get; } /** */ void VoidMethod(); /** */ void VoidMethod(int arg); /** */ void VoidMethod(int arg, string arg1, object arg2); /** */ void VoidMethod(int arg, string arg1, object arg2, params object[] args); /** */ object ObjectMethod(); /** */ object ObjectMethod(int arg); /** */ object ObjectMethod(int arg, string arg1, object arg2); /** */ object ObjectMethod(int arg, string arg1, object arg2, params object[] args); /** */ void ExceptionMethod(); /** */ void CustomExceptionMethod(); /** */ void CustomExceptionBinarizableMethod(bool throwOnWrite, bool throwOnRead); /** */ TestBinarizableClass BinarizableArgMethod(int arg1, IBinaryObject arg2); /** */ IBinaryObject BinarizableResultMethod(int arg1, TestBinarizableClass arg2); /** */ IBinaryObject BinarizableArgAndResultMethod(int arg1, IBinaryObject arg2); /** */ void MissingMethod(); /** */ int AmbiguousMethod(int arg); } /// <summary> /// Test service. /// </summary> [Serializable] private class TestIgniteService : ITestIgniteService, ITestIgniteServiceAmbiguity { /** */ private readonly IBinary _binary; /// <summary> /// Initializes a new instance of the <see cref="TestIgniteService"/> class. /// </summary> /// <param name="binary">Binary.</param> public TestIgniteService(IBinary binary) { _binary = binary; } /** <inheritdoc /> */ public int IntProp { get; set; } /** <inheritdoc /> */ public object ObjProp { get; set; } /** <inheritdoc /> */ public string InvokeResult { get; private set; } /** <inheritdoc /> */ public void VoidMethod() { InvokeResult = "VoidMethod"; } /** <inheritdoc /> */ public void VoidMethod(int arg) { InvokeResult = "VoidMethod" + arg; } /** <inheritdoc /> */ public void VoidMethod(int arg, string arg1, object arg2 = null) { InvokeResult = "VoidMethod" + arg + arg1 + arg2; } /** <inheritdoc /> */ public void VoidMethod(int arg, string arg1, object arg2 = null, params object[] args) { InvokeResult = "VoidMethod" + arg + arg1 + arg2 + string.Concat(args.Select(x => x.ToString())); } /** <inheritdoc /> */ public object ObjectMethod() { return "ObjectMethod"; } /** <inheritdoc /> */ public object ObjectMethod(int arg) { return "ObjectMethod" + arg; } /** <inheritdoc /> */ public object ObjectMethod(int arg, string arg1, object arg2 = null) { return "ObjectMethod" + arg + arg1 + arg2; } /** <inheritdoc /> */ public object ObjectMethod(int arg, string arg1, object arg2 = null, params object[] args) { return "ObjectMethod" + arg + arg1 + arg2 + string.Concat(args.Select(x => x.ToString())); } /** <inheritdoc /> */ public void ExceptionMethod() { throw new ArithmeticException("Expected exception"); } /** <inheritdoc /> */ public void CustomExceptionMethod() { throw new CustomException(); } /** <inheritdoc /> */ public void CustomExceptionBinarizableMethod(bool throwOnWrite, bool throwOnRead) { throw new CustomExceptionBinarizable {ThrowOnRead = throwOnRead, ThrowOnWrite = throwOnWrite}; } /** <inheritdoc /> */ public TestBinarizableClass BinarizableArgMethod(int arg1, IBinaryObject arg2) { return arg2.Deserialize<TestBinarizableClass>(); } /** <inheritdoc /> */ public IBinaryObject BinarizableResultMethod(int arg1, TestBinarizableClass arg2) { return _binary.ToBinary<IBinaryObject>(arg2); } /** <inheritdoc /> */ public IBinaryObject BinarizableArgAndResultMethod(int arg1, IBinaryObject arg2) { return _binary.ToBinary<IBinaryObject>(arg2.Deserialize<TestBinarizableClass>()); } /** <inheritdoc /> */ public override string ToString() { return IntProp.ToString(); } /** <inheritdoc /> */ public override int GetHashCode() { // ReSharper disable once NonReadonlyMemberInGetHashCode return IntProp.GetHashCode(); } /** <inheritdoc /> */ int ITestIgniteService.AmbiguousMethod(int arg) { return arg; } /** <inheritdoc /> */ int ITestIgniteServiceAmbiguity.AmbiguousMethod(int arg) { return -arg; } } /// <summary> /// Test serializable class. /// </summary> [Serializable] private class TestClass { /** */ public string Prop { get; set; } /** <inheritdoc /> */ public override string ToString() { return "TestClass" + Prop; } } /// <summary> /// Custom non-serializable exception. /// </summary> private class CustomException : Exception, IBinarizable { /** <inheritDoc /> */ public void WriteBinary(IBinaryWriter writer) { throw new BinaryObjectException("Expected"); } /** <inheritDoc /> */ public void ReadBinary(IBinaryReader reader) { throw new BinaryObjectException("Expected"); } } /// <summary> /// Custom non-serializable exception. /// </summary> private class CustomExceptionBinarizable : Exception, IBinarizable { /** */ public bool ThrowOnWrite { get; set; } /** */ public bool ThrowOnRead { get; set; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteBoolean("ThrowOnRead", ThrowOnRead); if (ThrowOnWrite) throw new Exception("Expected exception in CustomExceptionBinarizable.WriteBinary"); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { ThrowOnRead = reader.ReadBoolean("ThrowOnRead"); if (ThrowOnRead) throw new Exception("Expected exception in CustomExceptionBinarizable.ReadBinary"); } } /// <summary> /// Binarizable object for method argument/result. /// </summary> public class TestBinarizableClass : IBinarizable { /** */ public string Prop { get; set; } /** */ public bool ThrowOnWrite { get; set; } /** */ public bool ThrowOnRead { get; set; } /** <inheritdoc /> */ public void WriteBinary(IBinaryWriter writer) { writer.WriteString("Prop", Prop); writer.WriteBoolean("ThrowOnRead", ThrowOnRead); if (ThrowOnWrite) throw new Exception("Expected exception in TestBinarizableClass.WriteBinary"); } /** <inheritdoc /> */ public void ReadBinary(IBinaryReader reader) { Prop = reader.ReadString("Prop"); ThrowOnRead = reader.ReadBoolean("ThrowOnRead"); if (ThrowOnRead) throw new Exception("Expected exception in TestBinarizableClass.ReadBinary"); } } } /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality with keepBinary mode enabled on client. /// </summary> public class ServiceProxyTestKeepBinaryClient : ServiceProxyTest { /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTestKeepBinaryClient"/> class. /// </summary> public ServiceProxyTestKeepBinaryClient() { KeepBinary = true; } [Test] public void TestBinarizableMethods() { var prx = GetProxy(); var obj = new TestBinarizableClass { Prop = "PropValue" }; var result = prx.BinarizableResultMethod(1, obj); Assert.AreEqual(obj.Prop, result.Deserialize<TestBinarizableClass>().Prop); } } /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality with keepBinary mode enabled on server. /// </summary> public class ServiceProxyTestKeepBinaryServer : ServiceProxyTest { /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTestKeepBinaryServer"/> class. /// </summary> public ServiceProxyTestKeepBinaryServer() { SrvKeepBinary = true; } [Test] public void TestBinarizableMethods() { var prx = GetProxy(); var obj = new TestBinarizableClass { Prop = "PropValue" }; var portObj = Binary.ToBinary<IBinaryObject>(obj); var result = prx.BinarizableArgMethod(1, portObj); Assert.AreEqual(obj.Prop, result.Prop); } } /// <summary> /// Tests <see cref="ServiceProxySerializer"/> functionality with keepBinary mode enabled on client and on server. /// </summary> public class ServiceProxyTestKeepBinaryClientServer : ServiceProxyTest { /// <summary> /// Initializes a new instance of the <see cref="ServiceProxyTestKeepBinaryClientServer"/> class. /// </summary> public ServiceProxyTestKeepBinaryClientServer() { KeepBinary = true; SrvKeepBinary = true; } [Test] public void TestBinarizableMethods() { var prx = GetProxy(); var obj = new TestBinarizableClass { Prop = "PropValue" }; var portObj = Binary.ToBinary<IBinaryObject>(obj); var result = prx.BinarizableArgAndResultMethod(1, portObj); Assert.AreEqual(obj.Prop, result.Deserialize<TestBinarizableClass>().Prop); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using UnityEngine; using Vexe.Runtime.Helpers; namespace Vexe.Runtime.Types { /// <summary> /// Serializable by Unity's serialization system - Extracted from System.Collections.Generic (not a wrapper) /// </summary> [Serializable, DebuggerDisplay("Count = {Count}")] public class SerializableDictionary<TKey, TValue> : IDictionary<TKey, TValue>, IDictionary { [SerializeField] private int[] _Buckets; [SerializeField] private int[] _HashCodes; [SerializeField] private int[] _Next; [SerializeField] private int _Count; [SerializeField] private int _Version; [SerializeField] private int _FreeList; [SerializeField] private int _FreeCount; [SerializeField] private TKey[] _Keys; [SerializeField] private TValue[] _Values; private readonly IEqualityComparer<TKey> _Comparer; public Dictionary<TKey, TValue> AsDictionary { get { return new Dictionary<TKey, TValue>(this); } } public int Count { get { return _Count - _FreeCount; } } public TValue this[TKey key] { get { int index = FindIndex(key); if (index >= 0) return _Values[index]; ErrorHelper.KeyNotFound(key.ToString()); return default(TValue); } set { Insert(key, value, false); } } public SerializableDictionary() : this(0, null) { } public SerializableDictionary(int capacity) : this(capacity, null) { } public SerializableDictionary(IEqualityComparer<TKey> comparer) : this(0, comparer) { } public SerializableDictionary(int capacity, IEqualityComparer<TKey> comparer) { if (capacity < 0) throw new ArgumentOutOfRangeException("capacity"); Initialize(capacity); _Comparer = (comparer ?? EqualityComparer<TKey>.Default); } public SerializableDictionary(IDictionary<TKey, TValue> dictionary) : this(dictionary, null) { } public SerializableDictionary(IDictionary<TKey, TValue> dictionary, IEqualityComparer<TKey> comparer) : this((dictionary != null) ? dictionary.Count : 0, comparer) { if (dictionary == null) throw new ArgumentNullException("dictionary"); foreach (KeyValuePair<TKey, TValue> current in dictionary) Add(current.Key, current.Value); } public bool ContainsValue(TValue value) { if (value == null) { for (int i = 0; i < _Count; i++) { if (_HashCodes[i] >= 0 && _Values[i] == null) return true; } } else { var defaultComparer = EqualityComparer<TValue>.Default; for (int i = 0; i < _Count; i++) { if (_HashCodes[i] >= 0 && defaultComparer.Equals(_Values[i], value)) return true; } } return false; } public bool ContainsKey(TKey key) { return FindIndex(key) >= 0; } public void Clear() { if (_Count <= 0) return; for (int i = 0; i < _Buckets.Length; i++) _Buckets[i] = -1; Array.Clear(_Keys, 0, _Count); Array.Clear(_Values, 0, _Count); Array.Clear(_HashCodes, 0, _Count); Array.Clear(_Next, 0, _Count); _FreeList = -1; _Count = 0; _FreeCount = 0; _Version++; } public void Add(TKey key, TValue value) { Insert(key, value, true); } private void Resize(int newSize, bool forceNewHashCodes) { int[] bucketsCopy = new int[newSize]; for (int i = 0; i < bucketsCopy.Length; i++) bucketsCopy[i] = -1; var keysCopy = new TKey[newSize]; var valuesCopy = new TValue[newSize]; var hashCodesCopy = new int[newSize]; var nextCopy = new int[newSize]; Array.Copy(_Values, 0, valuesCopy, 0, _Count); Array.Copy(_Keys, 0, keysCopy, 0, _Count); Array.Copy(_HashCodes, 0, hashCodesCopy, 0, _Count); Array.Copy(_Next, 0, nextCopy, 0, _Count); if (forceNewHashCodes) { for (int i = 0; i < _Count; i++) { if (hashCodesCopy[i] != -1) hashCodesCopy[i] = (_Comparer.GetHashCode(keysCopy[i]) & 2147483647); } } for (int i = 0; i < _Count; i++) { int index = hashCodesCopy[i] % newSize; nextCopy[i] = bucketsCopy[index]; bucketsCopy[index] = i; } _Buckets = bucketsCopy; _Keys = keysCopy; _Values = valuesCopy; _HashCodes = hashCodesCopy; _Next = nextCopy; } private void Resize() { Resize(PrimeHelper.ExpandPrime(_Count), false); } public bool Remove(TKey key) { if (key == null) throw new ArgumentNullException("key"); int hash = _Comparer.GetHashCode(key) & 2147483647; int index = hash % _Buckets.Length; int num = -1; for (int i = _Buckets[index]; i >= 0; i = _Next[i]) { if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key)) { if (num < 0) _Buckets[index] = _Next[i]; else _Next[num] = _Next[i]; _HashCodes[i] = -1; _Next[i] = _FreeList; _Keys[i] = default(TKey); _Values[i] = default(TValue); _FreeList = i; _FreeCount++; _Version++; return true; } num = i; } return false; } private void Insert(TKey key, TValue value, bool add) { if (key == null) throw new ArgumentNullException("key"); if (_Buckets == null) Initialize(0); int hash = _Comparer.GetHashCode(key) & 2147483647; int index = hash % _Buckets.Length; int num1 = 0; for (int i = _Buckets[index]; i >= 0; i = _Next[i]) { if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key)) { if (add) throw new ArgumentException("Key already exists: " + key); _Values[i] = value; _Version++; return; } num1++; } int num2; if (_FreeCount > 0) { num2 = _FreeList; _FreeList = _Next[num2]; _FreeCount--; } else { if (_Count == _Keys.Length) { Resize(); index = hash % _Buckets.Length; } num2 = _Count; _Count++; } _HashCodes[num2] = hash; _Next[num2] = _Buckets[index]; _Keys[num2] = key; _Values[num2] = value; _Buckets[index] = num2; _Version++; //if (num3 > 100 && HashHelpers.IsWellKnownEqualityComparer(comparer)) //{ // comparer = (IEqualityComparer<TKey>)HashHelpers.GetRandomizedEqualityComparer(comparer); // Resize(entries.Length, true); //} } private void Initialize(int capacity) { int prime = PrimeHelper.GetPrime(capacity); _Buckets = new int[prime]; for (int i = 0; i < _Buckets.Length; i++) _Buckets[i] = -1; _Keys = new TKey[prime]; _Values = new TValue[prime]; _HashCodes = new int[prime]; _Next = new int[prime]; _FreeList = -1; } private int FindIndex(TKey key) { if (key == null) throw new ArgumentNullException("key"); if (_Buckets != null) { int hash = _Comparer.GetHashCode(key) & 2147483647; for (int i = _Buckets[hash % _Buckets.Length]; i >= 0; i = _Next[i]) { if (_HashCodes[i] == hash && _Comparer.Equals(_Keys[i], key)) return i; } } return -1; } public bool TryGetValue(TKey key, out TValue value) { int index = FindIndex(key); if (index >= 0) { value = _Values[index]; return true; } value = default(TValue); return false; } public TValue ValueOrDefault(TKey key) { return ValueOrDefault(key, default(TValue)); } public TValue ValueOrDefault(TKey key, TValue defaultValue) { //return this[key, defaultValue]; int index = FindIndex(key); if (index >= 0) return _Values[index]; return defaultValue; } private static class PrimeHelper { public static readonly int[] Primes = new int[] { 3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919, 1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591, 17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437, 187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263, 1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 }; public static bool IsPrime(int candidate) { if ((candidate & 1) != 0) { int num = (int) Math.Sqrt((double) candidate); for (int i = 3; i <= num; i += 2) { if (candidate % i == 0) { return false; } } return true; } return candidate == 2; } public static int GetPrime(int min) { if (min < 0) throw new ArgumentException("min < 0"); for (int i = 0; i < PrimeHelper.Primes.Length; i++) { int prime = PrimeHelper.Primes[i]; if (prime >= min) return prime; } for (int i = min | 1; i < 2147483647; i += 2) { if (PrimeHelper.IsPrime(i) && (i - 1) % 101 != 0) return i; } return min; } public static int ExpandPrime(int oldSize) { int num = 2 * oldSize; if (num > 2146435069 && 2146435069 > oldSize) { return 2146435069; } return PrimeHelper.GetPrime(num); } } public ICollection<TKey> Keys { get { return _Keys.Take(Count).ToArray(); } } public ICollection<TValue> Values { get { return _Values.Take(Count).ToArray(); } } public void Add(KeyValuePair<TKey, TValue> item) { Add(item.Key, item.Value); } public bool Contains(KeyValuePair<TKey, TValue> item) { int index = FindIndex(item.Key); return index >= 0 && EqualityComparer<TValue>.Default.Equals(_Values[index], item.Value); } public void CopyTo(KeyValuePair<TKey, TValue>[] array, int index) { if (array == null) throw new ArgumentNullException("array"); if (index < 0 || index > array.Length) throw new ArgumentOutOfRangeException(string.Format("index = {0} array.Length = {1}", index, array.Length)); if (array.Length - index < Count) throw new ArgumentException(string.Format("The number of elements in the dictionary ({0}) is greater than the available space from index to the end of the destination array {1}.", Count, array.Length)); for (int i = 0; i < _Count; i++) { if (_HashCodes[i] >= 0) array[index++] = new KeyValuePair<TKey, TValue>(_Keys[i], _Values[i]); } } public bool IsReadOnly { get { return false; } } public bool Remove(KeyValuePair<TKey, TValue> item) { return Remove(item.Key); } public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator() { return GetEnumerator(); } public struct Enumerator : IEnumerator<KeyValuePair<TKey, TValue>>, IDictionaryEnumerator { private readonly SerializableDictionary<TKey, TValue> _Dictionary; private int _Version; private int _Index; private KeyValuePair<TKey, TValue> _Current; public KeyValuePair<TKey, TValue> Current { get { return _Current; } } internal Enumerator(SerializableDictionary<TKey, TValue> dictionary) { _Dictionary = dictionary; _Version = dictionary._Version; _Current = default(KeyValuePair<TKey, TValue>); _Index = 0; } public bool MoveNext() { if (_Version != _Dictionary._Version) throw new InvalidOperationException(string.Format("Enumerator version {0} != Dictionary version {1}", _Version, _Dictionary._Version)); while (_Index < _Dictionary._Count) { if (_Dictionary._HashCodes[_Index] >= 0) { _Current = new KeyValuePair<TKey, TValue>(_Dictionary._Keys[_Index], _Dictionary._Values[_Index]); _Index++; return true; } _Index++; } _Index = _Dictionary._Count + 1; _Current = default(KeyValuePair<TKey, TValue>); return false; } void IEnumerator.Reset() { if (_Version != _Dictionary._Version) throw new InvalidOperationException(string.Format("Enumerator version {0} != Dictionary version {1}", _Version, _Dictionary._Version)); _Index = 0; _Current = default(KeyValuePair<TKey, TValue>); } object IEnumerator.Current { get { return Current; } } public void Dispose() { } public DictionaryEntry Entry { get { return new DictionaryEntry(Key, Value); } } public object Key { get { return Current.Key; } } public object Value { get { return Current.Value; } } } // IDictionary #region public void Add(object key, object value) { Add((TKey) key, (TValue) value); } public bool Contains(object key) { return ContainsKey((TKey) key); } IDictionaryEnumerator IDictionary.GetEnumerator() { return GetEnumerator(); } public bool IsFixedSize { get { return false; } } ICollection IDictionary.Keys { get { return _Keys.Take(Count).ToArray(); } } ICollection IDictionary.Values { get { return _Values.Take(Count).ToArray(); } } public void Remove(object key) { Remove((TKey) key); } public object this[object key] { get { return this[(TKey) key]; } set { this[(TKey) key] = (TValue) value; } } public void CopyTo(Array array, int index) { CopyTo((KeyValuePair<TKey, TValue>[]) array, index); } public bool IsSynchronized { get { throw new NotImplementedException(); } } public object SyncRoot { get { throw new NotImplementedException(); } } #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> /// A theater group or company\u2014for example, the Royal Shakespeare Company or Druid Theatre. /// </summary> public class TheaterGroup_Core : TypeCore, IPerformingGroup { public TheaterGroup_Core() { this._TypeId = 265; this._Id = "TheaterGroup"; this._Schema_Org_Url = "http://schema.org/TheaterGroup"; string label = ""; GetLabel(out label, "TheaterGroup", typeof(TheaterGroup_Core)); this._Label = label; this._Ancestors = new int[]{266,193,200}; this._SubTypes = new int[0]; this._SuperTypes = new int[]{200}; this._Properties = new int[]{67,108,143,229,5,10,47,75,77,85,91,94,95,115,130,137,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> /// A contact point for a person or organization. /// </summary> private ContactPoints_Core contactPoints; public ContactPoints_Core ContactPoints { get { return contactPoints; } set { contactPoints = value; SetPropertyInstance(contactPoints); } } /// <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> /// Email address. /// </summary> private Email_Core email; public Email_Core Email { get { return email; } set { email = value; SetPropertyInstance(email); } } /// <summary> /// People working for this organization. /// </summary> private Employees_Core employees; public Employees_Core Employees { get { return employees; } set { employees = value; SetPropertyInstance(employees); } } /// <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> /// A person who founded this organization. /// </summary> private Founders_Core founders; public Founders_Core Founders { get { return founders; } set { founders = value; SetPropertyInstance(founders); } } /// <summary> /// The date that this organization was founded. /// </summary> private FoundingDate_Core foundingDate; public FoundingDate_Core FoundingDate { get { return foundingDate; } set { foundingDate = value; SetPropertyInstance(foundingDate); } } /// <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> /// The location of the event or organization. /// </summary> private Location_Core location; public Location_Core Location { get { return location; } set { location = value; SetPropertyInstance(location); } } /// <summary> /// A member of this organization. /// </summary> private Members_Core members; public Members_Core Members { get { return members; } set { members = value; SetPropertyInstance(members); } } /// <summary> /// The name of the item. /// </summary> private Name_Core name; public Name_Core Name { get { return name; } set { name = value; SetPropertyInstance(name); } } /// <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); } } } }
using System; using System.Linq; using System.ComponentModel.DataAnnotations; using Csla; using System.ComponentModel; using System.Threading.Tasks; using ProjectTracker.Dal; namespace ProjectTracker.Library { [Serializable()] public class ProjectEdit : CslaBaseTypes.BusinessBase<ProjectEdit> { public static readonly PropertyInfo<byte[]> TimeStampProperty = RegisterProperty<byte[]>(nameof(TimeStamp)); [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public byte[] TimeStamp { get { return GetProperty(TimeStampProperty); } set { SetProperty(TimeStampProperty, value); } } public static readonly PropertyInfo<int> IdProperty = RegisterProperty<int>(nameof(Id)); [Display(Name = "Project id")] public int Id { get { return GetProperty(IdProperty); } private set { LoadProperty(IdProperty, value); } } public static readonly PropertyInfo<string> NameProperty = RegisterProperty<string>(nameof(Name)); [Display(Name = "Project name")] [Required] [StringLength(50)] public string Name { get { return GetProperty(NameProperty); } set { SetProperty(NameProperty, value); } } public static readonly PropertyInfo<DateTime?> StartedProperty = RegisterProperty<DateTime?>(nameof(Started)); public DateTime? Started { get { return GetProperty(StartedProperty); } set { SetProperty(StartedProperty, value); } } public static readonly PropertyInfo<DateTime?> EndedProperty = RegisterProperty<DateTime?>(nameof(Ended)); public DateTime? Ended { get { return GetProperty(EndedProperty); } set { SetProperty(EndedProperty, value); } } public static readonly PropertyInfo<string> DescriptionProperty = RegisterProperty<string>(nameof(Description)); public string Description { get { return GetProperty(DescriptionProperty); } set { SetProperty(DescriptionProperty, value); } } public static readonly PropertyInfo<ProjectResources> ResourcesProperty = RegisterProperty<ProjectResources>(nameof(Resources)); public ProjectResources Resources { get { return GetProperty(ResourcesProperty); } private set { LoadProperty(ResourcesProperty, value); } } public override string ToString() { return Id.ToString(); } protected override void AddBusinessRules() { base.AddBusinessRules(); //BusinessRules.AddRule(new Csla.Rules.CommonRules.Required(NameProperty)); BusinessRules.AddRule( new StartDateGTEndDate { PrimaryProperty = StartedProperty, AffectedProperties = { EndedProperty } }); BusinessRules.AddRule( new StartDateGTEndDate { PrimaryProperty = EndedProperty, AffectedProperties = { StartedProperty } }); BusinessRules.AddRule( new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.WriteProperty, NameProperty, "ProjectManager")); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.WriteProperty, StartedProperty, Security.Roles.ProjectManager)); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.WriteProperty, EndedProperty, Security.Roles.ProjectManager)); BusinessRules.AddRule(new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.WriteProperty, DescriptionProperty, Security.Roles.ProjectManager)); BusinessRules.AddRule(new NoDuplicateResource { PrimaryProperty = ResourcesProperty }); } [EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [ObjectAuthorizationRules] public static void AddObjectAuthorizationRules() { Csla.Rules.BusinessRules.AddRule( typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole( Csla.Rules.AuthorizationActions.CreateObject, "ProjectManager")); Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.EditObject, Security.Roles.ProjectManager)); Csla.Rules.BusinessRules.AddRule(typeof(ProjectEdit), new Csla.Rules.CommonRules.IsInRole(Csla.Rules.AuthorizationActions.DeleteObject, Security.Roles.ProjectManager, Security.Roles.Administrator)); } protected override void OnChildChanged(Csla.Core.ChildChangedEventArgs e) { if (e.ChildObject is ProjectResources) { BusinessRules.CheckRules(ResourcesProperty); OnPropertyChanged(ResourcesProperty); } base.OnChildChanged(e); } private class NoDuplicateResource : Csla.Rules.BusinessRule { protected override void Execute(Csla.Rules.IRuleContext context) { var target = (ProjectEdit)context.Target; foreach (var item in target.Resources) { var count = target.Resources.Count(r => r.ResourceId == item.ResourceId); if (count > 1) { context.AddErrorResult("Duplicate resources not allowed"); return; } } } } private class StartDateGTEndDate : Csla.Rules.BusinessRule { protected override void Execute(Csla.Rules.IRuleContext context) { var target = (ProjectEdit)context.Target; var started = target.ReadProperty(StartedProperty); var ended = target.ReadProperty(EndedProperty); if (started.HasValue && ended.HasValue && started > ended || !started.HasValue && ended.HasValue) context.AddErrorResult("Start date can't be after end date"); } } public async static Task<ProjectEdit> NewProjectAsync() { return await DataPortal.CreateAsync<ProjectEdit>(); } public async static Task<ProjectEdit> GetProjectAsync(int id) { return await DataPortal.FetchAsync<ProjectEdit>(id); } public static ProjectEdit NewProject() { return DataPortal.Create<ProjectEdit>(); } public static ProjectEdit GetProject(int id) { return DataPortal.Fetch<ProjectEdit>(id); } public static async Task DeleteProjectAsync(int id) { await DataPortal.DeleteAsync<ProjectEdit>(id); } public static async Task<bool> ExistsAsync(int id) { var cmd = await DataPortal.CreateAsync<ProjectExistsCommand>(id); cmd = await DataPortal.ExecuteAsync(cmd); return cmd.ProjectExists; } [Create] [RunLocal] private void Create() { LoadProperty(ResourcesProperty, DataPortal.CreateChild<ProjectResources>()); BusinessRules.CheckRules(); } [Fetch] private void Fetch(int id, [Inject] IProjectDal dal) { var data = dal.Fetch(id); using (BypassPropertyChecks) { Id = data.Id; Name = data.Name; Description = data.Description; Started = data.Started; Ended = data.Ended; TimeStamp = data.LastChanged; Resources = DataPortal.FetchChild<ProjectResources>(id); } } [Insert] private void Insert([Inject] IProjectDal dal) { using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.ProjectDto { Name = this.Name, Description = this.Description, Started = this.Started, Ended = this.Ended }; dal.Insert(item); Id = item.Id; TimeStamp = item.LastChanged; } FieldManager.UpdateChildren(this); } [Update] private void Update([Inject] IProjectDal dal) { using (BypassPropertyChecks) { var item = new ProjectTracker.Dal.ProjectDto { Id = this.Id, Name = this.Name, Description = this.Description, Started = this.Started, Ended = this.Ended, LastChanged = this.TimeStamp }; dal.Update(item); TimeStamp = item.LastChanged; } FieldManager.UpdateChildren(this.Id); } [DeleteSelf] private void DeleteSelf([Inject] IProjectDal dal) { using (BypassPropertyChecks) { Resources.Clear(); FieldManager.UpdateChildren(this); Delete(this.Id, dal); } } [Delete] private void Delete(int id, [Inject] IProjectDal dal) { dal.Delete(id); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Runtime.InteropServices; namespace Internal.Cryptography.Pal.Native { internal enum CertQueryObjectType : int { CERT_QUERY_OBJECT_FILE = 0x00000001, CERT_QUERY_OBJECT_BLOB = 0x00000002, } [Flags] internal enum ExpectedContentTypeFlags : int { //encoded single certificate CERT_QUERY_CONTENT_FLAG_CERT = 1 << ContentType.CERT_QUERY_CONTENT_CERT, //encoded single CTL CERT_QUERY_CONTENT_FLAG_CTL = 1 << ContentType.CERT_QUERY_CONTENT_CTL, //encoded single CRL CERT_QUERY_CONTENT_FLAG_CRL = 1 << ContentType.CERT_QUERY_CONTENT_CRL, //serialized store CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_STORE, //serialized single certificate CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CERT, //serialized single CTL CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CTL, //serialized single CRL CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL = 1 << ContentType.CERT_QUERY_CONTENT_SERIALIZED_CRL, //an encoded PKCS#7 signed message CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED, //an encoded PKCS#7 message. But it is not a signed message CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_UNSIGNED, //the content includes an embedded PKCS7 signed message CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED = 1 << ContentType.CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED, //an encoded PKCS#10 CERT_QUERY_CONTENT_FLAG_PKCS10 = 1 << ContentType.CERT_QUERY_CONTENT_PKCS10, //an encoded PFX BLOB CERT_QUERY_CONTENT_FLAG_PFX = 1 << ContentType.CERT_QUERY_CONTENT_PFX, //an encoded CertificatePair (contains forward and/or reverse cross certs) CERT_QUERY_CONTENT_FLAG_CERT_PAIR = 1 << ContentType.CERT_QUERY_CONTENT_CERT_PAIR, //an encoded PFX BLOB, and we do want to load it (not included in //CERT_QUERY_CONTENT_FLAG_ALL) CERT_QUERY_CONTENT_FLAG_PFX_AND_LOAD = 1 << ContentType.CERT_QUERY_CONTENT_PFX_AND_LOAD, CERT_QUERY_CONTENT_FLAG_ALL = CERT_QUERY_CONTENT_FLAG_CERT | CERT_QUERY_CONTENT_FLAG_CTL | CERT_QUERY_CONTENT_FLAG_CRL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_STORE | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CERT | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CTL | CERT_QUERY_CONTENT_FLAG_SERIALIZED_CRL | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_UNSIGNED | CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED | CERT_QUERY_CONTENT_FLAG_PKCS10 | CERT_QUERY_CONTENT_FLAG_PFX | CERT_QUERY_CONTENT_FLAG_CERT_PAIR, } [Flags] internal enum ExpectedFormatTypeFlags : int { CERT_QUERY_FORMAT_FLAG_BINARY = 1 << FormatType.CERT_QUERY_FORMAT_BINARY, CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_BASE64_ENCODED, CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED = 1 << FormatType.CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED, CERT_QUERY_FORMAT_FLAG_ALL = CERT_QUERY_FORMAT_FLAG_BINARY | CERT_QUERY_FORMAT_FLAG_BASE64_ENCODED | CERT_QUERY_FORMAT_FLAG_ASN_ASCII_HEX_ENCODED, } internal enum CertEncodingType : int { PKCS_7_ASN_ENCODING = 0x10000, X509_ASN_ENCODING = 0x00001, All = PKCS_7_ASN_ENCODING | X509_ASN_ENCODING, } internal enum ContentType : int { //encoded single certificate CERT_QUERY_CONTENT_CERT = 1, //encoded single CTL CERT_QUERY_CONTENT_CTL = 2, //encoded single CRL CERT_QUERY_CONTENT_CRL = 3, //serialized store CERT_QUERY_CONTENT_SERIALIZED_STORE = 4, //serialized single certificate CERT_QUERY_CONTENT_SERIALIZED_CERT = 5, //serialized single CTL CERT_QUERY_CONTENT_SERIALIZED_CTL = 6, //serialized single CRL CERT_QUERY_CONTENT_SERIALIZED_CRL = 7, //a PKCS#7 signed message CERT_QUERY_CONTENT_PKCS7_SIGNED = 8, //a PKCS#7 message, such as enveloped message. But it is not a signed message, CERT_QUERY_CONTENT_PKCS7_UNSIGNED = 9, //a PKCS7 signed message embedded in a file CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED = 10, //an encoded PKCS#10 CERT_QUERY_CONTENT_PKCS10 = 11, //an encoded PFX BLOB CERT_QUERY_CONTENT_PFX = 12, //an encoded CertificatePair (contains forward and/or reverse cross certs) CERT_QUERY_CONTENT_CERT_PAIR = 13, //an encoded PFX BLOB, which was loaded to phCertStore CERT_QUERY_CONTENT_PFX_AND_LOAD = 14, } internal enum FormatType : int { CERT_QUERY_FORMAT_BINARY = 1, CERT_QUERY_FORMAT_BASE64_ENCODED = 2, CERT_QUERY_FORMAT_ASN_ASCII_HEX_ENCODED = 3, } // CRYPTOAPI_BLOB has many typedef aliases in the C++ world (CERT_BLOB, DATA_BLOB, etc.) We'll just stick to one name here. [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPTOAPI_BLOB { public CRYPTOAPI_BLOB(int cbData, byte* pbData) { this.cbData = cbData; this.pbData = pbData; } public int cbData; public byte* pbData; public byte[] ToByteArray() { if (cbData == 0) { return Array.Empty<byte>(); } byte[] array = new byte[cbData]; Marshal.Copy((IntPtr)pbData, array, 0, cbData); return array; } } internal enum CertContextPropId : int { CERT_KEY_PROV_INFO_PROP_ID = 2, CERT_SHA1_HASH_PROP_ID = 3, CERT_KEY_CONTEXT_PROP_ID = 5, CERT_FRIENDLY_NAME_PROP_ID = 11, CERT_ARCHIVED_PROP_ID = 19, CERT_KEY_IDENTIFIER_PROP_ID = 20, CERT_PUBKEY_ALG_PARA_PROP_ID = 22, CERT_NCRYPT_KEY_HANDLE_PROP_ID = 78, CERT_CLR_DELETE_KEY_PROP_ID = 125, } [Flags] internal enum CertSetPropertyFlags : int { CERT_SET_PROPERTY_INHIBIT_PERSIST_FLAG = 0x40000000, None = 0x00000000, } internal enum CertNameType : int { CERT_NAME_EMAIL_TYPE = 1, CERT_NAME_RDN_TYPE = 2, CERT_NAME_ATTR_TYPE = 3, CERT_NAME_SIMPLE_DISPLAY_TYPE = 4, CERT_NAME_FRIENDLY_DISPLAY_TYPE = 5, CERT_NAME_DNS_TYPE = 6, CERT_NAME_URL_TYPE = 7, CERT_NAME_UPN_TYPE = 8, } [Flags] internal enum CertNameFlags : int { None = 0x00000000, CERT_NAME_ISSUER_FLAG = 0x00000001, } internal enum CertNameStringType : int { CERT_X500_NAME_STR = 3, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CONTEXT { public CertEncodingType dwCertEncodingType; public byte* pbCertEncoded; public int cbCertEncoded; public CERT_INFO* pCertInfo; public IntPtr hCertStore; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_INFO { public int dwVersion; public CRYPTOAPI_BLOB SerialNumber; public CRYPT_ALGORITHM_IDENTIFIER SignatureAlgorithm; public CRYPTOAPI_BLOB Issuer; public FILETIME NotBefore; public FILETIME NotAfter; public CRYPTOAPI_BLOB Subject; public CERT_PUBLIC_KEY_INFO SubjectPublicKeyInfo; public CRYPT_BIT_BLOB IssuerUniqueId; public CRYPT_BIT_BLOB SubjectUniqueId; public int cExtension; public CERT_EXTENSION* rgExtension; } [StructLayout(LayoutKind.Sequential)] internal struct CRYPT_ALGORITHM_IDENTIFIER { public IntPtr pszObjId; public CRYPTOAPI_BLOB Parameters; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_PUBLIC_KEY_INFO { public CRYPT_ALGORITHM_IDENTIFIER Algorithm; public CRYPT_BIT_BLOB PublicKey; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPT_BIT_BLOB { public int cbData; public byte* pbData; public int cUnusedBits; public byte[] ToByteArray() { if (cbData == 0) { return Array.Empty<byte>(); } byte[] array = new byte[cbData]; Marshal.Copy((IntPtr)pbData, array, 0, cbData); return array; } } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_EXTENSION { public IntPtr pszObjId; public int fCritical; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct FILETIME { private uint ftTimeLow; private uint ftTimeHigh; public DateTime ToDateTime() { long fileTime = (((long)ftTimeHigh) << 32) + ftTimeLow; return DateTime.FromFileTime(fileTime); } public static FILETIME FromDateTime(DateTime dt) { long fileTime = dt.ToFileTime(); unchecked { return new FILETIME() { ftTimeLow = (uint)fileTime, ftTimeHigh = (uint)(fileTime >> 32), }; } } } internal enum CertStoreProvider : int { CERT_STORE_PROV_MEMORY = 2, CERT_STORE_PROV_SYSTEM_W = 10, } [Flags] internal enum CertStoreFlags : int { CERT_STORE_NO_CRYPT_RELEASE_FLAG = 0x00000001, CERT_STORE_SET_LOCALIZED_NAME_FLAG = 0x00000002, CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG = 0x00000004, CERT_STORE_DELETE_FLAG = 0x00000010, CERT_STORE_UNSAFE_PHYSICAL_FLAG = 0x00000020, CERT_STORE_SHARE_STORE_FLAG = 0x00000040, CERT_STORE_SHARE_CONTEXT_FLAG = 0x00000080, CERT_STORE_MANIFOLD_FLAG = 0x00000100, CERT_STORE_ENUM_ARCHIVED_FLAG = 0x00000200, CERT_STORE_UPDATE_KEYID_FLAG = 0x00000400, CERT_STORE_BACKUP_RESTORE_FLAG = 0x00000800, CERT_STORE_READONLY_FLAG = 0x00008000, CERT_STORE_OPEN_EXISTING_FLAG = 0x00004000, CERT_STORE_CREATE_NEW_FLAG = 0x00002000, CERT_STORE_MAXIMUM_ALLOWED_FLAG = 0x00001000, CERT_SYSTEM_STORE_CURRENT_USER = 0x00010000, CERT_SYSTEM_STORE_LOCAL_MACHINE = 0x00020000, None = 0x00000000, } internal enum CertStoreAddDisposition : int { CERT_STORE_ADD_NEW = 1, CERT_STORE_ADD_USE_EXISTING = 2, CERT_STORE_ADD_REPLACE_EXISTING = 3, CERT_STORE_ADD_ALWAYS = 4, CERT_STORE_ADD_REPLACE_EXISTING_INHERIT_PROPERTIES = 5, CERT_STORE_ADD_NEWER = 6, CERT_STORE_ADD_NEWER_INHERIT_PROPERTIES = 7, } [Flags] internal enum PfxCertStoreFlags : int { CRYPT_EXPORTABLE = 0x00000001, CRYPT_USER_PROTECTED = 0x00000002, CRYPT_MACHINE_KEYSET = 0x00000020, CRYPT_USER_KEYSET = 0x00001000, PKCS12_PREFER_CNG_KSP = 0x00000100, PKCS12_ALWAYS_CNG_KSP = 0x00000200, PKCS12_ALLOW_OVERWRITE_KEY = 0x00004000, PKCS12_NO_PERSIST_KEY = 0x00008000, PKCS12_INCLUDE_EXTENDED_PROPERTIES = 0x00000010, None = 0x00000000, } internal enum CryptMessageParameterType : int { CMSG_SIGNER_COUNT_PARAM = 5, CMSG_SIGNER_INFO_PARAM = 6, } [StructLayout(LayoutKind.Sequential)] internal struct CMSG_SIGNER_INFO_Partial // This is not the full definition of CMSG_SIGNER_INFO. Only defining the part we use. { public int dwVersion; public CRYPTOAPI_BLOB Issuer; public CRYPTOAPI_BLOB SerialNumber; //... more fields follow ... } [Flags] internal enum CertFindFlags : int { None = 0x00000000, } internal enum CertFindType : int { CERT_FIND_SUBJECT_CERT = 0x000b0000, CERT_FIND_HASH = 0x00010000, CERT_FIND_SUBJECT_STR = 0x00080007, CERT_FIND_ISSUER_STR = 0x00080004, CERT_FIND_EXISTING = 0x000d0000, CERT_FIND_ANY = 0x00000000, } [Flags] internal enum PFXExportFlags : int { REPORT_NO_PRIVATE_KEY = 0x00000001, REPORT_NOT_ABLE_TO_EXPORT_PRIVATE_KEY = 0x00000002, EXPORT_PRIVATE_KEYS = 0x00000004, None = 0x00000000, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CRYPT_KEY_PROV_INFO { public char* pwszContainerName; public char* pwszProvName; public int dwProvType; public CryptAcquireContextFlags dwFlags; public int cProvParam; public IntPtr rgProvParam; public int dwKeySpec; } [Flags] internal enum CryptAcquireContextFlags : int { CRYPT_DELETEKEYSET = 0x00000010, CRYPT_MACHINE_KEYSET = 0x00000020, None = 0x00000000, } [Flags] internal enum CertNameStrTypeAndFlags : int { CERT_SIMPLE_NAME_STR = 1, CERT_OID_NAME_STR = 2, CERT_X500_NAME_STR = 3, CERT_NAME_STR_SEMICOLON_FLAG = 0x40000000, CERT_NAME_STR_NO_PLUS_FLAG = 0x20000000, CERT_NAME_STR_NO_QUOTING_FLAG = 0x10000000, CERT_NAME_STR_CRLF_FLAG = 0x08000000, CERT_NAME_STR_COMMA_FLAG = 0x04000000, CERT_NAME_STR_REVERSE_FLAG = 0x02000000, CERT_NAME_STR_DISABLE_IE4_UTF8_FLAG = 0x00010000, CERT_NAME_STR_ENABLE_T61_UNICODE_FLAG = 0x00020000, CERT_NAME_STR_ENABLE_UTF8_UNICODE_FLAG = 0x00040000, CERT_NAME_STR_FORCE_UTF8_DIR_STR_FLAG = 0x00080000, } internal enum FormatObjectType : int { None = 0, } internal enum FormatObjectStructType : int { X509_NAME = 7, } internal static class AlgId { public const int CALG_RSA_KEYX = 0xa400; public const int CALG_RSA_SIGN = 0x2400; public const int CALG_DSS_SIGN = 0x2200; public const int CALG_SHA1 = 0x8004; } [Flags] internal enum CryptDecodeObjectFlags : int { None = 0x00000000, } internal enum CryptDecodeObjectStructType : int { CNG_RSA_PUBLIC_KEY_BLOB = 72, X509_DSS_PUBLICKEY = 38, X509_DSS_PARAMETERS = 39, X509_KEY_USAGE = 14, X509_BASIC_CONSTRAINTS = 13, X509_BASIC_CONSTRAINTS2 = 15, X509_ENHANCED_KEY_USAGE = 36, X509_CERT_POLICIES = 16, X509_UNICODE_ANY_STRING = 24, X509_CERTIFICATE_TEMPLATE = 64, } [StructLayout(LayoutKind.Sequential)] internal struct CTL_USAGE { public int cUsageIdentifier; public IntPtr rgpszUsageIdentifier; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_USAGE_MATCH { public CertUsageMatchType dwType; public CTL_USAGE Usage; } internal enum CertUsageMatchType : int { USAGE_MATCH_TYPE_AND = 0x00000000, USAGE_MATCH_TYPE_OR = 0x00000001, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_PARA { public int cbSize; public CERT_USAGE_MATCH RequestedUsage; public CERT_USAGE_MATCH RequestedIssuancePolicy; public int dwUrlRetrievalTimeout; public int fCheckRevocationFreshnessTime; public int dwRevocationFreshnessTime; public FILETIME* pftCacheResync; public int pStrongSignPara; public int dwStrongSignFlags; } [Flags] internal enum CertChainFlags : int { None = 0x00000000, CERT_CHAIN_REVOCATION_CHECK_END_CERT = 0x10000000, CERT_CHAIN_REVOCATION_CHECK_CHAIN = 0x20000000, CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT = 0x40000000, CERT_CHAIN_REVOCATION_CHECK_CACHE_ONLY = unchecked((int)0x80000000), } internal enum ChainEngine : int { HCCE_CURRENT_USER = 0x0, HCCE_LOCAL_MACHINE = 0x1, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_DSS_PARAMETERS { public CRYPTOAPI_BLOB p; public CRYPTOAPI_BLOB q; public CRYPTOAPI_BLOB g; } internal enum PubKeyMagic : int { DSS_MAGIC = 0x31535344, } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_BASIC_CONSTRAINTS_INFO { public CRYPT_BIT_BLOB SubjectType; public int fPathLenConstraint; public int dwPathLenConstraint; public int cSubtreesConstraint; public CRYPTOAPI_BLOB* rgSubtreesConstraint; // PCERT_NAME_BLOB // SubjectType.pbData[0] can contain a CERT_CA_SUBJECT_FLAG that when set indicates that the certificate's subject can act as a CA public const byte CERT_CA_SUBJECT_FLAG = 0x80; }; [StructLayout(LayoutKind.Sequential)] internal struct CERT_BASIC_CONSTRAINTS2_INFO { public int fCA; public int fPathLenConstraint; public int dwPathLenConstraint; }; [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_ENHKEY_USAGE { public int cUsageIdentifier; public IntPtr* rgpszUsageIdentifier; // LPSTR* } internal enum CertStoreSaveAs : int { CERT_STORE_SAVE_AS_STORE = 1, CERT_STORE_SAVE_AS_PKCS7 = 2, } internal enum CertStoreSaveTo : int { CERT_STORE_SAVE_TO_MEMORY = 2, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_POLICY_INFO { public IntPtr pszPolicyIdentifier; public int cPolicyQualifier; public IntPtr rgPolicyQualifier; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_POLICIES_INFO { public int cPolicyInfo; public CERT_POLICY_INFO* rgPolicyInfo; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_NAME_VALUE { public int dwValueType; public CRYPTOAPI_BLOB Value; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_TEMPLATE_EXT { public IntPtr pszObjId; public int dwMajorVersion; public int fMinorVersion; public int dwMinorVersion; } [Flags] internal enum CertControlStoreFlags : int { None = 0x00000000, } internal enum CertControlStoreType : int { CERT_STORE_CTRL_AUTO_RESYNC = 4, } [Flags] internal enum CertTrustErrorStatus : int { CERT_TRUST_NO_ERROR = 0x00000000, CERT_TRUST_IS_NOT_TIME_VALID = 0x00000001, CERT_TRUST_IS_NOT_TIME_NESTED = 0x00000002, CERT_TRUST_IS_REVOKED = 0x00000004, CERT_TRUST_IS_NOT_SIGNATURE_VALID = 0x00000008, CERT_TRUST_IS_NOT_VALID_FOR_USAGE = 0x00000010, CERT_TRUST_IS_UNTRUSTED_ROOT = 0x00000020, CERT_TRUST_REVOCATION_STATUS_UNKNOWN = 0x00000040, CERT_TRUST_IS_CYCLIC = 0x00000080, CERT_TRUST_INVALID_EXTENSION = 0x00000100, CERT_TRUST_INVALID_POLICY_CONSTRAINTS = 0x00000200, CERT_TRUST_INVALID_BASIC_CONSTRAINTS = 0x00000400, CERT_TRUST_INVALID_NAME_CONSTRAINTS = 0x00000800, CERT_TRUST_HAS_NOT_SUPPORTED_NAME_CONSTRAINT = 0x00001000, CERT_TRUST_HAS_NOT_DEFINED_NAME_CONSTRAINT = 0x00002000, CERT_TRUST_HAS_NOT_PERMITTED_NAME_CONSTRAINT = 0x00004000, CERT_TRUST_HAS_EXCLUDED_NAME_CONSTRAINT = 0x00008000, CERT_TRUST_IS_OFFLINE_REVOCATION = 0x01000000, CERT_TRUST_NO_ISSUANCE_CHAIN_POLICY = 0x02000000, CERT_TRUST_IS_EXPLICIT_DISTRUST = 0x04000000, CERT_TRUST_HAS_NOT_SUPPORTED_CRITICAL_EXT = 0x08000000, CERT_TRUST_HAS_WEAK_SIGNATURE = 0x00100000, // These can be applied to chains only CERT_TRUST_IS_PARTIAL_CHAIN = 0x00010000, CERT_TRUST_CTL_IS_NOT_TIME_VALID = 0x00020000, CERT_TRUST_CTL_IS_NOT_SIGNATURE_VALID = 0x00040000, CERT_TRUST_CTL_IS_NOT_VALID_FOR_USAGE = 0x00080000, } [Flags] internal enum CertTrustInfoStatus : int { // These can be applied to certificates only CERT_TRUST_HAS_EXACT_MATCH_ISSUER = 0x00000001, CERT_TRUST_HAS_KEY_MATCH_ISSUER = 0x00000002, CERT_TRUST_HAS_NAME_MATCH_ISSUER = 0x00000004, CERT_TRUST_IS_SELF_SIGNED = 0x00000008, // These can be applied to certificates and chains CERT_TRUST_HAS_PREFERRED_ISSUER = 0x00000100, CERT_TRUST_HAS_ISSUANCE_CHAIN_POLICY = 0x00000200, CERT_TRUST_HAS_VALID_NAME_CONSTRAINTS = 0x00000400, // These can be applied to chains only CERT_TRUST_IS_COMPLEX_CHAIN = 0x00010000, } [StructLayout(LayoutKind.Sequential)] internal struct CERT_TRUST_STATUS { public CertTrustErrorStatus dwErrorStatus; public CertTrustInfoStatus dwInfoStatus; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_ELEMENT { public int cbSize; public CERT_CONTEXT* pCertContext; public CERT_TRUST_STATUS TrustStatus; public IntPtr pRevocationInfo; public IntPtr pIssuanceUsage; public IntPtr pApplicationUsage; public IntPtr pwszExtendedErrorInfo; } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_SIMPLE_CHAIN { public int cbSize; public CERT_TRUST_STATUS TrustStatus; public int cElement; public CERT_CHAIN_ELEMENT** rgpElement; public IntPtr pTrustListInfo; // fHasRevocationFreshnessTime is only set if we are able to retrieve // revocation information for all elements checked for revocation. // For a CRL its CurrentTime - ThisUpdate. // // dwRevocationFreshnessTime is the largest time across all elements // checked. public int fHasRevocationFreshnessTime; public int dwRevocationFreshnessTime; // seconds } [StructLayout(LayoutKind.Sequential)] internal unsafe struct CERT_CHAIN_CONTEXT { public int cbSize; public CERT_TRUST_STATUS TrustStatus; public int cChain; public CERT_SIMPLE_CHAIN** rgpChain; // Following is returned when CERT_CHAIN_RETURN_LOWER_QUALITY_CONTEXTS // is set in dwFlags public int cLowerQualityChainContext; public CERT_CHAIN_CONTEXT** rgpLowerQualityChainContext; // fHasRevocationFreshnessTime is only set if we are able to retrieve // revocation information for all elements checked for revocation. // For a CRL its CurrentTime - ThisUpdate. // // dwRevocationFreshnessTime is the largest time across all elements // checked. public int fHasRevocationFreshnessTime; public int dwRevocationFreshnessTime; // seconds // Flags passed when created via CertGetCertificateChain public int dwCreateFlags; // Following is updated with unique Id when the chain context is logged. public Guid ChainId; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_POLICY_PARA { public int cbSize; public int dwFlags; public IntPtr pvExtraPolicyPara; } [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_POLICY_STATUS { public int cbSize; public int dwError; public IntPtr lChainIndex; public IntPtr lElementIndex; public IntPtr pvExtraPolicyStatus; } internal enum ChainPolicy : int { // Predefined verify chain policies CERT_CHAIN_POLICY_BASE = 1, } internal enum CryptAcquireFlags : int { CRYPT_ACQUIRE_ONLY_NCRYPT_KEY_FLAG = 0x00040000, } [Flags] internal enum ChainEngineConfigFlags : int { CERT_CHAIN_CACHE_END_CERT = 0x00000001, CERT_CHAIN_CACHE_ONLY_URL_RETRIEVAL = 0x00000004, CERT_CHAIN_USE_LOCAL_MACHINE_STORE = 0x00000008, CERT_CHAIN_ENABLE_CACHE_AUTO_UPDATE = 0x00000010, CERT_CHAIN_ENABLE_SHARE_STORE = 0x00000020, CERT_CHAIN_DISABLE_AIA = 0x00002000, } // Windows 7 definition of the struct [StructLayout(LayoutKind.Sequential)] internal struct CERT_CHAIN_ENGINE_CONFIG { public int cbSize; public IntPtr hRestrictedRoot; public IntPtr hRestrictedTrust; public IntPtr hRestrictedOther; public int cAdditionalStore; public IntPtr rghAdditionalStore; public ChainEngineConfigFlags dwFlags; public int dwUrlRetrievalTimeout; public int MaximumCachedCertificates; public int CycleDetectionModulus; public IntPtr hExclusiveRoot; public IntPtr hExclusiveTrustedPeople; } }
// 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 XorInt64() { var test = new SimpleBinaryOpTest__XorInt64(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__XorInt64 { private const int VectorSize = 32; private const int ElementCount = VectorSize / sizeof(Int64); private static Int64[] _data1 = new Int64[ElementCount]; private static Int64[] _data2 = new Int64[ElementCount]; private static Vector256<Int64> _clsVar1; private static Vector256<Int64> _clsVar2; private Vector256<Int64> _fld1; private Vector256<Int64> _fld2; private SimpleBinaryOpTest__DataTable<Int64> _dataTable; static SimpleBinaryOpTest__XorInt64() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar1), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar2), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__XorInt64() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld1), ref Unsafe.As<Int64, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld2), ref Unsafe.As<Int64, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (long)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (long)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int64>(_data1, _data2, new Int64[ElementCount], VectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.Xor( Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.Xor( Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.Xor( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.Xor), new Type[] { typeof(Vector256<Int64>), typeof(Vector256<Int64>) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)), Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.Xor( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector256<Int64>>(_dataTable.inArray2Ptr); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Avx.LoadVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray1Ptr)); var right = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArray2Ptr)); var result = Avx2.Xor(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__XorInt64(); var result = Avx2.Xor(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Avx2.Xor(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> left, Vector256<Int64> right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int64[] inArray1 = new Int64[ElementCount]; Int64[] inArray2 = new Int64[ElementCount]; Int64[] outArray = new Int64[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int64[] left, Int64[] right, Int64[] result, [CallerMemberName] string method = "") { if ((long)(left[0] ^ right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((long)(left[i] ^ right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Avx2)}.{nameof(Avx2.Xor)}<Int64>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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.Globalization; using System.IO; using System.Security; using System.Text; using System.Threading; using Microsoft.Win32.SafeHandles; using Internal.Win32; using Internal.Runtime.CompilerServices; using REG_TZI_FORMAT = Interop.Kernel32.REG_TZI_FORMAT; using TIME_ZONE_INFORMATION = Interop.Kernel32.TIME_ZONE_INFORMATION; using TIME_DYNAMIC_ZONE_INFORMATION = Interop.Kernel32.TIME_DYNAMIC_ZONE_INFORMATION; namespace System { public sealed partial class TimeZoneInfo { // registry constants for the 'Time Zones' hive // private const string TimeZonesRegistryHive = @"SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones"; private const string DisplayValue = "Display"; private const string DaylightValue = "Dlt"; private const string StandardValue = "Std"; private const string MuiDisplayValue = "MUI_Display"; private const string MuiDaylightValue = "MUI_Dlt"; private const string MuiStandardValue = "MUI_Std"; private const string TimeZoneInfoValue = "TZI"; private const string FirstEntryValue = "FirstEntry"; private const string LastEntryValue = "LastEntry"; private const int MaxKeyLength = 255; private sealed partial class CachedData { private static TimeZoneInfo GetCurrentOneYearLocal() { // load the data from the OS TIME_ZONE_INFORMATION timeZoneInformation; uint result = Interop.Kernel32.GetTimeZoneInformation(out timeZoneInformation); return result == Interop.Kernel32.TIME_ZONE_ID_INVALID ? CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId) : GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled: false); } private volatile OffsetAndRule _oneYearLocalFromUtc; public OffsetAndRule GetOneYearLocalFromUtc(int year) { OffsetAndRule oneYearLocFromUtc = _oneYearLocalFromUtc; if (oneYearLocFromUtc == null || oneYearLocFromUtc.Year != year) { TimeZoneInfo currentYear = GetCurrentOneYearLocal(); AdjustmentRule rule = currentYear._adjustmentRules == null ? null : currentYear._adjustmentRules[0]; oneYearLocFromUtc = new OffsetAndRule(year, currentYear.BaseUtcOffset, rule); _oneYearLocalFromUtc = oneYearLocFromUtc; } return oneYearLocFromUtc; } } private sealed class OffsetAndRule { public readonly int Year; public readonly TimeSpan Offset; public readonly AdjustmentRule Rule; public OffsetAndRule(int year, TimeSpan offset, AdjustmentRule rule) { Year = year; Offset = offset; Rule = rule; } } /// <summary> /// Returns a cloned array of AdjustmentRule objects /// </summary> public AdjustmentRule[] GetAdjustmentRules() { if (_adjustmentRules == null) { return Array.Empty<AdjustmentRule>(); } return (AdjustmentRule[])_adjustmentRules.Clone(); } private static void PopulateAllSystemTimeZones(CachedData cachedData) { Debug.Assert(Monitor.IsEntered(cachedData)); using (RegistryKey reg = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false)) { if (reg != null) { foreach (string keyName in reg.GetSubKeyNames()) { TimeZoneInfo value; Exception ex; TryGetTimeZone(keyName, false, out value, out ex, cachedData); // populate the cache } } } } private TimeZoneInfo(in TIME_ZONE_INFORMATION zone, bool dstDisabled) { string standardName = zone.GetStandardName(); if (standardName.Length == 0) { _id = LocalId; // the ID must contain at least 1 character - initialize _id to "Local" } else { _id = standardName; } _baseUtcOffset = new TimeSpan(0, -(zone.Bias), 0); if (!dstDisabled) { // only create the adjustment rule if DST is enabled REG_TZI_FORMAT regZone = new REG_TZI_FORMAT(zone); AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(regZone, DateTime.MinValue.Date, DateTime.MaxValue.Date, zone.Bias); if (rule != null) { _adjustmentRules = new[] { rule }; } } ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime); _displayName = standardName; _standardDisplayName = standardName; _daylightDisplayName = zone.GetDaylightName(); } /// <summary> /// Helper function to check if the current TimeZoneInformation struct does not support DST. /// This check returns true when the DaylightDate == StandardDate. /// This check is only meant to be used for "Local". /// </summary> private static bool CheckDaylightSavingTimeNotSupported(in TIME_ZONE_INFORMATION timeZone) => timeZone.DaylightDate.Equals(timeZone.StandardDate); /// <summary> /// Converts a REG_TZI_FORMAT struct to an AdjustmentRule. /// </summary> private static AdjustmentRule CreateAdjustmentRuleFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, DateTime startDate, DateTime endDate, int defaultBaseUtcOffset) { bool supportsDst = timeZoneInformation.StandardDate.Month != 0; if (!supportsDst) { if (timeZoneInformation.Bias == defaultBaseUtcOffset) { // this rule will not contain any information to be used to adjust dates. just ignore it return null; } return AdjustmentRule.CreateAdjustmentRule( startDate, endDate, TimeSpan.Zero, // no daylight saving transition TransitionTime.CreateFixedDateRule(DateTime.MinValue, 1, 1), TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(1), 1, 1), new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), // Bias delta is all what we need from this rule noDaylightTransitions: false); } // // Create an AdjustmentRule with TransitionTime objects // TransitionTime daylightTransitionStart; if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionStart, readStartDate: true)) { return null; } TransitionTime daylightTransitionEnd; if (!TransitionTimeFromTimeZoneInformation(timeZoneInformation, out daylightTransitionEnd, readStartDate: false)) { return null; } if (daylightTransitionStart.Equals(daylightTransitionEnd)) { // this happens when the time zone does support DST but the OS has DST disabled return null; } return AdjustmentRule.CreateAdjustmentRule( startDate, endDate, new TimeSpan(0, -timeZoneInformation.DaylightBias, 0), daylightTransitionStart, daylightTransitionEnd, new TimeSpan(0, defaultBaseUtcOffset - timeZoneInformation.Bias, 0), noDaylightTransitions: false); } /// <summary> /// Helper function that searches the registry for a time zone entry /// that matches the TimeZoneInformation struct. /// </summary> private static string FindIdFromTimeZoneInformation(in TIME_ZONE_INFORMATION timeZone, out bool dstDisabled) { dstDisabled = false; using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive, writable: false)) { if (key == null) { return null; } foreach (string keyName in key.GetSubKeyNames()) { if (TryCompareTimeZoneInformationToRegistry(timeZone, keyName, out dstDisabled)) { return keyName; } } } return null; } /// <summary> /// Helper function for retrieving the local system time zone. /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException. /// Assumes cachedData lock is taken. /// </summary> /// <returns>A new TimeZoneInfo instance.</returns> private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData) { Debug.Assert(Monitor.IsEntered(cachedData)); // // Try using the "kernel32!GetDynamicTimeZoneInformation" API to get the "id" // var dynamicTimeZoneInformation = new TIME_DYNAMIC_ZONE_INFORMATION(); // call kernel32!GetDynamicTimeZoneInformation... uint result = Interop.Kernel32.GetDynamicTimeZoneInformation(out dynamicTimeZoneInformation); if (result == Interop.Kernel32.TIME_ZONE_ID_INVALID) { // return a dummy entry return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId); } // check to see if we can use the key name returned from the API call string dynamicTimeZoneKeyName = dynamicTimeZoneInformation.GetTimeZoneKeyName(); if (dynamicTimeZoneKeyName.Length != 0) { TimeZoneInfo zone; Exception ex; if (TryGetTimeZone(dynamicTimeZoneKeyName, dynamicTimeZoneInformation.DynamicDaylightTimeDisabled != 0, out zone, out ex, cachedData) == TimeZoneInfoResult.Success) { // successfully loaded the time zone from the registry return zone; } } var timeZoneInformation = new TIME_ZONE_INFORMATION(dynamicTimeZoneInformation); // the key name was not returned or it pointed to a bogus entry - search for the entry ourselves string id = FindIdFromTimeZoneInformation(timeZoneInformation, out bool dstDisabled); if (id != null) { TimeZoneInfo zone; Exception ex; if (TryGetTimeZone(id, dstDisabled, out zone, out ex, cachedData) == TimeZoneInfoResult.Success) { // successfully loaded the time zone from the registry return zone; } } // We could not find the data in the registry. Fall back to using // the data from the Win32 API return GetLocalTimeZoneFromWin32Data(timeZoneInformation, dstDisabled); } /// <summary> /// Helper function used by 'GetLocalTimeZone()' - this function wraps a bunch of /// try/catch logic for handling the TimeZoneInfo private constructor that takes /// a TIME_ZONE_INFORMATION structure. /// </summary> private static TimeZoneInfo GetLocalTimeZoneFromWin32Data(in TIME_ZONE_INFORMATION timeZoneInformation, bool dstDisabled) { // first try to create the TimeZoneInfo with the original 'dstDisabled' flag try { return new TimeZoneInfo(timeZoneInformation, dstDisabled); } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } // if 'dstDisabled' was false then try passing in 'true' as a last ditch effort if (!dstDisabled) { try { return new TimeZoneInfo(timeZoneInformation, dstDisabled: true); } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } } // the data returned from Windows is completely bogus; return a dummy entry return CreateCustomTimeZone(LocalId, TimeSpan.Zero, LocalId, LocalId); } /// <summary> /// Helper function for retrieving a TimeZoneInfo object by time_zone_name. /// This function wraps the logic necessary to keep the private /// SystemTimeZones cache in working order /// /// This function will either return a valid TimeZoneInfo instance or /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'. /// </summary> public static TimeZoneInfo FindSystemTimeZoneById(string id) { // Special case for Utc as it will not exist in the dictionary with the rest // of the system time zones. There is no need to do this check for Local.Id // since Local is a real time zone that exists in the dictionary cache if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase)) { return Utc; } if (id == null) { throw new ArgumentNullException(nameof(id)); } if (id.Length == 0 || id.Length > MaxKeyLength || id.Contains('\0')) { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); } TimeZoneInfo value; Exception e; TimeZoneInfoResult result; CachedData cachedData = s_cachedData; lock (cachedData) { result = TryGetTimeZone(id, false, out value, out e, cachedData); } if (result == TimeZoneInfoResult.Success) { return value; } else if (result == TimeZoneInfoResult.InvalidTimeZoneException) { throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidRegistryData, id), e); } else if (result == TimeZoneInfoResult.SecurityException) { throw new SecurityException(SR.Format(SR.Security_CannotReadRegistryData, id), e); } else { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e); } } // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst) { bool isDaylightSavings = false; isAmbiguousLocalDst = false; TimeSpan baseOffset; int timeYear = time.Year; OffsetAndRule match = s_cachedData.GetOneYearLocalFromUtc(timeYear); baseOffset = match.Offset; if (match.Rule != null) { baseOffset = baseOffset + match.Rule.BaseUtcOffsetDelta; if (match.Rule.HasDaylightSaving) { isDaylightSavings = GetIsDaylightSavingsFromUtc(time, timeYear, match.Offset, match.Rule, null, out isAmbiguousLocalDst, Local); baseOffset += (isDaylightSavings ? match.Rule.DaylightDelta : TimeSpan.Zero /* FUTURE: rule.StandardDelta */); } } return baseOffset; } /// <summary> /// Converts a REG_TZI_FORMAT struct to a TransitionTime /// - When the argument 'readStart' is true the corresponding daylightTransitionTimeStart field is read /// - When the argument 'readStart' is false the corresponding dayightTransitionTimeEnd field is read /// </summary> private static bool TransitionTimeFromTimeZoneInformation(in REG_TZI_FORMAT timeZoneInformation, out TransitionTime transitionTime, bool readStartDate) { // // SYSTEMTIME - // // If the time zone does not support daylight saving time or if the caller needs // to disable daylight saving time, the wMonth member in the SYSTEMTIME structure // must be zero. If this date is specified, the DaylightDate value in the // TIME_ZONE_INFORMATION structure must also be specified. Otherwise, the system // assumes the time zone data is invalid and no changes will be applied. // bool supportsDst = (timeZoneInformation.StandardDate.Month != 0); if (!supportsDst) { transitionTime = default; return false; } // // SYSTEMTIME - // // * FixedDateRule - // If the Year member is not zero, the transition date is absolute; it will only occur one time // // * FloatingDateRule - // To select the correct day in the month, set the Year member to zero, the Hour and Minute // members to the transition time, the DayOfWeek member to the appropriate weekday, and the // Day member to indicate the occurence of the day of the week within the month (first through fifth). // // Using this notation, specify the 2:00a.m. on the first Sunday in April as follows: // Hour = 2, // Month = 4, // DayOfWeek = 0, // Day = 1. // // Specify 2:00a.m. on the last Thursday in October as follows: // Hour = 2, // Month = 10, // DayOfWeek = 4, // Day = 5. // if (readStartDate) { // // read the "daylightTransitionStart" // if (timeZoneInformation.DaylightDate.Year == 0) { transitionTime = TransitionTime.CreateFloatingDateRule( new DateTime(1, /* year */ 1, /* month */ 1, /* day */ timeZoneInformation.DaylightDate.Hour, timeZoneInformation.DaylightDate.Minute, timeZoneInformation.DaylightDate.Second, timeZoneInformation.DaylightDate.Milliseconds), timeZoneInformation.DaylightDate.Month, timeZoneInformation.DaylightDate.Day, /* Week 1-5 */ (DayOfWeek)timeZoneInformation.DaylightDate.DayOfWeek); } else { transitionTime = TransitionTime.CreateFixedDateRule( new DateTime(1, /* year */ 1, /* month */ 1, /* day */ timeZoneInformation.DaylightDate.Hour, timeZoneInformation.DaylightDate.Minute, timeZoneInformation.DaylightDate.Second, timeZoneInformation.DaylightDate.Milliseconds), timeZoneInformation.DaylightDate.Month, timeZoneInformation.DaylightDate.Day); } } else { // // read the "daylightTransitionEnd" // if (timeZoneInformation.StandardDate.Year == 0) { transitionTime = TransitionTime.CreateFloatingDateRule( new DateTime(1, /* year */ 1, /* month */ 1, /* day */ timeZoneInformation.StandardDate.Hour, timeZoneInformation.StandardDate.Minute, timeZoneInformation.StandardDate.Second, timeZoneInformation.StandardDate.Milliseconds), timeZoneInformation.StandardDate.Month, timeZoneInformation.StandardDate.Day, /* Week 1-5 */ (DayOfWeek)timeZoneInformation.StandardDate.DayOfWeek); } else { transitionTime = TransitionTime.CreateFixedDateRule( new DateTime(1, /* year */ 1, /* month */ 1, /* day */ timeZoneInformation.StandardDate.Hour, timeZoneInformation.StandardDate.Minute, timeZoneInformation.StandardDate.Second, timeZoneInformation.StandardDate.Milliseconds), timeZoneInformation.StandardDate.Month, timeZoneInformation.StandardDate.Day); } } return true; } /// <summary> /// Helper function that takes: /// 1. A string representing a time_zone_name registry key name. /// 2. A REG_TZI_FORMAT struct containing the default rule. /// 3. An AdjustmentRule[] out-parameter. /// </summary> private static bool TryCreateAdjustmentRules(string id, in REG_TZI_FORMAT defaultTimeZoneInformation, out AdjustmentRule[] rules, out Exception e, int defaultBaseUtcOffset) { rules = null; e = null; try { // Optional, Dynamic Time Zone Registry Data // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- // // HKLM // Software // Microsoft // Windows NT // CurrentVersion // Time Zones // <time_zone_name> // Dynamic DST // * "FirstEntry" REG_DWORD "1980" // First year in the table. If the current year is less than this value, // this entry will be used for DST boundaries // * "LastEntry" REG_DWORD "2038" // Last year in the table. If the current year is greater than this value, // this entry will be used for DST boundaries" // * "<year1>" REG_BINARY REG_TZI_FORMAT // * "<year2>" REG_BINARY REG_TZI_FORMAT // * "<year3>" REG_BINARY REG_TZI_FORMAT // using (RegistryKey dynamicKey = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id + "\\Dynamic DST", writable: false)) { if (dynamicKey == null) { AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation( defaultTimeZoneInformation, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); if (rule != null) { rules = new[] { rule }; } return true; } // // loop over all of the "<time_zone_name>\Dynamic DST" hive entries // // read FirstEntry {MinValue - (year1, 12, 31)} // read MiddleEntry {(yearN, 1, 1) - (yearN, 12, 31)} // read LastEntry {(yearN, 1, 1) - MaxValue } // read the FirstEntry and LastEntry key values (ex: "1980", "2038") int first = (int)dynamicKey.GetValue(FirstEntryValue, -1); int last = (int)dynamicKey.GetValue(LastEntryValue, -1); if (first == -1 || last == -1 || first > last) { return false; } // read the first year entry REG_TZI_FORMAT dtzi; if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, first.ToString(CultureInfo.InvariantCulture), out dtzi)) { return false; } if (first == last) { // there is just 1 dynamic rule for this time zone. AdjustmentRule rule = CreateAdjustmentRuleFromTimeZoneInformation(dtzi, DateTime.MinValue.Date, DateTime.MaxValue.Date, defaultBaseUtcOffset); if (rule != null) { rules = new[] { rule }; } return true; } List<AdjustmentRule> rulesList = new List<AdjustmentRule>(1); // there are more than 1 dynamic rules for this time zone. AdjustmentRule firstRule = CreateAdjustmentRuleFromTimeZoneInformation( dtzi, DateTime.MinValue.Date, // MinValue new DateTime(first, 12, 31), // December 31, <FirstYear> defaultBaseUtcOffset); if (firstRule != null) { rulesList.Add(firstRule); } // read the middle year entries for (int i = first + 1; i < last; i++) { if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, i.ToString(CultureInfo.InvariantCulture), out dtzi)) { return false; } AdjustmentRule middleRule = CreateAdjustmentRuleFromTimeZoneInformation( dtzi, new DateTime(i, 1, 1), // January 01, <Year> new DateTime(i, 12, 31), // December 31, <Year> defaultBaseUtcOffset); if (middleRule != null) { rulesList.Add(middleRule); } } // read the last year entry if (!TryGetTimeZoneEntryFromRegistry(dynamicKey, last.ToString(CultureInfo.InvariantCulture), out dtzi)) { return false; } AdjustmentRule lastRule = CreateAdjustmentRuleFromTimeZoneInformation( dtzi, new DateTime(last, 1, 1), // January 01, <LastYear> DateTime.MaxValue.Date, // MaxValue defaultBaseUtcOffset); if (lastRule != null) { rulesList.Add(lastRule); } // convert the List to an AdjustmentRule array if (rulesList.Count != 0) { rules = rulesList.ToArray(); } } // end of: using (RegistryKey dynamicKey... } catch (InvalidCastException ex) { // one of the RegistryKey.GetValue calls could not be cast to an expected value type e = ex; return false; } catch (ArgumentOutOfRangeException ex) { e = ex; return false; } catch (ArgumentException ex) { e = ex; return false; } return true; } private static unsafe bool TryGetTimeZoneEntryFromRegistry(RegistryKey key, string name, out REG_TZI_FORMAT dtzi) { if (!(key.GetValue(name, null) is byte[] regValue) || regValue.Length != sizeof(REG_TZI_FORMAT)) { dtzi = default; return false; } fixed (byte * pBytes = &regValue[0]) dtzi = *(REG_TZI_FORMAT *)pBytes; return true; } /// <summary> /// Helper function that compares the StandardBias and StandardDate portion a /// TimeZoneInformation struct to a time zone registry entry. /// </summary> private static bool TryCompareStandardDate(in TIME_ZONE_INFORMATION timeZone, in REG_TZI_FORMAT registryTimeZoneInfo) => timeZone.Bias == registryTimeZoneInfo.Bias && timeZone.StandardBias == registryTimeZoneInfo.StandardBias && timeZone.StandardDate.Equals(registryTimeZoneInfo.StandardDate); /// <summary> /// Helper function that compares a TimeZoneInformation struct to a time zone registry entry. /// </summary> private static bool TryCompareTimeZoneInformationToRegistry(in TIME_ZONE_INFORMATION timeZone, string id, out bool dstDisabled) { dstDisabled = false; using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false)) { if (key == null) { return false; } REG_TZI_FORMAT registryTimeZoneInfo; if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out registryTimeZoneInfo)) { return false; } // // first compare the bias and standard date information between the data from the Win32 API // and the data from the registry... // bool result = TryCompareStandardDate(timeZone, registryTimeZoneInfo); if (!result) { return false; } result = dstDisabled || CheckDaylightSavingTimeNotSupported(timeZone) || // // since Daylight Saving Time is not "disabled", do a straight comparision between // the Win32 API data and the registry data ... // (timeZone.DaylightBias == registryTimeZoneInfo.DaylightBias && timeZone.DaylightDate.Equals(registryTimeZoneInfo.DaylightDate)); // Finally compare the "StandardName" string value... // // we do not compare "DaylightName" as this TimeZoneInformation field may contain // either "StandardName" or "DaylightName" depending on the time of year and current machine settings // if (result) { string registryStandardName = key.GetValue(StandardValue, string.Empty) as string; result = string.Equals(registryStandardName, timeZone.GetStandardName(), StringComparison.Ordinal); } return result; } } /// <summary> /// Helper function for retrieving a localized string resource via MUI. /// The function expects a string in the form: "@resource.dll, -123" /// /// "resource.dll" is a language-neutral portable executable (LNPE) file in /// the %windir%\system32 directory. The OS is queried to find the best-fit /// localized resource file for this LNPE (ex: %windir%\system32\en-us\resource.dll.mui). /// If a localized resource file exists, we LoadString resource ID "123" and /// return it to our caller. /// </summary> private static string TryGetLocalizedNameByMuiNativeResource(string resource) { if (string.IsNullOrEmpty(resource)) { return string.Empty; } // parse "@tzres.dll, -100" // // filePath = "C:\Windows\System32\tzres.dll" // resourceId = -100 // string[] resources = resource.Split(','); if (resources.Length != 2) { return string.Empty; } string filePath; int resourceId; // get the path to Windows\System32 string system32 = Environment.SystemDirectory; // trim the string "@tzres.dll" => "tzres.dll" string tzresDll = resources[0].TrimStart('@'); try { filePath = Path.Combine(system32, tzresDll); } catch (ArgumentException) { // there were probably illegal characters in the path return string.Empty; } if (!int.TryParse(resources[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out resourceId)) { return string.Empty; } resourceId = -resourceId; try { unsafe { char* fileMuiPath = stackalloc char[Interop.Kernel32.MAX_PATH]; int fileMuiPathLength = Interop.Kernel32.MAX_PATH; int languageLength = 0; long enumerator = 0; bool succeeded = Interop.Kernel32.GetFileMUIPath( Interop.Kernel32.MUI_PREFERRED_UI_LANGUAGES, filePath, null /* language */, ref languageLength, fileMuiPath, ref fileMuiPathLength, ref enumerator); return succeeded ? TryGetLocalizedNameByNativeResource(new string(fileMuiPath, 0, fileMuiPathLength), resourceId) : string.Empty; } } catch (EntryPointNotFoundException) { return string.Empty; } } /// <summary> /// Helper function for retrieving a localized string resource via a native resource DLL. /// The function expects a string in the form: "C:\Windows\System32\en-us\resource.dll" /// /// "resource.dll" is a language-specific resource DLL. /// If the localized resource DLL exists, LoadString(resource) is returned. /// </summary> private static unsafe string TryGetLocalizedNameByNativeResource(string filePath, int resource) { using (SafeLibraryHandle handle = Interop.Kernel32.LoadLibraryEx(filePath, IntPtr.Zero, Interop.Kernel32.LOAD_LIBRARY_AS_DATAFILE)) { if (!handle.IsInvalid) { const int LoadStringMaxLength = 500; char* localizedResource = stackalloc char[LoadStringMaxLength]; int charsWritten = Interop.User32.LoadString(handle, (uint)resource, localizedResource, LoadStringMaxLength); if (charsWritten != 0) { return new string(localizedResource, 0, charsWritten); } } } return string.Empty; } /// <summary> /// Helper function for retrieving the DisplayName, StandardName, and DaylightName from the registry /// /// The function first checks the MUI_ key-values, and if they exist, it loads the strings from the MUI /// resource dll(s). When the keys do not exist, the function falls back to reading from the standard /// key-values /// </summary> private static void GetLocalizedNamesByRegistryKey(RegistryKey key, out string displayName, out string standardName, out string daylightName) { displayName = string.Empty; standardName = string.Empty; daylightName = string.Empty; // read the MUI_ registry keys string displayNameMuiResource = key.GetValue(MuiDisplayValue, string.Empty) as string; string standardNameMuiResource = key.GetValue(MuiStandardValue, string.Empty) as string; string daylightNameMuiResource = key.GetValue(MuiDaylightValue, string.Empty) as string; // try to load the strings from the native resource DLL(s) if (!string.IsNullOrEmpty(displayNameMuiResource)) { displayName = TryGetLocalizedNameByMuiNativeResource(displayNameMuiResource); } if (!string.IsNullOrEmpty(standardNameMuiResource)) { standardName = TryGetLocalizedNameByMuiNativeResource(standardNameMuiResource); } if (!string.IsNullOrEmpty(daylightNameMuiResource)) { daylightName = TryGetLocalizedNameByMuiNativeResource(daylightNameMuiResource); } // fallback to using the standard registry keys if (string.IsNullOrEmpty(displayName)) { displayName = key.GetValue(DisplayValue, string.Empty) as string; } if (string.IsNullOrEmpty(standardName)) { standardName = key.GetValue(StandardValue, string.Empty) as string; } if (string.IsNullOrEmpty(daylightName)) { daylightName = key.GetValue(DaylightValue, string.Empty) as string; } } /// <summary> /// Helper function that takes a string representing a time_zone_name registry key name /// and returns a TimeZoneInfo instance. /// </summary> private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e) { e = null; // Standard Time Zone Registry Data // -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= // HKLM // Software // Microsoft // Windows NT // CurrentVersion // Time Zones // <time_zone_name> // * STD, REG_SZ "Standard Time Name" // (For OS installed zones, this will always be English) // * MUI_STD, REG_SZ "@tzres.dll,-1234" // Indirect string to localized resource for Standard Time, // add "%windir%\system32\" after "@" // * DLT, REG_SZ "Daylight Time Name" // (For OS installed zones, this will always be English) // * MUI_DLT, REG_SZ "@tzres.dll,-1234" // Indirect string to localized resource for Daylight Time, // add "%windir%\system32\" after "@" // * Display, REG_SZ "Display Name like (GMT-8:00) Pacific Time..." // * MUI_Display, REG_SZ "@tzres.dll,-1234" // Indirect string to localized resource for the Display, // add "%windir%\system32\" after "@" // * TZI, REG_BINARY REG_TZI_FORMAT // using (RegistryKey key = Registry.LocalMachine.OpenSubKey(TimeZonesRegistryHive + "\\" + id, writable: false)) { if (key == null) { value = null; return TimeZoneInfoResult.TimeZoneNotFoundException; } REG_TZI_FORMAT defaultTimeZoneInformation; if (!TryGetTimeZoneEntryFromRegistry(key, TimeZoneInfoValue, out defaultTimeZoneInformation)) { // the registry value could not be cast to a byte array value = null; return TimeZoneInfoResult.InvalidTimeZoneException; } AdjustmentRule[] adjustmentRules; if (!TryCreateAdjustmentRules(id, defaultTimeZoneInformation, out adjustmentRules, out e, defaultTimeZoneInformation.Bias)) { value = null; return TimeZoneInfoResult.InvalidTimeZoneException; } GetLocalizedNamesByRegistryKey(key, out string displayName, out string standardName, out string daylightName); try { value = new TimeZoneInfo( id, new TimeSpan(0, -(defaultTimeZoneInformation.Bias), 0), displayName, standardName, daylightName, adjustmentRules, disableDaylightSavingTime: false); return TimeZoneInfoResult.Success; } catch (ArgumentException ex) { // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException value = null; e = ex; return TimeZoneInfoResult.InvalidTimeZoneException; } catch (InvalidTimeZoneException ex) { // TimeZoneInfo constructor can throw ArgumentException and InvalidTimeZoneException value = null; e = ex; return TimeZoneInfoResult.InvalidTimeZoneException; } } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using TechAndWingsApi.Areas.HelpPage.ModelDescriptions; using TechAndWingsApi.Areas.HelpPage.Models; namespace TechAndWingsApi.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//////////////////////////////////////////////////////////////// // // // Neoforce Controls // // // //////////////////////////////////////////////////////////////// // // // File: ListBox.cs // // // // Version: 0.7 // // // // Date: 11/09/2010 // // // // Author: Tom Shane // // // //////////////////////////////////////////////////////////////// // // // Copyright (c) by Tom Shane // // // //////////////////////////////////////////////////////////////// #region //// Using ///////////// //////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Input; //////////////////////////////////////////////////////////////////////////// #endregion namespace TomShane.Neoforce.Controls { #region //// Classes /////////// //////////////////////////////////////////////////////////////////////////// /// <include file='Documents/ListBox.xml' path='ListBox/Class[@name="ListBox"]/*' /> public class ListBox : Control { #region //// Fields //////////// //////////////////////////////////////////////////////////////////////////// private List<object> items = new List<object>(); private ScrollBar sbVert = null; private ClipBox pane = null; private int itemIndex = -1; private bool hotTrack = false; private int itemsCount = 0; private bool hideSelection = true; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Properties //////// //////////////////////////////////////////////////////////////////////////// public virtual List<object> Items { get { return items; } internal set { items = value; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual bool HotTrack { get { return hotTrack; } set { if (hotTrack != value) { hotTrack = value; if (!Suspended) OnHotTrackChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual int ItemIndex { get { return itemIndex; } set { //if (itemIndex != value) { if (value >= 0 && value < items.Count) { itemIndex = value; } else { itemIndex = -1; } ScrollTo(itemIndex); if (!Suspended) OnItemIndexChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual bool HideSelection { get { return hideSelection; } set { if (hideSelection != value) { hideSelection = value; Invalidate(); if (!Suspended) OnHideSelectionChanged(new EventArgs()); } } } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Events //////////// //////////////////////////////////////////////////////////////////////////// public event EventHandler HotTrackChanged; public event EventHandler ItemIndexChanged; public event EventHandler HideSelectionChanged; //////////////////////////////////////////////////////////////////////////// #endregion #region //// Construstors ////// //////////////////////////////////////////////////////////////////////////// public ListBox(Manager manager) : base(manager) { Width = 64; Height = 64; MinimumHeight = 16; sbVert = new ScrollBar(Manager, Orientation.Vertical); sbVert.Init(); sbVert.Parent = this; sbVert.Left = Left + Width - sbVert.Width - Skin.Layers["Control"].ContentMargins.Right; sbVert.Top = Top + Skin.Layers["Control"].ContentMargins.Top; sbVert.Height = Height - Skin.Layers["Control"].ContentMargins.Vertical; sbVert.Anchor = Anchors.Top | Anchors.Right | Anchors.Bottom; sbVert.PageSize = 25; sbVert.Range = 1; sbVert.PageSize = 1; sbVert.StepSize = 10; pane = new ClipBox(manager); pane.Init(); pane.Parent = this; pane.Top = Skin.Layers["Control"].ContentMargins.Top; pane.Left = Skin.Layers["Control"].ContentMargins.Left; pane.Width = Width - sbVert.Width - Skin.Layers["Control"].ContentMargins.Horizontal - 1; pane.Height = Height - Skin.Layers["Control"].ContentMargins.Vertical; pane.Anchor = Anchors.All; pane.Passive = true; pane.CanFocus = false; pane.Draw += new DrawEventHandler(DrawPane); CanFocus = true; Passive = false; } //////////////////////////////////////////////////////////////////////////// #endregion #region //// Methods /////////// //////////////////////////////////////////////////////////////////////////// public override void Init() { base.Init(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void AutoHeight(int maxItems) { if (items != null && items.Count < maxItems) maxItems = items.Count; if (maxItems < 3) { //maxItems = 3; sbVert.Visible = false; pane.Width = Width - Skin.Layers["Control"].ContentMargins.Horizontal - 1; } else { pane.Width = Width - sbVert.Width - Skin.Layers["Control"].ContentMargins.Horizontal - 1; sbVert.Visible = true; } SkinText font = Skin.Layers["Control"].Text; if (items != null && items.Count > 0) { int h = (int)font.Font.Resource.MeasureString(items[0].ToString()).Y; Height = (h * maxItems) + (Skin.Layers["Control"].ContentMargins.Vertical);// - Skin.OriginMargins.Vertical); } else { Height = 32; } } //////////////////////////////////////////////////////////////////////////// public override int MinimumHeight { get { return base.MinimumHeight; } set { base.MinimumHeight = value; if (this.sbVert != null) this.sbVert.MinimumHeight = value; } } //////////////////////////////////////////////////////////////////////////// protected override void DrawControl(Renderer renderer, Rectangle rect, GameTime gameTime) { sbVert.Invalidate(); pane.Invalidate(); //DrawPane(this, new DrawEventArgs(renderer, rect, gameTime)); base.DrawControl(renderer, rect, gameTime); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void DrawPane(object sender, DrawEventArgs e) { if (items != null && items.Count > 0) { SkinText font = Skin.Layers["Control"].Text; SkinLayer sel = Skin.Layers["ListBox.Selection"]; int h = (int)font.Font.Resource.MeasureString(items[0].ToString()).Y; int v = (sbVert.Value / 10); int p = (sbVert.PageSize / 10); int d = (int)(((sbVert.Value % 10) / 10f) * h); int c = items.Count; int s = itemIndex; for (int i = v; i <= v + p + 1; i++) { if (i < c) { e.Renderer.DrawString(this, Skin.Layers["Control"], items[i].ToString(), new Rectangle(e.Rectangle.Left, e.Rectangle.Top - d + ((i - v) * h), e.Rectangle.Width, h), false); } } if (s >= 0 && s < c && (Focused || !hideSelection)) { int pos = -d + ((s - v) * h); if (pos > -h && pos < (p + 1) * h) { e.Renderer.DrawLayer(this, sel, new Rectangle(e.Rectangle.Left, e.Rectangle.Top + pos, e.Rectangle.Width, h)); e.Renderer.DrawString(this, sel, items[s].ToString(), new Rectangle(e.Rectangle.Left, e.Rectangle.Top + pos, e.Rectangle.Width, h), false); } } } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (e.Button == MouseButton.Left || e.Button == MouseButton.Right) { TrackItem(e.Position.X, e.Position.Y); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void TrackItem(int x, int y) { if (items != null && items.Count > 0 && (pane.ControlRect.Contains(new Point(x, y)))) { SkinText font = Skin.Layers["Control"].Text; int h = (int)font.Font.Resource.MeasureString(items[0].ToString()).Y; int d = (int)(((sbVert.Value % 10) / 10f) * h); int i = (int)Math.Floor((sbVert.Value / 10f) + ((float)y / h)); if (i >= 0 && i < Items.Count && i >= (int)Math.Floor((float)sbVert.Value / 10f) && i < (int)Math.Ceiling((float)(sbVert.Value + sbVert.PageSize) / 10f)) ItemIndex = i; Focused = true; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (hotTrack) { TrackItem(e.Position.X, e.Position.Y); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnKeyPress(KeyEventArgs e) { if (e.Key == Keys.Down) { e.Handled = true; itemIndex += sbVert.StepSize / 10; } else if (e.Key == Keys.Up) { e.Handled = true; itemIndex -= sbVert.StepSize / 10; } else if (e.Key == Keys.PageDown) { e.Handled = true; itemIndex += sbVert.PageSize / 10; } else if (e.Key == Keys.PageUp) { e.Handled = true; itemIndex -= sbVert.PageSize / 10; } else if (e.Key == Keys.Home) { e.Handled = true; itemIndex = 0; } else if (e.Key == Keys.End) { e.Handled = true; itemIndex = items.Count - 1; } if (itemIndex < 0) itemIndex = 0; else if (itemIndex >= Items.Count) itemIndex = Items.Count - 1; ItemIndex = itemIndex; base.OnKeyPress(e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnGamePadPress(GamePadEventArgs e) { if (e.Button == GamePadActions.Down) { e.Handled = true; itemIndex += sbVert.StepSize / 10; } else if (e.Button == GamePadActions.Up) { e.Handled = true; itemIndex -= sbVert.StepSize / 10; } if (itemIndex < 0) itemIndex = 0; else if (itemIndex >= Items.Count) itemIndex = Items.Count - 1; ItemIndex = itemIndex; base.OnGamePadPress(e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// private void ItemsChanged() { if (items != null && items.Count > 0) { SkinText font = Skin.Layers["Control"].Text; int h = (int)font.Font.Resource.MeasureString(items[0].ToString()).Y; int sizev = Height - Skin.Layers["Control"].ContentMargins.Vertical; sbVert.Range = items.Count * 10; sbVert.PageSize = (int)Math.Floor((float)sizev * 10 / h); Invalidate(); } else if (items == null || items.Count <= 0) { sbVert.Range = 1; sbVert.PageSize = 1; Invalidate(); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected override void OnResize(ResizeEventArgs e) { base.OnResize(e); ItemsChanged(); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// public virtual void ScrollTo(int index) { ItemsChanged(); if ((index * 10) < sbVert.Value) { sbVert.Value = index * 10; } else if (index >= (int)Math.Floor(((float)sbVert.Value + sbVert.PageSize) / 10f)) { sbVert.Value = ((index + 1) * 10) - sbVert.PageSize; } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected internal override void Update(GameTime gameTime) { base.Update(gameTime); if (Visible && items != null && items.Count != itemsCount) { itemsCount = items.Count; ItemsChanged(); } } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnItemIndexChanged(EventArgs e) { if (ItemIndexChanged != null) ItemIndexChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnHotTrackChanged(EventArgs e) { if (HotTrackChanged != null) HotTrackChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// protected virtual void OnHideSelectionChanged(EventArgs e) { if (HideSelectionChanged != null) HideSelectionChanged.Invoke(this, e); } //////////////////////////////////////////////////////////////////////////// #endregion } //////////////////////////////////////////////////////////////////////////// #endregion }
using System; using System.Collections.Generic; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using Microsoft.VisualStudio.TestTools.UnitTesting; using DotVVM.Framework.Binding; using DotVVM.Framework.Binding.Expressions; using DotVVM.Framework.Compilation; using DotVVM.Framework.Configuration; using DotVVM.Framework.Controls; using DotVVM.Framework.Controls.Infrastructure; using DotVVM.Framework.Hosting; using DotVVM.Framework.Runtime; using Microsoft.Extensions.DependencyInjection; using DotVVM.Framework.Binding.Properties; using System.Linq; using DotVVM.Framework.DependencyInjection; using DotVVM.Framework.ResourceManagement; using DotVVM.Framework.Testing; namespace DotVVM.Framework.Tests.Runtime { [TestClass] public class DefaultViewCompilerTests { private IDotvvmRequestContext context; [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementWithAttributeProperty() { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal Text='test' />"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(2, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(RawLiteral)); Assert.AreEqual("test ", ((RawLiteral)page.Children[0]).EncodedText); Assert.IsInstanceOfType(page.Children[1], typeof(Literal)); Assert.AreEqual("test", ((Literal)page.Children[1]).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementWithBindingProperty() { var markup = string.Format("@viewModel {0}, {1}\r\ntest <dot:Literal Text='{{{{value: FirstName}}}}' />", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name); var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(2, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(RawLiteral)); Assert.AreEqual("test ", ((RawLiteral)page.Children[0]).EncodedText); Assert.IsInstanceOfType(page.Children[1], typeof(Literal)); var binding = ((Literal)page.Children[1]).GetBinding(Literal.TextProperty) as ValueBindingExpression; Assert.IsNotNull(binding); Assert.AreEqual("FirstName", binding.GetProperty<OriginalStringBindingProperty>().Code); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_BindingInText() { var markup = string.Format("@viewModel {0}, {1}\r\ntest {{{{value: FirstName}}}}", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name); var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(2, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(RawLiteral)); Assert.AreEqual("test ", ((RawLiteral)page.Children[0]).EncodedText); Assert.IsInstanceOfType(page.Children[1], typeof(Literal)); var binding = ((Literal)page.Children[1]).GetBinding(Literal.TextProperty) as ValueBindingExpression; Assert.IsNotNull(binding); Assert.AreEqual("FirstName", binding.GetProperty<OriginalStringBindingProperty>().Code); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_NestedControls() { var markup = @"@viewModel System.Object, mscorlib <dot:PlaceHolder>test <dot:Literal /></dot:PlaceHolder>"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(1, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(PlaceHolder)); Assert.AreEqual(2, page.Children[0].Children.Count); Assert.IsTrue(page.Children[0].Children[0] is RawLiteral); Assert.IsTrue(page.Children[0].Children[1] is Literal); Assert.AreEqual("test ", ((RawLiteral)page.Children[0].Children[0]).EncodedText); Assert.AreEqual("", ((Literal)page.Children[0].Children[1]).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementCannotHaveContent_TextInside() { Assert.ThrowsException<DotvvmCompilationException>(() => { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal>aaa</dot:Literal>"; var page = CompileMarkup(markup); }); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementCannotHaveContent_BindingAndWhiteSpaceInside() { Assert.ThrowsException<DotvvmCompilationException>(() => { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal>{{value: FirstName}} </dot:Literal>"; var page = CompileMarkup(markup); }); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_ElementCannotHaveContent_ElementInside() { Assert.ThrowsException<DotvvmCompilationException>(() => { var markup = @"@viewModel System.Object, mscorlib test <dot:Literal><a /></dot:Literal>"; var page = CompileMarkup(markup); }); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_Template() { var markup = string.Format("@viewModel {0}, {1}\r\n", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name) + @"<dot:Repeater DataSource=""{value: FirstName}""> <ItemTemplate> <p>This is a test</p> </ItemTemplate> </dot:Repeater>"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.AreEqual(1, page.Children.Count); Assert.IsInstanceOfType(page.Children[0], typeof(Repeater)); DotvvmControl placeholder = new PlaceHolder(); ((Repeater)page.Children[0]).ItemTemplate.BuildContent(context, placeholder); Assert.AreEqual(3, placeholder.Children.Count); Assert.IsTrue(string.IsNullOrWhiteSpace(((RawLiteral)placeholder.Children[0]).EncodedText)); Assert.AreEqual("p", ((HtmlGenericControl)placeholder.Children[1]).TagName); Assert.AreEqual("This is a test", ((RawLiteral)placeholder.Children[1].Children[0]).EncodedText); Assert.IsTrue(string.IsNullOrWhiteSpace(((RawLiteral)placeholder.Children[2]).EncodedText)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_AttachedProperty() { var markup = @"@viewModel System.Object, mscorlib <dot:Button Validation.Enabled=""false"" /><dot:Button Validation.Enabled=""true"" /><dot:Button />"; var page = CompileMarkup(markup); Assert.IsInstanceOfType(page, typeof(DotvvmView)); var button1 = page.Children[0]; Assert.IsInstanceOfType(button1, typeof(Button)); Assert.IsFalse((bool)button1.GetValue(Controls.Validation.EnabledProperty)); var button2 = page.Children[1]; Assert.IsInstanceOfType(button2, typeof(Button)); Assert.IsTrue((bool)button2.GetValue(Controls.Validation.EnabledProperty)); var button3 = page.Children[2]; Assert.IsInstanceOfType(button3, typeof(Button)); Assert.IsTrue((bool)button3.GetValue(Controls.Validation.EnabledProperty)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControl() { var markup = @"@viewModel System.Object, mscorlib <cc:Test1 />"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test1.dothtml", @"@viewModel System.Object, mscorlib <dot:Literal Text='aaa' />" } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(DotvvmView)); var literal = page.Children[0].Children[0]; Assert.IsInstanceOfType(literal, typeof(Literal)); Assert.AreEqual("aaa", ((Literal)literal).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControlWithBaseType() { var markup = @"@viewModel System.Object, mscorlib <cc:Test2 />"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test2.dothtml", string.Format("@baseType {0}, {1}\r\n@viewModel System.Object, mscorlib\r\n<dot:Literal Text='aaa' />", typeof(TestControl), typeof(TestControl).Assembly.GetName().Name) } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(TestControl)); var literal = page.Children[0].Children[0].Children[0]; Assert.IsInstanceOfType(literal, typeof(Literal)); Assert.AreEqual("aaa", ((Literal)literal).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControlWithDI() { var markup = @"@viewModel System.Object, mscorlib <cc:Test5 />"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test5.dothtml", $"@baseType {typeof(TestMarkupDIControl)}\n@viewModel System.Object, mscorlib\n<dot:Literal Text='aaa' />" } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(TestMarkupDIControl)); var control = (TestMarkupDIControl)page.Children[0]; Assert.IsNotNull(control.config); var literal = page.Children[0].Children[0].Children[0]; Assert.IsInstanceOfType(literal, typeof(Literal)); Assert.AreEqual("aaa", ((Literal)literal).Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControl_InTemplate() { var markup = string.Format("@viewModel {0}, {1}\r\n", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name) + @"<dot:Repeater DataSource=""{value: FirstName}""> <ItemTemplate> <cc:Test3 /> </ItemTemplate> </dot:Repeater>"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test3.dothtml", "@viewModel System.Char, mscorlib\r\n<dot:Literal Text='aaa' />" } }); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(Repeater)); var container = new PlaceHolder(); ((Repeater)page.Children[0]).ItemTemplate.BuildContent(context, container); var literal1 = container.Children[0]; Assert.IsInstanceOfType(literal1, typeof(RawLiteral)); Assert.IsTrue(string.IsNullOrWhiteSpace(((RawLiteral)literal1).EncodedText)); var markupControl = container.Children[1]; Assert.IsInstanceOfType(markupControl, typeof(DotvvmView)); Assert.IsInstanceOfType(markupControl.Children[0], typeof(Literal)); Assert.AreEqual("aaa", ((Literal)markupControl.Children[0]).Text); var literal2 = container.Children[2]; Assert.IsInstanceOfType(literal2, typeof(RawLiteral)); Assert.IsTrue(string.IsNullOrWhiteSpace(((RawLiteral)literal2).EncodedText)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_MarkupControl_InTemplate_CacheTest() { var markup = string.Format("@viewModel {0}, {1}\r\n", typeof(ViewCompilerTestViewModel).FullName, typeof(ViewCompilerTestViewModel).Assembly.GetName().Name) + @"<dot:Repeater DataSource=""{value: FirstName}""> <ItemTemplate> <cc:Test4 /> </ItemTemplate> </dot:Repeater>"; var page = CompileMarkup(markup, new Dictionary<string, string>() { { "test4.dothtml", "@viewModel System.Char, mscorlib\r\n<dot:Literal Text='aaa' />" } }, compileTwice: true); Assert.IsInstanceOfType(page, typeof(DotvvmView)); Assert.IsInstanceOfType(page.Children[0], typeof(Repeater)); var container = new PlaceHolder(); ((Repeater)page.Children[0]).ItemTemplate.BuildContent(context, container); var literal1 = container.Children[0]; Assert.IsInstanceOfType(literal1, typeof(RawLiteral)); Assert.IsTrue(string.IsNullOrWhiteSpace(((RawLiteral)literal1).EncodedText)); var markupControl = container.Children[1]; Assert.IsInstanceOfType(markupControl, typeof(DotvvmView)); Assert.IsInstanceOfType(markupControl.Children[0], typeof(Literal)); Assert.AreEqual("aaa", ((Literal)markupControl.Children[0]).Text); var literal2 = container.Children[2]; Assert.IsInstanceOfType(literal2, typeof(RawLiteral)); Assert.IsTrue(string.IsNullOrWhiteSpace(((RawLiteral)literal2).EncodedText)); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_Page_InvalidViewModelClass() { Assert.ThrowsException<DotvvmCompilationException>(() => { var markup = "@viewModel nonexistingclass\r\n{{value: Test}}"; var page = CompileMarkup(markup); }); } [TestMethod] public void DefaultViewCompiler_FlagsEnum() { var markup = @" @viewModel System.Object <ff:TestCodeControl Flags='A, B, C' />"; var page = CompileMarkup(markup); Assert.AreEqual(FlaggyEnum.A | FlaggyEnum.B | FlaggyEnum.C, page.GetThisAndAllDescendants().OfType<TestCodeControl>().First().Flags); } [TestMethod] public void DefaultViewCompiler_CustomDependencyInjection() { var markup = @" @viewModel System.Object <ff:TestCustomDependencyInjectionControl />"; var page = CompileMarkup(markup); Assert.IsTrue(page.GetThisAndAllDescendants().OfType<TestCustomDependencyInjectionControl>().First().IsCorrectlyCreated); } [TestMethod] public void ComboBox_ControlUsageValidation() { // CheckedItems must be a collection of CheckedValues var markup = @" @viewModel System.String <dot:ComboBox CheckedValue='{value: Length}' CheckedItems='{value: _this}' />"; Assert.ThrowsException<DotvvmCompilationException>(() => CompileMarkup(markup)); } [TestMethod] public void RadioButton_ControlUsageValidation() { // CheckedValue and CheckedItem must be the same type var markup = @" @viewModel System.String <dot:RadioButton CheckedValue='{value: _this}' CheckedItem='{value: Length}' />"; Assert.ThrowsException<DotvvmCompilationException>(() => CompileMarkup(markup)); } [TestMethod] public void DefaultViewCompiler_ViewDependencyInjection() { var markup = @" @viewModel System.Object @service config=DotVVM.Framework.Configuration.DotvvmConfiguration {{resource: config.ApplicationPhysicalPath}}{{resource: config.DefaultCulture}}"; var page = CompileMarkup(markup); var literals = page.GetAllDescendants().OfType<Literal>().ToArray(); Assert.AreEqual(2, literals.Length); Assert.AreEqual(context.Configuration.ApplicationPhysicalPath, literals[0].Text); Assert.AreEqual(context.Configuration.DefaultCulture, literals[1].Text); } [TestMethod] public void DefaultViewCompiler_CodeGeneration_PostbackHandlerResourceRegistration() { var markup = @" @viewModel System.Object <dot:Button Click='{command: 0}'> <Postback.Handlers> <ff:PostbackHandlerWithRequiredResource /> </Postback.Handlers> </dot:Button> "; var page = CompileMarkup(markup); Assert.IsTrue(context.ResourceManager.RequiredResources.Contains("testscript")); } [TestMethod] public void DefaultViewCompiler_ControlWithDependentProperties() { var markup = @" @viewModel System.Collections.Generic.List<string> <ff:ControlWithCompileDependentProperties OtherProperty='{value: _this.Length}' DataSource='{value: _this}'> </ff:ControlWithCompileDependentProperties> "; var page = CompileMarkup(markup); } [TestMethod] public void DefaultViewCompiler_ExcludedBindingProperty() { var markup = @" @viewModel object <ff:ControlWithCustomBindingProperties SomeProperty='{value: System.Environment.GetCommandLineArgs()}' /> "; var page = CompileMarkup(markup); var control = page.GetThisAndAllDescendants().OfType<ControlWithCustomBindingProperties>().Single(); var assemblies = ((IEnumerable<object>)control.SomeProperty).ToArray(); Assert.IsNotNull(assemblies); var lengthBinding = control.GetValueBinding(ControlWithCustomBindingProperties.SomePropertyProperty).GetProperty<DataSourceLengthBinding>().Binding; var lengthValue = BindingHelper.Evaluate((IStaticValueBinding)lengthBinding, control); Assert.AreEqual(assemblies.Length, lengthValue); } [TestMethod] public void DefaultViewCompiler_RequiredBindingProperty() { var markup = @" @viewModel object @import AppDomain = System.AppDomain <ff:ControlWithCustomBindingProperties SomeProperty='{value: _this}' /> "; var ex = Assert.ThrowsException<DotvvmCompilationException>(() => { CompileMarkup(markup); }); Assert.IsTrue(ex.ToString().Contains("DotVVM.Framework.Binding.Properties.DataSourceLengthBinding")); Assert.IsTrue(ex.ToString().Contains("Cannot find collection length from binding '_this'")); } [TestMethod] public void DefaultViewCompiler_InternalControl_Error() { var markup = @" @viewModel object <ff:InternalControl /> "; var ex = Assert.ThrowsException<DotvvmCompilationException>(() => { CompileMarkup(markup); }); Assert.IsTrue(ex.ToString().Contains("Control DotVVM.Framework.Tests.Runtime.InternalControl is not publicly accessible.")); Assert.IsFalse(ex.ToString().Contains("This is most probably bug in the DotVVM framework.")); } // Well, DotvvmProperties work even when they are internal. So I cannot add the check in order to remain backwards compatible :/ // [TestMethod] // public void DefaultViewCompiler_InternalDotvvmProperty_Error() // { // var markup = @" // @viewModel object // <ff:PublicControl MyInternalDotvvmProperty=1 /> // "; // // var ex = Assert.ThrowsException<DotvvmCompilationException>(() => { // var a = CompileMarkup(markup); // var x = a.GetThisAndAllDescendants().OfType<PublicControl>().Single().MyInternalDotvvmProperty; // Assert.AreEqual(1, x); // // }); // // Assert.IsTrue(ex.ToString().Contains("Control DotVVM.Framework.Tests.Runtime.InternalControl is not publicly accessible.")); // // Assert.IsFalse(ex.ToString().Contains("This is most probably bug in the DotVVM framework.")); // } [TestMethod] public void DefaultViewCompiler_InternalVirtualProperty_Error() { var markup = @" @viewModel object <ff:PublicControl MyInternalProperty=1 /> "; var ex = Assert.ThrowsException<DotvvmCompilationException>(() => { CompileMarkup(markup); }); Assert.IsTrue(ex.ToString().Contains("The control 'DotVVM.Framework.Tests.Runtime.PublicControl' does not have a property 'MyInternalProperty'")); Assert.IsFalse(ex.ToString().Contains("This is most probably bug in the DotVVM framework.")); } static ControlTestHelper controlHelper = new ControlTestHelper(true, config => { config.ApplicationPhysicalPath = Path.GetTempPath(); config.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test1", Src = "test1.dothtml" }); config.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test2", Src = "test2.dothtml" }); config.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test3", Src = "test3.dothtml" }); config.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test4", Src = "test4.dothtml" }); config.Markup.Controls.Add(new DotvvmControlConfiguration() { TagPrefix = "cc", TagName = "Test5", Src = "test5.dothtml" }); config.Markup.AddCodeControls("ff", typeof(TestControl)); config.Markup.AddAssembly(typeof(DefaultViewCompilerTests).Assembly.GetName().Name); }, services => { services.AddSingleton<CustomControlFactory>((s, t) => t == typeof(TestCustomDependencyInjectionControl) ? new TestCustomDependencyInjectionControl("") { IsCorrectlyCreated = true } : throw new Exception()); } ); private DotvvmControl CompileMarkup(string markup, Dictionary<string, string> markupFiles = null, bool compileTwice = false, [CallerMemberName]string fileName = null) { var config = controlHelper.Configuration; context = DotvvmTestHelper.CreateContext(config); var (_, controlBuilder) = controlHelper.CompilePage(markup, fileName, markupFiles); var controlBuilderFactory = context.Services.GetRequiredService<IControlBuilderFactory>(); var result = controlBuilder.Value.BuildControl(controlBuilderFactory, context.Services); if (compileTwice) { result = controlBuilder.Value.BuildControl(controlBuilderFactory, context.Services); } result.SetValue(Internal.RequestContextProperty, context); return result; } } internal class InternalControl: DotvvmControl { } public class PublicControl: DotvvmControl { [MarkupOptions()] internal int MyInternalProperty { get; set; } internal int MyInternalDotvvmProperty { get { return (int)GetValue(MyInternalDotvvmPropertyProperty); } set { SetValue(MyInternalDotvvmPropertyProperty, value); } } internal static readonly DotvvmProperty MyInternalDotvvmPropertyProperty = DotvvmProperty.Register<int, PublicControl>(nameof(MyInternalDotvvmProperty)); } public class PostbackHandlerWithRequiredResource : PostBackHandler { public PostbackHandlerWithRequiredResource(ResourceManager resources) { resources.AddStartupScript("testscript", "do_some_stuff()"); } protected internal override string ClientHandlerName => "something"; protected internal override Dictionary<string, object> GetHandlerOptions() { return new Dictionary<string, object>(); } } public class ViewCompilerTestViewModel { public string FirstName { get; set; } } public class TestControl : DotvvmMarkupControl { } public class TestMarkupDIControl : DotvvmMarkupControl { public readonly DotvvmConfiguration config; public TestMarkupDIControl(DotvvmConfiguration configuration) { this.config = configuration; } } public class TestDIControl : DotvvmControl { public readonly DotvvmConfiguration config; public TestDIControl(DotvvmConfiguration configuration) { this.config = configuration; } } [Flags] public enum FlaggyEnum { A, B, C, D} public class TestCodeControl: DotvvmControl { public FlaggyEnum Flags { get { return (FlaggyEnum)GetValue(FlagsProperty); } set { SetValue(FlagsProperty, value); } } public static readonly DotvvmProperty FlagsProperty = DotvvmProperty.Register<FlaggyEnum, TestCodeControl>(nameof(Flags)); } public delegate DotvvmControl CustomControlFactory(IServiceProvider sp, Type controlType); [RequireDependencyInjection(typeof(CustomControlFactory))] public class TestCustomDependencyInjectionControl: DotvvmControl { public bool IsCorrectlyCreated { get; set; } = false; public TestCustomDependencyInjectionControl(string something) { } } public class ControlWithCompileDependentProperties: DotvvmControl { public IEnumerable<object> DataSource { get { return (IEnumerable<object>)GetValue(DataSourceProperty); } set { SetValue(DataSourceProperty, value); } } public static readonly DotvvmProperty DataSourceProperty = DotvvmProperty.Register<IEnumerable<object>, ControlWithCompileDependentProperties>(nameof(DataSource)); [ControlPropertyBindingDataContextChange("DataSource")] [CollectionElementDataContextChange(1)] public IValueBinding OtherProperty { get { return (IValueBinding)GetValue(OtherPropertyProperty); } set { SetValue(OtherPropertyProperty, value); } } public static readonly DotvvmProperty OtherPropertyProperty = DotvvmProperty.Register<IValueBinding, ControlWithCompileDependentProperties>(nameof(OtherProperty)); } public class ControlWithCustomBindingProperties : DotvvmControl { [BindingCompilationRequirements( excluded: new [] { typeof(KnockoutExpressionBindingProperty) }, required: new [] { typeof(DataSourceLengthBinding) } )] public object SomeProperty { get { return GetValue(SomePropertyProperty); } set { SetValue(SomePropertyProperty, value); } } public static readonly DotvvmProperty SomePropertyProperty = DotvvmProperty.Register<object, ControlWithCustomBindingProperties>(nameof(SomeProperty)); } }
/* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. */ /****************************************************************************** * * You may not use the identified files except in compliance with The MIT * License (the "License.") * * You may obtain a copy of the License at * https://github.com/oracle/Oracle.NET/blob/master/LICENSE * * 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. * *****************************************************************************/ /******************************************************************************************** * @author : Jagriti * @version : 1.0 * Development Environment : Microsoft Visual Studio .Net * Name of the File : ViewProducts.cs * Creation/Modification History : * 24-July-2002 Created * * Sample Overview: * The purpose of this .NET sample application is to demonstrate how to populate a DataSet with data * from multiple Ref Cursors which are returned as OUT parameters from a database Stored Procedure * through Oracle Data Provider for .Net (ODP.Net) connection. The parameters of * 'OracleDbType.RefCursor' type are bound to the OracleCommand object. The Command type is set to * 'Stored Procedure' for OracleCommand. The OracleDataAdapter fills the DataSet with the Ref Cursors * returned as OUT parameter from the database stored procedure. The data from each Ref Cursor * is stored in a Data Table contained in the Data Set. The Data Tables are named as 'TableN' * where N stands for integers starting with 0. Different Data Grids can be bound to different * Data Tables. * * When this sample is run two Data Grids are displayed. One Data Grid populated with records * for products with 'Orderable' status and other Data Grid with records for products with * 'Under Development' status. The data is fetched from database stored procedure * 'getProductsInfo' from 'ODPNet' package. The 'productAdapter' executes 'productCmd'. * Command type for 'productCmd'. The two Data Tables created are 'Products' and 'Products1'. * The Data Grids are bound to these Data Tables. ***********************************************************************************************/ //Standard Namespaces referenced in this sample application using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using Oracle.ManagedDataAccess.Client; using Oracle.ManagedDataAccess.Types; namespace DSwithRefCur { public class ViewProducts : System.Windows.Forms.Form { //UI Components private Container components = null; private Button closeBtn; private Label headerLbl; //Data Grid component for Orderable Product Status private DataGrid orderableDataGrid; //Data Grid Table style and its corresponding columns for Orderable Product Status private DataGridTableStyle orderableDataGridTableStyle; private DataGridTextBoxColumn ProductID; private DataGridTextBoxColumn ProductName; private DataGridTextBoxColumn ProductDesc; private DataGridTextBoxColumn Category; private DataGridTextBoxColumn Price; //DataGrid component for Under Development Product Status private DataGrid udevelopmentDataGrid; //Data Grid Table style and its corresponding columns for Under Developement Product Status private DataGridTableStyle udevelopmentDataGridTableStyle; private DataGridTextBoxColumn ProductID1; private DataGridTextBoxColumn ProductName1; private DataGridTextBoxColumn ProductDesc1; private DataGridTextBoxColumn Category1; private DataGridTextBoxColumn Price1; //For database connection OracleConnection conn; /******************************************************************* * This method is the entry point for this sample application. * It also calls 'populateProducts' method that fills the Data Grids *******************************************************************/ static void Main() { //Instantiating this class ViewProducts viewproducts = new ViewProducts(); //Get database connection if (viewproducts.getDBConnection()) { //Calls populateProducts method that fetches data from //database and fills the Data Grids viewproducts.populateProducts(); //Start the application and display the View Products form Application.Run(viewproducts); } } //Constructor public ViewProducts() { // Required for Windows Form Designer support InitializeComponent(); } /******************************************************************************** * The purpose of this method is to populate the Data Grids with data from * Ref Cursors returned as OUT parameters from 'ODPNet.getProductsInfo' * database Stored Procedure. * Following is the flow for this method: * 1. For 'productCmd' OracleCommand object set the command as * a call to database Stored Procedure 'ODPNet.getProductsInfo'. * 2. Set command type as 'Stored Procedure' for 'productCmd'. * 3. Bind the Ref Cursor parameters as 'OracleDbType.RefCursor' to the * OracleCommand object. * 4. 'Fill' method for 'productAdapter' OracleDataAdapter fills 'productsDataSet' * with data returned upon executing OracleCommand object . * 5. 'ProductDataSet' contains two Data Tables 'Products' and 'Products1'. * 'Products' Data Table contains data from 'orderable' Ref Cursor * parameter. 'Products1' Data Table contains data from 'udevelopment' * Ref Cursor parameter. * 6. 'orderableDataGrid' is bound to 'Products' Data Table and * 'udevelopmentDataGrid' is bound to 'Products1' Data Table. ********************************************************************************/ private void populateProducts() { //To fill DataSet from datasource OracleDataAdapter productAdapter; //Represents Stored Procedure to execute against a data source OracleCommand productCmd; //In-memory cache of data DataSet productsDataSet; try{ //Step 1.// //Instantiate the command object productCmd = new OracleCommand(); //Call 'getProductsInfo' stored procedure of 'ODPNet' // database package productCmd.CommandText = "ODPNet.getProductsInfo"; //Step 2.// //Set the command Type to Stored Procedure productCmd.CommandType = CommandType.StoredProcedure; //Set the connection instance productCmd.Connection = conn; //Step 3.// //Bind the Ref Cursor parameters to the OracleCommand object //for 'orderable' product status productCmd.Parameters.Add("orderable",OracleDbType.RefCursor, DBNull.Value,ParameterDirection.Output); //for 'under development' product status productCmd.Parameters.Add("udevelopment",OracleDbType.RefCursor, DBNull.Value,ParameterDirection.Output); //Step 4.// //Set the command for the Data Adapter productAdapter = new OracleDataAdapter(productCmd); //Instantiate Data Set object productsDataSet = new DataSet("productsDataSet"); //Step 5.// //Fill Data Set with data from Data Adapter productAdapter.Fill(productsDataSet,"Products"); //Step 6.// //Bind 'orderableDataGrid' with 'Products' Data Table orderableDataGrid.SetDataBinding(productsDataSet,"Products"); //Bind 'udevelopmentDataGrid' with 'Products1' Data Table udevelopmentDataGrid.SetDataBinding(productsDataSet,"Products1"); } catch(Exception ex){ MessageBox.Show(ex.ToString()); } } /******************************************************************* * The purpose of this method is to get the database connection * using the parameters given. * Note: Replace the datasource parameter with your datasource value. ********************************************************************/ private Boolean getDBConnection() { try { //Connection Information string connectionString = //Username "User Id=" + ConnectionParams.Username + //Password ";Password=" + ConnectionParams.Password + //Replace with your datasource value (TNSNames) ";Data Source=" + ConnectionParams.Datasource ; //Connection to datasource, using connection parameters given above conn = new OracleConnection(connectionString); //Open database connection conn.Open(); return true; } catch (Exception ex) // catch exception when error in connecting to database occurs { //Display error message MessageBox.Show(ex.ToString()); return false; } } /********************************************************************** * This method is called on the click event of the 'Close' button. * The purpose of this method is to close the form 'ViewProducts' and * then exit out of the application. **********************************************************************/ private void closeBtn_Click(object sender, System.EventArgs e) { conn.Close(); this.Close(); Application.Exit(); } /********************************************************************* * The purpose of this method is to clean up any resources being used. *********************************************************************/ protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /*********************************************************************** * This is a required method for Designer support, its purpose is * to intialize the UI controls and their related properties. * NOTE: Do not modify the contents of this method with the code editor. ************************************************************************/ private void InitializeComponent() { this.orderableDataGrid = new System.Windows.Forms.DataGrid(); this.orderableDataGridTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.ProductID = new System.Windows.Forms.DataGridTextBoxColumn(); this.ProductName = new System.Windows.Forms.DataGridTextBoxColumn(); this.ProductDesc = new System.Windows.Forms.DataGridTextBoxColumn(); this.Category = new System.Windows.Forms.DataGridTextBoxColumn(); this.Price = new System.Windows.Forms.DataGridTextBoxColumn(); this.udevelopmentDataGrid = new System.Windows.Forms.DataGrid(); this.udevelopmentDataGridTableStyle = new System.Windows.Forms.DataGridTableStyle(); this.ProductID1 = new System.Windows.Forms.DataGridTextBoxColumn(); this.ProductName1 = new System.Windows.Forms.DataGridTextBoxColumn(); this.ProductDesc1 = new System.Windows.Forms.DataGridTextBoxColumn(); this.Category1 = new System.Windows.Forms.DataGridTextBoxColumn(); this.Price1 = new System.Windows.Forms.DataGridTextBoxColumn(); this.headerLbl = new System.Windows.Forms.Label(); this.closeBtn = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.orderableDataGrid)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.udevelopmentDataGrid)).BeginInit(); this.SuspendLayout(); // // orderableDataGrid // this.orderableDataGrid.CaptionForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.orderableDataGrid.CaptionText = "List of Orderable Products"; this.orderableDataGrid.DataMember = ""; this.orderableDataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.orderableDataGrid.Location = new System.Drawing.Point(72, 112); this.orderableDataGrid.Name = "orderableDataGrid"; this.orderableDataGrid.Size = new System.Drawing.Size(536, 152); this.orderableDataGrid.TabIndex = 0; this.orderableDataGrid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.orderableDataGridTableStyle}); // // orderableDataGridTableStyle // this.orderableDataGridTableStyle.DataGrid = this.orderableDataGrid; this.orderableDataGridTableStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] { this.ProductID, this.ProductName, this.ProductDesc, this.Category, this.Price}); this.orderableDataGridTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.orderableDataGridTableStyle.MappingName = "Products"; this.orderableDataGridTableStyle.ReadOnly = true; // // ProductID // this.ProductID.Format = ""; this.ProductID.FormatInfo = null; this.ProductID.HeaderText = "ID"; this.ProductID.MappingName = "Product_ID"; this.ProductID.Width = 50; // // ProductName // this.ProductName.Format = ""; this.ProductName.FormatInfo = null; this.ProductName.HeaderText = "Name"; this.ProductName.MappingName = "Product_Name"; this.ProductName.Width = 120; // // ProductDesc // this.ProductDesc.Format = ""; this.ProductDesc.FormatInfo = null; this.ProductDesc.HeaderText = "Description"; this.ProductDesc.MappingName = "Product_Desc"; this.ProductDesc.Width = 180; // // Category // this.Category.Format = ""; this.Category.FormatInfo = null; this.Category.HeaderText = "Category"; this.Category.MappingName = "Category"; this.Category.Width = 75; // // Price // this.Price.Format = ""; this.Price.FormatInfo = null; this.Price.HeaderText = "Price $"; this.Price.MappingName = "Price"; this.Price.Width = 56; // // udevelopmentDataGrid // this.udevelopmentDataGrid.CaptionForeColor = System.Drawing.SystemColors.ActiveCaptionText; this.udevelopmentDataGrid.CaptionText = "List of Products Under Development"; this.udevelopmentDataGrid.DataMember = ""; this.udevelopmentDataGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.udevelopmentDataGrid.Location = new System.Drawing.Point(72, 312); this.udevelopmentDataGrid.Name = "udevelopmentDataGrid"; this.udevelopmentDataGrid.Size = new System.Drawing.Size(536, 152); this.udevelopmentDataGrid.TabIndex = 1; this.udevelopmentDataGrid.TableStyles.AddRange(new System.Windows.Forms.DataGridTableStyle[] { this.udevelopmentDataGridTableStyle}); // // udevelopmentDataGridTableStyle // this.udevelopmentDataGridTableStyle.DataGrid = this.udevelopmentDataGrid; this.udevelopmentDataGridTableStyle.GridColumnStyles.AddRange(new System.Windows.Forms.DataGridColumnStyle[] { this.ProductID1, this.ProductName1, this.ProductDesc1, this.Category1, this.Price1}); this.udevelopmentDataGridTableStyle.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.udevelopmentDataGridTableStyle.MappingName = "Products1"; this.udevelopmentDataGridTableStyle.ReadOnly = true; // // ProductID1 // this.ProductID1.Format = ""; this.ProductID1.FormatInfo = null; this.ProductID1.HeaderText = "ID"; this.ProductID1.MappingName = "Product_ID"; this.ProductID1.Width = 51; // // ProductName1 // this.ProductName1.Format = ""; this.ProductName1.FormatInfo = null; this.ProductName1.HeaderText = "Name"; this.ProductName1.MappingName = "Product_Name"; this.ProductName1.Width = 125; // // ProductDesc1 // this.ProductDesc1.Format = ""; this.ProductDesc1.FormatInfo = null; this.ProductDesc1.HeaderText = "Description"; this.ProductDesc1.MappingName = "Product_Desc"; this.ProductDesc1.Width = 180; // // Category1 // this.Category1.Format = ""; this.Category1.FormatInfo = null; this.Category1.HeaderText = "Category"; this.Category1.MappingName = "Category"; this.Category1.Width = 75; // // Price1 // this.Price1.Format = ""; this.Price1.FormatInfo = null; this.Price1.HeaderText = "Price $"; this.Price1.MappingName = "Price"; this.Price1.Width = 64; // // headerLbl // this.headerLbl.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.headerLbl.Font = new System.Drawing.Font("Verdana", 18F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.headerLbl.ForeColor = System.Drawing.Color.Black; this.headerLbl.Location = new System.Drawing.Point(192, 24); this.headerLbl.Name = "headerLbl"; this.headerLbl.Size = new System.Drawing.Size(280, 24); this.headerLbl.TabIndex = 3; this.headerLbl.Text = "Favorite Stores"; this.headerLbl.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // closeBtn // this.closeBtn.BackColor = System.Drawing.SystemColors.Control; this.closeBtn.Font = new System.Drawing.Font("Verdana", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((System.Byte)(0))); this.closeBtn.Location = new System.Drawing.Point(304, 496); this.closeBtn.Name = "closeBtn"; this.closeBtn.Size = new System.Drawing.Size(64, 24); this.closeBtn.TabIndex = 6; this.closeBtn.Text = "Close"; this.closeBtn.Click += new System.EventHandler(this.closeBtn_Click); // // ViewProducts // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(672, 541); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.closeBtn, this.headerLbl, this.udevelopmentDataGrid, this.orderableDataGrid}); this.MaximizeBox = false; this.Name = "ViewProducts"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "ViewProducts"; ((System.ComponentModel.ISupportInitialize)(this.orderableDataGrid)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.udevelopmentDataGrid)).EndInit(); this.ResumeLayout(false); } #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Dynamic; using System.Reflection; using System.Security.Policy; using Noodles.Helpers; namespace Noodles.Models { public class ResourceFactory { public List<Func<object, INode, string, Resource>> Rules = new List<Func<object, INode, string, Resource>>() { CreateReflectionResource }; private static Lazy<ResourceFactory> _instance = new Lazy<ResourceFactory>(() => new ResourceFactory()); public static ResourceFactory Instance { get { return _instance.Value; } } public Resource Create(object target, INode parent, string fragment) { return Rules.Select(r => r(target, parent, fragment)).FirstOrDefault(); } static Resource CreateReflectionResource(object target, INode parent, string fragment) { if (target == null) throw new NullReferenceException("Null resource at'" + parent.Url + "/" + fragment + "' "); var type = target.GetType(); var nodeType = typeof(ReflectionResource<>).MakeGenericType(type); return (ReflectionResource)Activator.CreateInstance(nodeType, target, parent, fragment); } } public class ChildrenAttribute : Attribute { public string KeyName { get; private set; } internal readonly bool _allowEnumeration; public ChildrenAttribute(string key, bool allowEnumeration = false) { KeyName = key; _allowEnumeration = allowEnumeration; } public object ResolveChild(Func<IQueryable> getChildren, string key) { return getChildren().Where(KeyName + " == @0", key).Cast<object>().SingleOrDefault(); } } /// <summary> /// If a property is marked as a Slug, it will be used to build the url instead of the collection index /// </summary> public class SlugAttribute : Attribute { public static string GetSlug(object o) { var pi = GetSlugProperty(o.GetType()); if (pi == null) return null; return pi.GetValue(o) as string; } public static string GetSlugPropertyName(Type valueType) { var slugProperty = GetSlugProperty(valueType); if (slugProperty == null) return null; return slugProperty.Name; } public static PropertyInfo GetSlugProperty(Type valueType) { return valueType.GetProperties(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public) .FirstOrDefault(pi => pi.Attributes().OfType<SlugAttribute>().Any()); } } public class ReflectionResource : Resource { protected ReflectionResource(object target, INode parent, string name) { Value = target; ValueType = target.GetType(); Parent = parent; Name = name; } public string Name { get; set; } public object Value { get; protected set; } public Type ValueType { get; set; } IEnumerable<IInvokeableParameter> IInvokeable.Parameters { get { return this.ChildNodes.OfType<NodeProperty>() .Where(x => !x.Readonly).Select(s => (IInvokeableParameter) s); } } public string InvokeDisplayName { get { return "Save"; } } public Uri InvokeUrl { get { return Url; } } object IInvokeable.Target { get { return this; } } public IEnumerable<object> ChildNodes { get { return this.Value.GetNodeMethods(this).Cast<object>() .Concat(this.Value.GetNodeProperties(this)) .Concat(new[] {QueryableChild.GetChildCollection(this, this.Value)}) .Where(o => o != null); } } public Resource GetChild(string name) { var resolvedChild = new[]{this.Value}.Concat(ChildNodes).OfType<IResolveChild>() .Select(c => c.ResolveChild(name)) .Where(o => o != null) .Select(o => ResourceFactory.Instance.Create(o, this, name)) .FirstOrDefault(); if (resolvedChild != null) return resolvedChild; var childResource = this.ChildNodes.OfType<Resource>() .SingleOrDefault(np => np.Name.ToLowerInvariant() == name.ToLowerInvariant()); if (childResource != null) return childResource; return this.ChildNodes.OfType<NodeProperty>() .Where(np => np.Name.ToLowerInvariant() == name.ToLowerInvariant()) .Select(np => np.GetResource()) .SingleOrDefault(); } public string DisplayName { get { return Value.GetDisplayName(); } } public Uri Url { get { return Parent == null ? new Uri("/", UriKind.Relative) : (new Uri(Parent.Url.ToString() + Name + "/", UriKind.Relative)); } set { } } Type IInvokeable.ParameterType { get { return ValueType; } } Type IInvokeable.ResultType { get { return this.GetType(); } } public object Invoke(IDictionary<string, object> parameterDictionary) { foreach (var key in parameterDictionary.Keys) { var p = this.ChildNodes.OfType<NodeProperty>().SingleOrDefault(x => x.Readonly == false && x.Name == key); if (p == null) continue; p.SetValue(parameterDictionary[key]); } return null; } T IInvokeable.GetAttribute<T>() { return this.Attributes().OfType<T>().SingleOrDefault(); } public int Order { get { return int.MaxValue; } } public INode Parent { get; protected set; } INode INode.Parent { get { return Parent; } } public string UiHint { get { return ""; } } public Uri RootUrl { set { }} public IEnumerable<Attribute> Attributes { get { return this.Value.Attributes(); } } } public class ReflectionResource<T> : ReflectionResource, Resource<T>, INode<T> { public new T Target { get { return (T)base.Value; } } public ReflectionResource(T target, INode parent, string name):base(target, parent, name) { } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32; using Microsoft.Win32.SafeHandles; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.ConstrainedExecution; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Threading; using System.Runtime.Versioning; namespace System.Runtime.Caching { internal static class Dbg { #if DEBUG static readonly DateTime MinValuePlusOneDay = DateTime.MinValue.AddDays(1); static readonly DateTime MaxValueMinusOneDay = DateTime.MaxValue.AddDays(-1); #endif internal const string TAG_INTERNAL = "Internal"; internal const string TAG_EXTERNAL = "External"; internal const string TAG_ALL = "*"; internal const string DATE_FORMAT = @"yyyy/MM/dd HH:mm:ss.ffff"; internal const string TIME_FORMAT = @"HH:mm:ss:ffff"; #if DEBUG private static class NativeMethods { [DllImport("kernel32.dll")] internal extern static void DebugBreak(); [DllImport("kernel32.dll")] internal extern static int GetCurrentProcessId(); [DllImport("kernel32.dll")] internal extern static int GetCurrentThreadId(); [DllImport("kernel32.dll", CharSet=CharSet.Auto, SetLastError=true)] internal extern static IntPtr GetCurrentProcess(); [DllImport("kernel32.dll")] internal extern static bool IsDebuggerPresent(); [DllImport("kernel32.dll", SetLastError=true)] internal extern static bool TerminateProcess(HandleRef processHandle, int exitCode); internal const int PM_NOREMOVE = 0x0000; internal const int PM_REMOVE = 0x0001; [StructLayout(LayoutKind.Sequential)] internal struct MSG { internal IntPtr hwnd; internal int message; internal IntPtr wParam; internal IntPtr lParam; internal int time; internal int pt_x; internal int pt_y; } //[DllImport("user32.dll", CharSet=CharSet.Auto)] //internal extern static bool PeekMessage([In, Out] ref MSG msg, HandleRef hwnd, int msgMin, int msgMax, int remove); internal const int MB_OK = 0x00000000, MB_OKCANCEL = 0x00000001, MB_ABORTRETRYIGNORE = 0x00000002, MB_YESNOCANCEL = 0x00000003, MB_YESNO = 0x00000004, MB_RETRYCANCEL = 0x00000005, MB_ICONHAND = 0x00000010, MB_ICONQUESTION = 0x00000020, MB_ICONEXCLAMATION = 0x00000030, MB_ICONASTERISK = 0x00000040, MB_USERICON = 0x00000080, MB_ICONWARNING = 0x00000030, MB_ICONERROR = 0x00000010, MB_ICONINFORMATION = 0x00000040, MB_DEFBUTTON1 = 0x00000000, MB_DEFBUTTON2 = 0x00000100, MB_DEFBUTTON3 = 0x00000200, MB_DEFBUTTON4 = 0x00000300, MB_APPLMODAL = 0x00000000, MB_SYSTEMMODAL = 0x00001000, MB_TASKMODAL = 0x00002000, MB_HELP = 0x00004000, MB_NOFOCUS = 0x00008000, MB_SETFOREGROUND = 0x00010000, MB_DEFAULT_DESKTOP_ONLY = 0x00020000, MB_TOPMOST = 0x00040000, MB_RIGHT = 0x00080000, MB_RTLREADING = 0x00100000, MB_SERVICE_NOTIFICATION = 0x00200000, MB_SERVICE_NOTIFICATION_NT3X = 0x00040000, MB_TYPEMASK = 0x0000000F, MB_ICONMASK = 0x000000F0, MB_DEFMASK = 0x00000F00, MB_MODEMASK = 0x00003000, MB_MISCMASK = 0x0000C000; internal const int IDOK = 1, IDCANCEL = 2, IDABORT = 3, IDRETRY = 4, IDIGNORE = 5, IDYES = 6, IDNO = 7, IDCLOSE = 8, IDHELP = 9; //[DllImport("user32.dll", CharSet=CharSet.Auto, BestFitMapping=false)] //internal extern static int MessageBox(HandleRef hWnd, string text, string caption, int type); internal static readonly IntPtr HKEY_LOCAL_MACHINE = unchecked((IntPtr)(int)0x80000002); internal const int READ_CONTROL = 0x00020000; internal const int STANDARD_RIGHTS_READ = READ_CONTROL; internal const int SYNCHRONIZE = 0x00100000; internal const int KEY_QUERY_VALUE = 0x0001; internal const int KEY_ENUMERATE_SUB_KEYS = 0x0008; internal const int KEY_NOTIFY = 0x0010; internal const int KEY_READ = ((STANDARD_RIGHTS_READ | KEY_QUERY_VALUE | KEY_ENUMERATE_SUB_KEYS | KEY_NOTIFY) & (~SYNCHRONIZE)); internal const int REG_NOTIFY_CHANGE_NAME = 1; internal const int REG_NOTIFY_CHANGE_LAST_SET = 4; [DllImport("advapi32.dll", CharSet=CharSet.Auto, BestFitMapping=false, SetLastError=true)] internal extern static int RegOpenKeyEx(IntPtr hKey, string lpSubKey, int ulOptions, int samDesired, out SafeRegistryHandle hkResult); [DllImport("advapi32.dll", ExactSpelling=true, SetLastError=true)] internal extern static int RegNotifyChangeKeyValue(SafeRegistryHandle hKey, bool watchSubTree, uint notifyFilter, SafeWaitHandle regEvent, bool async); } private enum TagValue { Disabled = 0, Enabled = 1, Break = 2, Min = Disabled, Max = Break, } private const string TAG_ASSERT = "Assert"; private const string TAG_ASSERT_BREAK = "AssertBreak"; private const string TAG_DEBUG_VERBOSE = "DebugVerbose"; private const string TAG_DEBUG_MONITOR = "DebugMonitor"; private const string TAG_DEBUG_PREFIX = "DebugPrefix"; private const string TAG_DEBUG_THREAD_PREFIX = "DebugThreadPrefix"; private const string PRODUCT = "Microsoft .NET Framework"; private const string COMPONENT = "System.Web"; private static string s_regKeyName = @"Software\Microsoft\ASP.NET\Debug"; private static string s_listenKeyName = @"Software\Microsoft"; private static bool s_assert; private static bool s_assertBreak; private static bool s_includePrefix; private static bool s_includeThreadPrefix; private static bool s_monitor; private static object s_lock; private static volatile bool s_inited; private static ReadOnlyCollection<Tag> s_tagDefaults; private static List<Tag> s_tags; private static AutoResetEvent s_notifyEvent; private static RegisteredWaitHandle s_waitHandle; private static SafeRegistryHandle s_regHandle; private static bool s_stopMonitoring; private static Hashtable s_tableAlwaysValidate; private static Type[] s_DumpArgs; private static Type[] s_ValidateArgs; private class Tag { string _name; TagValue _value; int _prefixLength; internal Tag(string name, TagValue value) { _name = name; _value = value; if (_name[_name.Length - 1] == '*') { _prefixLength = _name.Length - 1; } else { _prefixLength = -1; } } internal string Name { get {return _name;} } internal TagValue Value { get {return _value;} } internal int PrefixLength { get {return _prefixLength;} } } static Dbg() { s_lock = new object(); } private static void EnsureInit() { bool continueInit = false; if (!s_inited) { lock (s_lock) { if (!s_inited) { s_tableAlwaysValidate = new Hashtable(); s_DumpArgs = new Type[1] {typeof(string)}; s_ValidateArgs = new Type[0]; List<Tag> tagDefaults = new List<Tag>(); tagDefaults.Add(new Tag(TAG_ALL, TagValue.Disabled)); tagDefaults.Add(new Tag(TAG_INTERNAL, TagValue.Enabled)); tagDefaults.Add(new Tag(TAG_EXTERNAL, TagValue.Enabled)); tagDefaults.Add(new Tag(TAG_ASSERT, TagValue.Break)); tagDefaults.Add(new Tag(TAG_ASSERT_BREAK, TagValue.Disabled)); tagDefaults.Add(new Tag(TAG_DEBUG_VERBOSE, TagValue.Enabled)); tagDefaults.Add(new Tag(TAG_DEBUG_MONITOR, TagValue.Enabled)); tagDefaults.Add(new Tag(TAG_DEBUG_PREFIX, TagValue.Enabled)); tagDefaults.Add(new Tag(TAG_DEBUG_THREAD_PREFIX, TagValue.Enabled)); s_tagDefaults = tagDefaults.AsReadOnly(); s_tags = new List<Tag>(s_tagDefaults); GetBuiltinTagValues(); continueInit = true; s_inited = true; } } } // Work to do outside the init lock. if (continueInit) { ReadTagsFromRegistry(); Trace(TAG_DEBUG_VERBOSE, "Debugging package initialized"); // Need to read tags before starting to monitor in order to get TAG_DEBUG_MONITOR StartRegistryMonitor(); } } private static bool StringEqualsIgnoreCase(string s1, string s2) { return StringComparer.OrdinalIgnoreCase.Equals(s1, s2); } private static void WriteTagsToRegistry() { try { using (RegistryKey key = Registry.LocalMachine.CreateSubKey(s_regKeyName)) { List<Tag> tags = s_tags; foreach (Tag tag in tags) { key.SetValue(tag.Name, tag.Value, RegistryValueKind.DWord); } } } catch { } } private static void GetBuiltinTagValues() { // Use GetTagValue instead of IsTagEnabled because it does not call EnsureInit // and potentially recurse. s_assert = (GetTagValue(TAG_ASSERT) != TagValue.Disabled); s_assertBreak = (GetTagValue(TAG_ASSERT_BREAK) != TagValue.Disabled); s_includePrefix = (GetTagValue(TAG_DEBUG_PREFIX) != TagValue.Disabled); s_includeThreadPrefix = (GetTagValue(TAG_DEBUG_THREAD_PREFIX) != TagValue.Disabled); s_monitor = (GetTagValue(TAG_DEBUG_MONITOR) != TagValue.Disabled); } private static void ReadTagsFromRegistry() { lock (s_lock) { try { List<Tag> tags = new List<Tag>(s_tagDefaults); string[] names = null; bool writeTags = false; using (RegistryKey key = Registry.LocalMachine.OpenSubKey(s_regKeyName, false)) { if (key != null) { names = key.GetValueNames(); foreach (string name in names) { TagValue value = TagValue.Disabled; try { TagValue keyvalue = (TagValue) key.GetValue(name); if (TagValue.Min <= keyvalue && keyvalue <= TagValue.Max) { value = keyvalue; } else { writeTags = true; } } catch { writeTags = true; } // Add tag to list, making sure it is unique. Tag tag = new Tag(name, (TagValue) value); bool found = false; for (int i = 0; i < s_tagDefaults.Count; i++) { if (StringEqualsIgnoreCase(name, tags[i].Name)) { found = true; tags[i] = tag; break; } } if (!found) { tags.Add(tag); } } } } s_tags = tags; GetBuiltinTagValues(); // Write tags out if there was an invalid value or // not all default tags are present. if (writeTags || (names != null && names.Length < tags.Count)) { WriteTagsToRegistry(); } } catch { s_tags = new List<Tag>(s_tagDefaults); } } } private static void StartRegistryMonitor() { if (!s_monitor) { Trace(TAG_DEBUG_VERBOSE, "WARNING: Registry monitoring disabled, changes during process execution will not be recognized."); return; } Trace(TAG_DEBUG_VERBOSE, "Monitoring registry key " + s_listenKeyName + " for changes."); // Event used to notify of changes. s_notifyEvent = new AutoResetEvent(false); // Register a wait on the event. s_waitHandle = ThreadPool.RegisterWaitForSingleObject(s_notifyEvent, OnRegChangeKeyValue, null, -1, false); // Monitor the registry. MonitorRegistryForOneChange(); } private static void StopRegistryMonitor() { // Cleanup allocated handles s_stopMonitoring = true; if (s_regHandle != null) { s_regHandle.Close(); s_regHandle = null; } if (s_waitHandle != null) { s_waitHandle.Unregister(s_notifyEvent); s_waitHandle = null; } if (s_notifyEvent != null) { s_notifyEvent.Close(); s_notifyEvent = null; } Trace(TAG_DEBUG_VERBOSE, "Registry monitoring stopped."); } public static void OnRegChangeKeyValue(object state, bool timedOut) { if (!s_stopMonitoring) { if (timedOut) { StopRegistryMonitor(); } else { // Monitor again MonitorRegistryForOneChange(); // Once we're monitoring, read the changes to the registry. // We have to do this after we start monitoring in order // to catch all changes to the registry. ReadTagsFromRegistry(); } } } private static void MonitorRegistryForOneChange() { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { // Close the open reg handle if (s_regHandle != null) { s_regHandle.Close(); s_regHandle = null; } // Open the reg key int result = NativeMethods.RegOpenKeyEx(NativeMethods.HKEY_LOCAL_MACHINE, s_listenKeyName, 0, NativeMethods.KEY_READ, out s_regHandle); if (result != 0) { StopRegistryMonitor(); return; } // Listen for changes. result = NativeMethods.RegNotifyChangeKeyValue( s_regHandle, true, NativeMethods.REG_NOTIFY_CHANGE_NAME | NativeMethods.REG_NOTIFY_CHANGE_LAST_SET, s_notifyEvent.SafeWaitHandle, true); if (result != 0) { StopRegistryMonitor(); } } } private static Tag FindMatchingTag(string name, bool exact) { List<Tag> tags = s_tags; // Look for exact match first foreach (Tag tag in tags) { if (StringEqualsIgnoreCase(name, tag.Name)) { return tag; } } if (exact) { return null; } Tag longestTag = null; int longestPrefix = -1; foreach (Tag tag in tags) { if ( tag.PrefixLength > longestPrefix && 0 == string.Compare(name, 0, tag.Name, 0, tag.PrefixLength, StringComparison.OrdinalIgnoreCase)) { longestTag = tag; longestPrefix = tag.PrefixLength; } } return longestTag; } private static TagValue GetTagValue(string name) { Tag tag = FindMatchingTag(name, false); if (tag != null) { return tag.Value; } else { return TagValue.Disabled; } } private static bool TraceBreak(string tagName, string message, Exception e, bool includePrefix) { EnsureInit(); TagValue tagValue = GetTagValue(tagName); if (tagValue == TagValue.Disabled) { return false; } bool isAssert = object.ReferenceEquals(tagName, TAG_ASSERT); if (isAssert) { tagName = ""; } string exceptionMessage = null; if (e != null) { string httpCode = null; string errorCode = null; if (e is ExternalException) { // note that HttpExceptions are ExternalExceptions errorCode = "_hr=0x" + ((ExternalException)e).ErrorCode.ToString("x", CultureInfo.InvariantCulture); } // Use e.ToString() in order to get inner exception if (errorCode != null) { exceptionMessage = "Exception " + e.ToString() + "\n" + httpCode + errorCode; } else { exceptionMessage = "Exception " + e.ToString(); } } if (string.IsNullOrEmpty(message) & exceptionMessage != null) { message = exceptionMessage; exceptionMessage = null; } string traceFormat; int idThread = 0; int idProcess = 0; if (!includePrefix || !s_includePrefix) { traceFormat = "{4}\n{5}"; } else { if (s_includeThreadPrefix) { idThread = Thread.CurrentThread.ManagedThreadId; using(var process = Process.GetCurrentProcess()) { idProcess = process.Id; } traceFormat = "[0x{0:x}.{1:x} {2} {3}] {4}\n{5}"; } else { traceFormat = "[{2} {3}] {4}\n{5}"; } } string suffix = ""; if (exceptionMessage != null) { suffix += exceptionMessage + "\n"; } bool doBreak = (tagValue == TagValue.Break); if (doBreak && !isAssert) { suffix += "Breaking into debugger...\n"; } string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, idProcess, idThread, COMPONENT, tagName, message, suffix); Debug.WriteLine(traceMessage); return doBreak; } //private class MBResult { // internal int Result; //} [ResourceExposure(ResourceScope.None)] static bool DoAssert(string message) { if (!s_assert) { return false; } // Skip 2 frames - one for this function, one for // the public Assert function that called this function. StackFrame frame = new StackFrame(2, true); StackTrace trace = new StackTrace(2, true); string fileName = frame.GetFileName(); int lineNumber = frame.GetFileLineNumber(); string traceFormat; if (!string.IsNullOrEmpty(fileName)) { traceFormat = "ASSERTION FAILED: {0}\nFile: {1}:{2}\nStack trace:\n{3}"; } else { traceFormat = "ASSERTION FAILED: {0}\nStack trace:\n{3}"; } string traceMessage = string.Format(CultureInfo.InvariantCulture, traceFormat, message, fileName, lineNumber, trace.ToString()); if (!TraceBreak(TAG_ASSERT, traceMessage, null, true)) { // If the value of "Assert" is not TagValue.Break, then don't even ask user. return false; } if (s_assertBreak) { // If "AssertBreak" is enabled, then always break. return true; } string dialogFormat; if (!string.IsNullOrEmpty(fileName)) { dialogFormat = @"Failed expression: {0} File: {1}:{2} Component: {3} PID={4} TID={5} Stack trace: {6} A=Exit process R=Debug I=Continue"; } else { dialogFormat = @"Failed expression: {0} (no file information available) Component: {3} PID={4} TID={5} Stack trace: {6} A=Exit process R=Debug I=Continue"; } int idProcess = 0; using (var process = Process.GetCurrentProcess()) { idProcess = process.Id; } string dialogMessage = string.Format( CultureInfo.InvariantCulture, dialogFormat, message, fileName, lineNumber, COMPONENT, idProcess, Thread.CurrentThread.ManagedThreadId, trace.ToString()); Debug.Fail(dialogMessage); return true; } #endif // // Sends the message to the debugger if the tag is enabled. // Also breaks into the debugger the value of the tag is 2 (TagValue.Break). // [Conditional("DEBUG")] internal static void Trace(string tagName, string message) { #if DEBUG if (TraceBreak(tagName, message, null, true)) { Break(); } #endif } // // Sends the message to the debugger if the tag is enabled. // Also breaks into the debugger the value of the tag is 2 (TagValue.Break). // [Conditional("DEBUG")] internal static void Trace(string tagName, string message, bool includePrefix) { #if DEBUG if (TraceBreak(tagName, message, null, includePrefix)) { Break(); } #endif } // // Sends the message to the debugger if the tag is enabled. // Also breaks into the debugger the value of the tag is 2 (TagValue.Break). // [Conditional("DEBUG")] internal static void Trace(string tagName, string message, Exception e) { #if DEBUG if (TraceBreak(tagName, message, e, true)) { Break(); } #endif } // // Sends the message to the debugger if the tag is enabled. // Also breaks into the debugger the value of the tag is 2 (TagValue.Break). // [Conditional("DEBUG")] internal static void Trace(string tagName, Exception e) { #if DEBUG if (TraceBreak(tagName, null, e, true)) { Break(); } #endif } // // Sends the message to the debugger if the tag is enabled. // Also breaks into the debugger the value of the tag is 2 (TagValue.Break). // [Conditional("DEBUG")] internal static void Trace(string tagName, string message, Exception e, bool includePrefix) { #if DEBUG if (TraceBreak(tagName, message, e, includePrefix)) { Break(); } #endif } #if DEBUG #endif [Conditional("DEBUG")] public static void TraceException(String tagName, Exception e) { #if DEBUG if (TraceBreak(tagName, null, e, true)) { Break(); } #endif } // // If the assertion is false and the 'Assert' tag is enabled: // * Send a message to the debugger. // * If the 'AssertBreak' tag is enabled, immediately break into the debugger // * Else display a dialog box asking the user to Abort, Retry (break), or Ignore // [Conditional("DEBUG")] internal static void Assert(bool assertion, string message) { #if DEBUG EnsureInit(); if (assertion == false) { if (DoAssert(message)) { Break(); } } #endif } // // If the assertion is false and the 'Assert' tag is enabled: // * Send a message to the debugger. // * If the 'AssertBreak' tag is enabled, immediately break into the debugger // * Else display a dialog box asking the user to Abort, Retry (break), or Ignore // [Conditional("DEBUG")] [ResourceExposure(ResourceScope.None)] internal static void Assert(bool assertion) { #if DEBUG EnsureInit(); if (assertion == false) { if (DoAssert(null)) { Break(); } } #endif } // // Like Assert, but the assertion is always considered to be false. // [Conditional("DEBUG")] [ResourceExposure(ResourceScope.None)] internal static void Fail(string message) { #if DEBUG Assert(false, message); #endif } // // Returns true if the tag is enabled, false otherwise. // Note that the tag needn't be an exact match. // [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] [ResourceExposure(ResourceScope.None)] internal static bool IsTagEnabled(string tagName) { #if DEBUG EnsureInit(); return GetTagValue(tagName) != TagValue.Disabled; #else return false; #endif } // // Returns true if the tag present. // This function chekcs for an exact match. // [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] [ResourceExposure(ResourceScope.None)] internal static bool IsTagPresent(string tagName) { #if DEBUG EnsureInit(); return FindMatchingTag(tagName, true) != null; #else return false; #endif } // // Breaks into the debugger, or launches one if not yet attached. // [Conditional("DEBUG")] [ResourceExposure(ResourceScope.None)] internal static void Break() { #if DEBUG if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && NativeMethods.IsDebuggerPresent()) { NativeMethods.DebugBreak(); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && !Debugger.IsAttached) { Debugger.Launch(); } else { Debugger.Break(); } #endif } // // Tells the debug system to always validate calls for a // particular tag. This is useful for temporarily enabling // validation in stress tests or other situations where you // may not have control over the debug tags that are enabled // on a particular machine. // [Conditional("DEBUG")] internal static void AlwaysValidate(string tagName) { #if DEBUG EnsureInit(); s_tableAlwaysValidate[tagName] = tagName; #endif } // // Throws an exception if the assertion is not valid. // Use this function from a DebugValidate method where // you would otherwise use Assert. // [Conditional("DEBUG")] internal static void CheckValid(bool assertion, string message) { #if DEBUG if (!assertion) { throw new Exception(message); } #endif } // // Calls DebugValidate on an object if such a method exists. // // This method should be used from implementations of DebugValidate // where it is unknown whether an object has a DebugValidate method. // For example, the DoubleLink class uses it to validate the // item of type Object which it points to. // // This method should NOT be used when code wants to conditionally // validate an object and have a failed validation caught in an assert. // Use Debug.Validate(tagName, obj) for that purpose. // [Conditional("DEBUG")] [ResourceExposure(ResourceScope.None)] internal static void Validate(Object obj) { #if DEBUG Type type; MethodInfo mi; if (obj != null) { type = obj.GetType(); mi = type.GetMethod( "DebugValidate", BindingFlags.NonPublic | BindingFlags.Instance, null, s_ValidateArgs, null); if (mi != null) { object[] tempIndex = null; mi.Invoke(obj, tempIndex); } } #endif } // // Validates an object is the "Validate" tag is enabled, or when // the "Validate" tag is not disabled and the given 'tag' is enabled. // An Assertion is made if the validation fails. // [Conditional("DEBUG")] [ResourceExposure(ResourceScope.None)] internal static void Validate(string tagName, Object obj) { #if DEBUG EnsureInit(); if ( obj != null && ( IsTagEnabled("Validate") || ( !IsTagPresent("Validate") && ( s_tableAlwaysValidate[tagName] != null || IsTagEnabled(tagName))))) { try { Validate(obj); } catch (Exception e) { Assert(false, "Validate failed: " + e.InnerException.Message); } #pragma warning disable 1058 catch { Assert(false, "Validate failed. Non-CLS compliant exception caught."); } #pragma warning restore 1058 } #endif } #if DEBUG // // Calls DebugDescription on an object to get its description. // // This method should only be used in implementations of DebugDescription // where it is not known whether a nested objects has an implementation // of DebugDescription. For example, the double linked list class uses // GetDescription to get the description of the item it points to. // // This method should NOT be used when you want to conditionally // dump an object. Use Debug.Dump instead. // // @param obj The object to call DebugDescription on. May be null. // @param indent A prefix for each line in the description. This is used // to allow the nested display of objects within other objects. // The indent is usually a multiple of four spaces. // // @return The description. // internal static string GetDescription(Object obj, string indent) { string description; Type type; MethodInfo mi; Object[] parameters; if (obj == null) { description = "\n"; } else { type = obj.GetType(); mi = type.GetMethod( "DebugDescription", BindingFlags.NonPublic | BindingFlags.Instance, null, s_DumpArgs, null); if (mi == null || mi.ReturnType != typeof(string)) { description = indent + obj.ToString(); } else { parameters = new Object[1] {(Object) indent}; description = (string) mi.Invoke(obj, parameters); } } return description; } #endif // // Dumps an object to the debugger if the "Dump" tag is enabled, // or if the "Dump" tag is not present and the 'tag' is enabled. // // @param tagName The tag to Dump with. // @param obj The object to dump. // [Conditional("DEBUG")] internal static void Dump(string tagName, Object obj) { #if DEBUG EnsureInit(); string description; string traceTag = null; bool dumpEnabled, dumpPresent; if (obj != null) { dumpEnabled = IsTagEnabled("Dump"); dumpPresent = IsTagPresent("Dump"); if (dumpEnabled || !dumpPresent) { if (IsTagEnabled(tagName)) { traceTag = tagName; } else if (dumpEnabled) { traceTag = "Dump"; } if (traceTag != null) { description = GetDescription(obj, string.Empty); Trace(traceTag, "Dump\n" + description); } } } #endif } [SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Justification = "Grandfathered suppression from original caching code checkin")] static internal string FormatLocalDate(DateTime localTime) { #if DEBUG return localTime.ToString(DATE_FORMAT, CultureInfo.InvariantCulture); #else return string.Empty; #endif } } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Permissive License. // See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL. // All other rights reserved. using System; using System.Globalization; using System.Windows; using System.Windows.Automation; using System.Collections; using System.Threading; using System.Reflection; using System.Xml; using System.Runtime.InteropServices; using System.Text; using System.IO; using System.CodeDom; using System.Security; using System.Security.Permissions; using System.Resources; namespace Microsoft.Test.UIAutomation { using Microsoft.Test.UIAutomation; using Microsoft.Test.UIAutomation.Core; using Microsoft.Test.UIAutomation.Tests.Patterns; using Microsoft.Test.UIAutomation.Tests.Controls; using Microsoft.Test.UIAutomation.Tests.Scenarios; using Microsoft.Test.UIAutomation.Interfaces; using Microsoft.Test.UIAutomation.TestManager; using InternalHelper.Enumerations; using InternalHelper.Tests; using InternalHelper; using Microsoft.Test.UIAutomation.Logging; /// ----------------------------------------------------------------------- /// <summary></summary> /// ----------------------------------------------------------------------- public sealed class TestRuns { // This is an array of elements that if we find them as child elements, // only run one of the children...don't run every sibling with the // same control type, there is no need to test out each and every // list item if we are testing out a controls children static string[] m_Duplicate = new string[] { ControlType.Button.ProgrammaticName, ControlType.Custom.ProgrammaticName, ControlType.DataItem.ProgrammaticName, ControlType.Group.ProgrammaticName, ControlType.HeaderItem.ProgrammaticName, ControlType.Hyperlink.ProgrammaticName, ControlType.Image.ProgrammaticName, ControlType.ListItem.ProgrammaticName, ControlType.MenuItem.ProgrammaticName, ControlType.Separator.ProgrammaticName, ControlType.SplitButton.ProgrammaticName, ControlType.TabItem.ProgrammaticName, ControlType.Thumb.ProgrammaticName, ControlType.TreeItem.ProgrammaticName }; /// <summary> /// Defined so it would pass FxCop rules. /// </summary> TestRuns() { } #region Data Members and Properties /// ------------------------------------------------------------------- /// <summary> /// Command line argument that sets TestObject property indicating if /// UIA Verify should preserve existing content for controls that support /// TextPattern/ValuePattenrn. /// Set to TRUE if contents hould be preserved, i.e. not clobbered /// </summary> /// ------------------------------------------------------------------- public static bool NoClobber { get { return TestObject._noClobber; } set { TestObject._noClobber = value; } } static bool _filterOutBugs = true; /// ------------------------------------------------------------------- /// <summary>Set it to false if you want the tests to report failures /// for known issues./// </summary> /// ------------------------------------------------------------------- public static bool FilterOutBugs { get { return TestRuns._filterOutBugs; } set { TestRuns._filterOutBugs = value; } } static string _bugFilterFile = string.Empty; /// ------------------------------------------------------------------- /// <summary>Bug filter file</summary> /// ------------------------------------------------------------------- public static string BugFilterFile { get { return TestRuns._bugFilterFile; } set { TestRuns._bugFilterFile = value; } } static bool _isClientSideProviderLoaded = true; /// ------------------------------------------------------------------- /// <summary>Bug filter file</summary> /// ------------------------------------------------------------------- public static bool IsClientSideProviderLoaded { get { return _isClientSideProviderLoaded; } } [DllImport("UIAutomationCore.dll", CharSet = CharSet.Unicode)] private static extern void UiaRegisterProviderCallback(IntPtr callback); /// ------------------------------------------------------------------- /// <summary>Different ways that the proxies are setup.</summary> /// ------------------------------------------------------------------- public enum ProxyVersionEnum { /// <summary> /// Standard managed proxies used in Vista timeframe. Default setting for TestRuns.ProxyVersion /// </summary> Vista, /// <summary> /// Use TestRuns.UiaRegisterProviderCallback() to use this setting /// </summary> ProviderCallbackNull } /// ------------------------------------------------------------------- /// <summary>Returns the different ways that the proxies are setup.</summary> /// ------------------------------------------------------------------- static ProxyVersionEnum _proxyVersion = ProxyVersionEnum.Vista; /// ------------------------------------------------------------------- /// <summary>Returns the different ways that the proxies are setup.</summary> /// ------------------------------------------------------------------- public static ProxyVersionEnum ProxyVersion { get { return _proxyVersion; } } /// ------------------------------------------------------------------- /// <summary>String property for the command line that started this test /// run. No required.</summary> /// ------------------------------------------------------------------- static string _commandLine = string.Empty; /// ------------------------------------------------------------------- /// <summary>String property for the command line that started this test /// run. No required.</summary> /// ------------------------------------------------------------------- public static string CommandLine { set { _commandLine = value; } get { return _commandLine; } } /// ------------------------------------------------------------------- /// <summary>Calls UiaRegisterProviderCallback(IntPtr.Zero) which unregisters /// the client side providers.</summary> /// ------------------------------------------------------------------- public static void UnRegisterProviderCallback() { UIVerifyLogger.LogComment("Calling UiaRegisterProviderCallback(IntPtr.Zero)"); _isClientSideProviderLoaded = false; UiaRegisterProviderCallback(IntPtr.Zero); } #endregion Data Members and Properties #region Entry for running tests #region Scenarios specific tests /// ------------------------------------------------------------------ /// <summary> /// Run the specified scenario test /// </summary> /// ------------------------------------------------------------------ public static bool RunScenarioTest(string testSuite, string testName, object arguments, bool testEvents, IApplicationCommands commands) { return RunScenarioTest(null, testSuite, testName, arguments, testEvents, commands); } /// ------------------------------------------------------------------ /// <summary> /// Run the specified pattern test /// </summary> /// ------------------------------------------------------------------ public static bool RunScenarioTest(AutomationElement element, string testSuite, string testName, object arguments, bool testEvents, IApplicationCommands commands) { object testObject = TestObject.GetScenarioTestObject(testSuite, element, testEvents, TestPriorities.PriAll, commands); // Test this object return ((TestObject)testObject).InvokeSceanario(testSuite, testName, arguments); } #endregion #region Pattern specific tests /// ------------------------------------------------------------------ /// <summary> /// Run the specified pattern test /// </summary> /// ------------------------------------------------------------------ public static bool RunPatternTest(AutomationElement element, bool testEvents, bool testChildren, string testSuite, string test, object arguments, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object testObject = TestObject.GetPatternTestObject(testSuite, element, testEvents, TestPriorities.PriAll, commands); passed &= ((TestObject)testObject).InvokeTest(testSuite, test, arguments); if (testChildren) { passed &= RunPatternTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, testSuite, test, arguments, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Run all the tests associated with the pattern as defiend by testSuite /// </summary> /// ------------------------------------------------------------------- public static bool RunPatternTests(AutomationElement element, bool testEvents, bool testChildren, string testSuite, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object testObject = TestObject.GetPatternTestObject(testSuite, element, testEvents, TestPriorities.PriAll, commands); passed &= ((TestObject)testObject).InvokeTests(testSuite, testCaseType); if (testChildren) { passed &= RunPatternTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, testSuite, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Run all the tests associated with the defined pattern and that meet /// the criteria as supplied as arguments /// </summary> /// ------------------------------------------------------------------- public static bool RunPatternTests(AutomationElement element, bool testEvents, TestPriorities priority, TestCaseType testCaseType, string testSuite, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object testObject = TestObject.GetPatternTestObject(testSuite, element, testEvents, priority, commands); passed &= ((TestObject)testObject).InvokeTests(testSuite, testCaseType); } catch (Exception exception) { if (exception.InnerException != null && !(exception.InnerException is IncorrectElementConfigurationForTestException)) UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } #endregion Pattern specific tests #region Control specific tests /// ------------------------------------------------------------------ /// <summary> /// /// </summary> /// <returns></returns> /// ------------------------------------------------------------------ public static bool RunControlTests(AutomationElement element, bool testEvents, bool testChildren, TestPriorities priority, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { string testSuite = TestObject.GetTestType(element); object testObject = TestObject.GetControlTestObject(element, testEvents, priority, commands); passed &= ((TestObject)testObject).InvokeTests(testSuite, testCaseType); if (testChildren) { passed &= RunControlTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, priority, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } private static bool RunControlTestsOnDescendants(AutomationElement element, bool testEvents, bool testChildren, TestPriorities priority, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { string testSuite = TestObject.GetTestType(element); object testObject = TestObject.GetControlTestObject(element, testEvents, TestPriorities.PriAll, commands); passed &= ((TestObject)testObject).InvokeTests(testSuite, testCaseType); if (testChildren) { passed &= RunControlTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, priority, testCaseType, commands); passed &= RunControlTestsOnDescendants(TreeWalker.ControlViewWalker.GetNextSibling(element), testEvents, testChildren, priority, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Run the specified control test by name /// </summary> /// ------------------------------------------------------------------- public static bool RunControlTest(AutomationElement element, bool testEvents, string testSuite, string test, object arguments, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object testObject = TestObject.GetControlTestObject(element, testEvents, TestPriorities.PriAll, commands); passed &= ((TestObject)testObject).InvokeTest(testSuite, test, arguments); } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } #endregion Control specific tests #region Versions of All* tests /// ------------------------------------------------------------------ /// <summary> /// Run all the tests for patterns, control type, and AutomationElement that meet the criteria as supplied as arguments /// </summary> /// <returns></returns> /// ------------------------------------------------------------------ public static bool RunAllTests(AutomationElement element, bool testEvents, TestPriorities priority, TestCaseType testCaseType, bool testChildren, bool normalize, IApplicationCommands commands) { bool passed = true; if (element != null) { try { passed &= RunAllControlTests(element, testEvents, priority, testCaseType, testChildren, normalize, commands); passed &= RunAutomationElementTests(element, testEvents, priority, testCaseType, testChildren, normalize, commands); passed &= RunAllPatternTests(element, testEvents, priority, testCaseType, testChildren, normalize, commands); } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Run all the supported pattern tests associated with the element and that meet /// the criteria as supplied as arguments /// </summary> /// ------------------------------------------------------------------- public static bool RunAllPatternTests(AutomationElement element, bool testEvents, TestPriorities priority, TestCaseType testCaseType, bool testChildren, bool normalize, IApplicationCommands commands) { bool passed = true; if (element != null) { try { ArrayList al = Helpers.GetPatternSuitesForAutomationElement(element); foreach (string testSuite in al) { passed &= RunPatternTests(element, testEvents, priority, testCaseType, testSuite, commands); } if (testChildren) { passed &= RunAllPatternTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, priority, normalize, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Run all control tests, pattern tests, and automation element tests /// </summary> /// ------------------------------------------------------------------- public static bool RunAllControlTests(AutomationElement element, bool testEvents, TestPriorities priority, TestCaseType testCaseType, bool testChildren, bool normalize, IApplicationCommands commands) { bool passed = true; if (element != null) { try { passed &= RunControlTests(element, testEvents, false, priority, testCaseType, commands); if (testChildren) { passed &= RunAllControlTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, priority, normalize, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } #endregion Versions of All* tests #region Misc /// ------------------------------------------------------------------- /// <summary> /// Run all the AutomationElement tests on the element that meet the /// criteria as supplied as arguments /// </summary> /// ------------------------------------------------------------------- public static bool RunAutomationElementTests(AutomationElement element, bool testEvents, TestPriorities priority, TestCaseType testCaseType, bool testChildren, bool normalize, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object test = new AutomationElementTests(element, priority, null, testEvents, TypeOfControl.UnknownControl, commands); passed &= ((TestObject)test).InvokeTests(AutomationElementTests.TestSuite, testCaseType); if (testChildren) { passed &= RunAutomationElementTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, priority, normalize, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Run the Automation test as defined by test /// </summary> /// ------------------------------------------------------------------- public static bool RunAutomationElementTest(AutomationElement element, bool testEvents, string test, bool testChildren, object arguments, bool normalize, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object testObject = new AutomationElementTests(element, TestPriorities.PriAll, null, testEvents, TypeOfControl.UnknownControl, commands); passed &= ((TestObject)testObject).InvokeTest(AutomationElementTests.TestSuite, test, arguments); if (testChildren) { passed &= RunAutomationElementTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, test, testChildren, arguments, normalize, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Recursively tests the children Logical Elements /// </summary> /// ------------------------------------------------------------------- static bool RunAutomationElementTestOnDescendants(AutomationElement element, bool testEvents, string test, bool testChildren, object arguments, bool normalize, IApplicationCommands commands) { bool passed = true; if (element != null) { try { AutomationElement tempLe; ArrayList list; Hashtable ht = GetHashedElements(element); IDictionaryEnumerator enumerator = ht.GetEnumerator(); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); // Add the nodes to the tree. Some of the nodes we may want to remove // because of redundancy for specific nodes as defined in the m_Duplicate // ArrayList. while (enumerator.MoveNext()) { // Get the list of elements list = (ArrayList)ht[enumerator.Key]; if (normalize && Array.IndexOf(m_Duplicate, enumerator.Key) != -1) {// We want to normalize the list, only to uniuque elements tempLe = (AutomationElement)list[rnd.Next(list.Count)]; passed &= RunAutomationElementTest(tempLe, testEvents, test, false, arguments, normalize, commands); if (testChildren) { passed &= RunAutomationElementTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(tempLe), testEvents, test, testChildren, arguments, normalize, commands); } } else {// We don't want to normalize, just do everything foreach (AutomationElement el in list) { passed &= RunAutomationElementTest(el, testEvents, test, false, arguments, normalize, commands); if (testChildren) { passed &= RunAutomationElementTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(el), testEvents, test, testChildren, arguments, normalize, commands); } } } } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } #endregion Misc #endregion Entry for running tests #region Misc /// ------------------------------------------------------------------- /// <summary> /// Generates a hash table. The key is the localized control type. The /// element is an ArrayList of the actual elements that correspond to /// the control type. /// </summary> /// ------------------------------------------------------------------- static Hashtable GetHashedElements(AutomationElement element) { Hashtable ht = new Hashtable(); // Hash the elements into unique buckets so we can pick random elements in each bucket if // we so desire later in code that follows this. for (AutomationElement tempElement = element; tempElement != null; tempElement = TreeWalker.ControlViewWalker.GetNextSibling(tempElement)) { string controlType; if (tempElement.Current.ControlType != null) { controlType = tempElement.Current.ControlType.ProgrammaticName; // Add the entry if it does not exist. if (!ht.ContainsKey(controlType)) { ht.Add(controlType, new ArrayList()); } // Add the element to the key's ArrayList. ((ArrayList)ht[controlType]).Add(tempElement); } } return ht; } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- static bool RunPatternTestOnDescendants(AutomationElement element, bool testEvents, bool testChildren, string testSuite, string test, object arguments, IApplicationCommands commands) { bool passed = true; if (element != null) { try { try { //AutomationIdentifier IsPatternAvaliable = Helpers.GetPropertyByName(Automa // Try to instantiate a test object with this pattern. If the pattern is no supported, then object testObject = TestObject.GetPatternTestObject(testSuite, element, testEvents, TestPriorities.PriAll, commands); passed &= ((TestObject)testObject).InvokeTest(testSuite, test, arguments); } catch (Exception) { // Trying to get a pattern that is not supported. Eat this so that we can continue to do the children } if (testChildren) { passed &= RunPatternTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, testSuite, test, arguments, commands); passed &= RunPatternTestOnDescendants(TreeWalker.ControlViewWalker.GetNextSibling(element), testEvents, testChildren, testSuite, test, arguments, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- static bool RunPatternTestsOnDescendants(AutomationElement element, bool testEvents, bool testChildren, string testSuite, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { object testObject = TestObject.GetPatternTestObject(testSuite, element, testEvents, TestPriorities.PriAll, commands); // Test this object passed &= ((TestObject)testObject).InvokeTests(testSuite, testCaseType); if (testChildren) { passed &= RunPatternTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(element), testEvents, testChildren, testSuite, testCaseType, commands); passed &= RunPatternTestsOnDescendants(TreeWalker.ControlViewWalker.GetNextSibling(element), testEvents, testChildren, testSuite, testCaseType, commands); } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- static bool RunAllPatternTestsOnDescendants(AutomationElement element, bool testEvents, bool testChildren, TestPriorities priority, bool normalize, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { AutomationElement tempLe; ArrayList list; Hashtable ht = GetHashedElements(element); IDictionaryEnumerator enumerator = ht.GetEnumerator(); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); // Add the nodes to the tree. Some of the nodes we may want to remove // because of redundancy for specific nodes as defined in the m_Duplicate // ArrayList. while (enumerator.MoveNext()) { list = (ArrayList)ht[enumerator.Key]; if (normalize && Array.IndexOf(m_Duplicate, enumerator.Key) != -1) { // Remove defined items that we don't want duplicates of tempLe = (AutomationElement)list[rnd.Next(list.Count)]; ArrayList al = Helpers.GetPatternSuitesForAutomationElement(tempLe); foreach (string testSuite in al) { passed &= RunAllPatternTests(tempLe, testEvents, priority, testCaseType, false, normalize, commands); } if (testChildren) { passed &= RunAllPatternTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(tempLe), testEvents, testChildren, priority, normalize, testCaseType, commands); } } else { // Add everything else whether duplicate or not foreach (AutomationElement el in list) { passed &= RunAllPatternTests(el, testEvents, priority, testCaseType, false, normalize, commands); if (testChildren) { passed &= RunAllPatternTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(el), testEvents, testChildren, priority, normalize, testCaseType, commands); } } } } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary></summary> /// ------------------------------------------------------------------- static bool RunAllControlTestOnDescendants(AutomationElement element, bool testEvents, bool testChildren, TestPriorities priority, bool normalize, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { AutomationElement tempLe; ArrayList list; Hashtable ht = GetHashedElements(element); IDictionaryEnumerator enumerator = ht.GetEnumerator(); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); // Add the nodes to the tree. Some of the nodes we may want to remove // because of redundancy for specific nodes as defined in the m_Duplicate // ArrayList. while (enumerator.MoveNext()) { list = (ArrayList)ht[enumerator.Key]; if (normalize && Array.IndexOf(m_Duplicate, enumerator.Key) != -1) { // Remove defined items that we don't want duplicates of tempLe = (AutomationElement)list[rnd.Next(list.Count)]; passed &= RunAllControlTests(tempLe, testEvents, priority, testCaseType, false, normalize, commands); if (testChildren) { passed &= RunAllControlTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(tempLe), testEvents, testChildren, priority, normalize, testCaseType, commands); } } else { // Add everything else whether duplicate or not foreach (AutomationElement el in list) { passed &= RunAllControlTests(el, testEvents, priority, testCaseType, false, normalize, commands); if (testChildren) { passed &= RunAllControlTestOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(el), testEvents, testChildren, priority, normalize, testCaseType, commands); } } } } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } /// ------------------------------------------------------------------- /// <summary> /// Recursively tests the children Logical Elements /// </summary> /// ------------------------------------------------------------------- static bool RunAutomationElementTestsOnDescendants(AutomationElement element, bool testEvents, bool testChildren, TestPriorities priority, bool normalize, TestCaseType testCaseType, IApplicationCommands commands) { bool passed = true; if (element != null) { try { AutomationElement tempLe; ArrayList list; Hashtable ht = GetHashedElements(element); IDictionaryEnumerator enumerator = ht.GetEnumerator(); Random rnd = new Random(unchecked((int)DateTime.Now.Ticks)); // Add the nodes to the tree. Some of the nodes we may want to remove // because of redundancy for specific nodes as defined in the m_Duplicate // ArrayList. while (enumerator.MoveNext()) { list = (ArrayList)ht[enumerator.Key]; if (normalize && Array.IndexOf(m_Duplicate, enumerator.Key) != -1) { // Remove defined items that we don't want duplicates of tempLe = (AutomationElement)list[rnd.Next(list.Count)]; passed &= RunAutomationElementTests(tempLe, testEvents, priority, testCaseType, false, normalize, commands); if (testChildren) { passed &= RunAutomationElementTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(tempLe), testEvents, testChildren, priority, normalize, testCaseType, commands); } } else { // Add everything else whether duplicate or not foreach (AutomationElement el in list) { passed &= RunAutomationElementTests(el, testEvents, priority, testCaseType, false, normalize, commands); if (testChildren) { passed &= RunAutomationElementTestsOnDescendants(TreeWalker.ControlViewWalker.GetFirstChild(el), testEvents, testChildren, priority, normalize, testCaseType, commands); } } } } } catch (Exception exception) { UIVerifyLogger.LogUnexpectedError(exception); } } return passed; } #endregion Misc public static void StopRunningTests() { TestObject.CancelRun = true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class NetworkStreamTest { [Fact] public void Ctor_NullSocket_ThrowsArgumentNullExceptions() { Assert.Throws<ArgumentNullException>("socket", () => new NetworkStream(null)); Assert.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, false)); Assert.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, true)); Assert.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, FileAccess.ReadWrite)); Assert.Throws<ArgumentNullException>("socket", () => new NetworkStream(null, FileAccess.ReadWrite, false)); } [Fact] public void Ctor_NotConnected_ThrowsIOException() { Assert.Throws<IOException>(() => new NetworkStream(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))); } [Fact] public async Task Ctor_NotStream_ThrowsIOException() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); await client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port)); Assert.Throws<IOException>(() => new NetworkStream(client)); } } [Fact] public async Task Ctor_NonBlockingSocket_ThrowsIOException() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { server.Blocking = false; Assert.Throws<IOException>(() => new NetworkStream(server)); } } } [Fact] public async Task Ctor_Socket_CanReadAndWrite_DoesntOwn() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets { using (var serverStream = new NetworkStream(server)) using (var clientStream = new NetworkStream(client)) { Assert.True(serverStream.CanWrite && serverStream.CanRead); Assert.True(clientStream.CanWrite && clientStream.CanRead); Assert.False(serverStream.CanSeek && clientStream.CanSeek); Assert.True(serverStream.CanTimeout && clientStream.CanTimeout); // Verify Read and Write on both streams byte[] buffer = new byte[1]; await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1); Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1)); Assert.Equal('b', (char)buffer[0]); } } } } } [Theory] [InlineData(FileAccess.ReadWrite)] [InlineData((FileAccess)42)] // unknown values treated as ReadWrite public async Task Ctor_SocketFileAccessBool_CanReadAndWrite_DoesntOwn(FileAccess access) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets { using (var serverStream = new NetworkStream(server, access, false)) using (var clientStream = new NetworkStream(client, access, false)) { Assert.True(serverStream.CanWrite && serverStream.CanRead); Assert.True(clientStream.CanWrite && clientStream.CanRead); Assert.False(serverStream.CanSeek && clientStream.CanSeek); Assert.True(serverStream.CanTimeout && clientStream.CanTimeout); // Verify Read and Write on both streams byte[] buffer = new byte[1]; await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1); Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1)); Assert.Equal('b', (char)buffer[0]); } } } } } [Theory] [InlineData(false)] [InlineData(true)] public async Task Ctor_SocketBool_CanReadAndWrite(bool ownsSocket) { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets { Exception e = await Record.ExceptionAsync(async () => { using (var serverStream = new NetworkStream(server, ownsSocket)) using (var clientStream = new NetworkStream(client, ownsSocket)) { Assert.True(serverStream.CanWrite && serverStream.CanRead); Assert.True(clientStream.CanWrite && clientStream.CanRead); Assert.False(serverStream.CanSeek && clientStream.CanSeek); Assert.True(serverStream.CanTimeout && clientStream.CanTimeout); // Verify Read and Write on both streams byte[] buffer = new byte[1]; await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); await clientStream.WriteAsync(new byte[] { (byte)'b' }, 0, 1); Assert.Equal(1, await serverStream.ReadAsync(buffer, 0, 1)); Assert.Equal('b', (char)buffer[0]); } }); if (i == 0) { Assert.Null(e); } else if (ownsSocket) { Assert.IsType<IOException>(e); } else { Assert.Null(e); } } } } } [Fact] public async Task Ctor_SocketFileAccess_CanReadAndWrite() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) { for (int i = 0; i < 2; i++) // Verify closing the streams doesn't close the sockets { using (var serverStream = new NetworkStream(server, FileAccess.Write)) using (var clientStream = new NetworkStream(client, FileAccess.Read)) { Assert.True(serverStream.CanWrite && !serverStream.CanRead); Assert.True(!clientStream.CanWrite && clientStream.CanRead); Assert.False(serverStream.CanSeek && clientStream.CanSeek); Assert.True(serverStream.CanTimeout && clientStream.CanTimeout); // Verify Read and Write on both streams byte[] buffer = new byte[1]; await serverStream.WriteAsync(new byte[] { (byte)'a' }, 0, 1); Assert.Equal(1, await clientStream.ReadAsync(buffer, 0, 1)); Assert.Equal('a', (char)buffer[0]); Assert.Throws<InvalidOperationException>(() => { serverStream.BeginRead(buffer, 0, 1, null, null); }); Assert.Throws<InvalidOperationException>(() => { clientStream.BeginWrite(buffer, 0, 1, null, null); }); Assert.Throws<InvalidOperationException>(() => { serverStream.ReadAsync(buffer, 0, 1); }); Assert.Throws<InvalidOperationException>(() => { clientStream.WriteAsync(buffer, 0, 1); }); } } } } } [Fact] public async Task SocketProperty_SameAsProvidedSocket() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) using (DerivedNetworkStream serverStream = new DerivedNetworkStream(server)) { Assert.Same(server, serverStream.Socket); } } } [OuterLoop("Spins waiting for DataAvailable")] [Fact] public async Task DataAvailable_ReturnsFalseOrTrueAppropriately() { await RunWithConnectedNetworkStreamsAsync(async (server, client) => { Assert.False(server.DataAvailable && client.DataAvailable); await server.WriteAsync(new byte[1], 0, 1); Assert.False(server.DataAvailable); Assert.True(SpinWait.SpinUntil(() => client.DataAvailable, 10000), "DataAvailable did not return true in the allotted time"); }); } [Theory] [InlineData(false)] [InlineData(true)] public async Task DisposedClosed_MembersThrowObjectDisposedException(bool close) { await RunWithConnectedNetworkStreamsAsync((server, _) => { if (close) server.Close(); else server.Dispose(); Assert.Throws<ObjectDisposedException>(() => server.DataAvailable); Assert.Throws<ObjectDisposedException>(() => server.Read(new byte[1], 0, 1)); Assert.Throws<ObjectDisposedException>(() => server.Write(new byte[1], 0, 1)); Assert.Throws<ObjectDisposedException>(() => server.BeginRead(new byte[1], 0, 1, null, null)); Assert.Throws<ObjectDisposedException>(() => server.BeginWrite(new byte[1], 0, 1, null, null)); Assert.Throws<ObjectDisposedException>(() => server.EndRead(null)); Assert.Throws<ObjectDisposedException>(() => server.EndWrite(null)); Assert.Throws<ObjectDisposedException>(() => { server.ReadAsync(new byte[1], 0, 1); }); Assert.Throws<ObjectDisposedException>(() => { server.WriteAsync(new byte[1], 0, 1); }); Assert.Throws<ObjectDisposedException>(() => { server.CopyToAsync(new MemoryStream()); }); return Task.CompletedTask; }); } [Fact] public async Task DisposeSocketDirectly_ReadWriteThrowIOException() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket serverSocket = await acceptTask) using (DerivedNetworkStream server = new DerivedNetworkStream(serverSocket)) { serverSocket.Dispose(); Assert.Throws<IOException>(() => server.Read(new byte[1], 0, 1)); Assert.Throws<IOException>(() => server.Write(new byte[1], 0, 1)); Assert.Throws<IOException>(() => server.BeginRead(new byte[1], 0, 1, null, null)); Assert.Throws<IOException>(() => server.BeginWrite(new byte[1], 0, 1, null, null)); Assert.Throws<IOException>(() => { server.ReadAsync(new byte[1], 0, 1); }); Assert.Throws<IOException>(() => { server.WriteAsync(new byte[1], 0, 1); }); } } } [Fact] public async Task InvalidIAsyncResult_EndReadWriteThrows() { await RunWithConnectedNetworkStreamsAsync((server, _) => { Assert.Throws<IOException>(() => server.EndRead(Task.CompletedTask)); Assert.Throws<IOException>(() => server.EndWrite(Task.CompletedTask)); return Task.CompletedTask; }); } [Fact] public async Task Close_InvalidArgument_Throws() { await RunWithConnectedNetworkStreamsAsync((server, _) => { Assert.Throws<ArgumentOutOfRangeException>(() => server.Close(-2)); server.Close(-1); server.Close(0); return Task.CompletedTask; }); } [Fact] public async Task ReadWrite_InvalidArguments_Throws() { await RunWithConnectedNetworkStreamsAsync((server, _) => { Assert.Throws<ArgumentNullException>(() => server.Read(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], 2, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Read(new byte[1], 0, 2)); Assert.Throws<ArgumentNullException>(() => server.BeginRead(null, 0, 0, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], -1, 0, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], 2, 0, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], 0, -1, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginRead(new byte[1], 0, 2, null, null)); Assert.Throws<ArgumentNullException>(() => { server.ReadAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], 2, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], 0, -1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.ReadAsync(new byte[1], 0, 2); }); Assert.Throws<ArgumentNullException>(() => server.Write(null, 0, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], 2, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => server.Write(new byte[1], 0, 2)); Assert.Throws<ArgumentNullException>(() => server.BeginWrite(null, 0, 0, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], -1, 0, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], 2, 0, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], 0, -1, null, null)); Assert.Throws<ArgumentOutOfRangeException>(() => server.BeginWrite(new byte[1], 0, 2, null, null)); Assert.Throws<ArgumentNullException>(() => { server.WriteAsync(null, 0, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], -1, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], 2, 0); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], 0, -1); }); Assert.Throws<ArgumentOutOfRangeException>(() => { server.WriteAsync(new byte[1], 0, 2); }); Assert.Throws<ArgumentNullException>(() => server.EndRead(null)); Assert.Throws<ArgumentNullException>(() => server.EndWrite(null)); return Task.CompletedTask; }); } [Fact] public async Task NotSeekable_OperationsThrowExceptions() { await RunWithConnectedNetworkStreamsAsync((server, client) => { Assert.False(server.CanSeek && client.CanSeek); Assert.Throws<NotSupportedException>(() => server.Seek(0, SeekOrigin.Begin)); Assert.Throws<NotSupportedException>(() => server.Length); Assert.Throws<NotSupportedException>(() => server.SetLength(1024)); Assert.Throws<NotSupportedException>(() => server.Position); Assert.Throws<NotSupportedException>(() => server.Position = 0); return Task.CompletedTask; }); } [Fact] public async Task ReadableWriteableProperties_Roundtrip() { using (Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { listener.Bind(new IPEndPoint(IPAddress.Loopback, 0)); listener.Listen(1); Task<Socket> acceptTask = listener.AcceptAsync(); await Task.WhenAll(acceptTask, client.ConnectAsync(new IPEndPoint(IPAddress.Loopback, ((IPEndPoint)listener.LocalEndPoint).Port))); using (Socket server = await acceptTask) using (DerivedNetworkStream serverStream = new DerivedNetworkStream(server)) { Assert.True(serverStream.Readable && serverStream.Writeable); serverStream.Readable = false; Assert.False(serverStream.Readable); Assert.False(serverStream.CanRead); Assert.Throws<InvalidOperationException>(() => serverStream.Read(new byte[1], 0, 1)); serverStream.Readable = true; Assert.True(serverStream.Readable); Assert.True(serverStream.CanRead); await client.SendAsync(new ArraySegment<byte>(new byte[1], 0, 1), SocketFlags.None); Assert.Equal(1, await serverStream.ReadAsync(new byte[1], 0, 1)); serverStream.Writeable = false; Assert.False(serverStream.Writeable); Assert.False(serverStream.CanWrite); Assert.Throws<InvalidOperationException>(() => serverStream.Write(new byte[1], 0, 1)); serverStream.Writeable = true; Assert.True(serverStream.Writeable); Assert.True(serverStream.CanWrite); await serverStream.WriteAsync(new byte[1], 0, 1); Assert.Equal(1, await client.ReceiveAsync(new ArraySegment<byte>(new byte[1], 0, 1), SocketFlags.None)); } } } [Fact] public async Task ReadWrite_Success() { await RunWithConnectedNetworkStreamsAsync((server, client) => { var clientData = new byte[] { 42 }; client.Write(clientData, 0, clientData.Length); var serverData = new byte[clientData.Length]; Assert.Equal(serverData.Length, server.Read(serverData, 0, serverData.Length)); Assert.Equal(clientData, serverData); client.Flush(); // nop return Task.CompletedTask; }); } [OuterLoop] // TODO: Issue #11345 [Theory] [MemberData(nameof(NonCanceledTokens))] public async Task ReadWriteAsync_NonCanceled_Success(CancellationToken nonCanceledToken) { await RunWithConnectedNetworkStreamsAsync(async (server, client) => { var clientData = new byte[] { 42 }; await client.WriteAsync(clientData, 0, clientData.Length, nonCanceledToken); var serverData = new byte[clientData.Length]; Assert.Equal(serverData.Length, await server.ReadAsync(serverData, 0, serverData.Length, nonCanceledToken)); Assert.Equal(clientData, serverData); Assert.Equal(TaskStatus.RanToCompletion, client.FlushAsync().Status); // nop }); } [Fact] public async Task BeginEndReadWrite_Sync_Success() { await RunWithConnectedNetworkStreamsAsync((server, client) => { var clientData = new byte[] { 42 }; client.EndWrite(client.BeginWrite(clientData, 0, clientData.Length, null, null)); var serverData = new byte[clientData.Length]; Assert.Equal(serverData.Length, server.EndRead(server.BeginRead(serverData, 0, serverData.Length, null, null))); Assert.Equal(clientData, serverData); return Task.CompletedTask; }); } [Fact] public async Task BeginEndReadWrite_Async_Success() { await RunWithConnectedNetworkStreamsAsync(async (server, client) => { var clientData = new byte[] { 42 }; var serverData = new byte[clientData.Length]; var tcs = new TaskCompletionSource<bool>(); client.BeginWrite(clientData, 0, clientData.Length, writeIar => { try { client.EndWrite(writeIar); server.BeginRead(serverData, 0, serverData.Length, readIar => { try { Assert.Equal(serverData.Length, server.EndRead(readIar)); tcs.SetResult(true); } catch (Exception e2) { tcs.SetException(e2); } }, null); } catch (Exception e1) { tcs.SetException(e1); } }, null); await tcs.Task; Assert.Equal(clientData, serverData); }); } [OuterLoop] // TODO: Issue #11345 [Fact] public async Task ReadWriteAsync_Canceled_ThrowsOperationCanceledException() { await RunWithConnectedNetworkStreamsAsync(async (server, client) => { var canceledToken = new CancellationToken(canceled: true); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => client.WriteAsync(new byte[1], 0, 1, canceledToken)); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => server.ReadAsync(new byte[1], 0, 1, canceledToken)); }); } public static object[][] NonCanceledTokens = new object[][] { new object[] { CancellationToken.None }, // CanBeCanceled == false new object[] { new CancellationTokenSource().Token } // CanBeCanceled == true }; [OuterLoop("Timeouts")] [Fact] public async Task ReadTimeout_Expires_ThrowsSocketException() { await RunWithConnectedNetworkStreamsAsync((server, client) => { Assert.Equal(-1, server.ReadTimeout); server.ReadTimeout = 1; Assert.ThrowsAny<IOException>(() => server.Read(new byte[1], 0, 1)); return Task.CompletedTask; }); } [Theory] [InlineData(0)] [InlineData(-2)] public async Task Timeout_InvalidData_ThrowsArgumentException(int invalidTimeout) { await RunWithConnectedNetworkStreamsAsync((server, client) => { Assert.Throws<ArgumentOutOfRangeException>("value", () => server.ReadTimeout = invalidTimeout); Assert.Throws<ArgumentOutOfRangeException>("value", () => server.WriteTimeout = invalidTimeout); return Task.CompletedTask; }); } [Fact] public async Task Timeout_ValidData_Roundtrips() { await RunWithConnectedNetworkStreamsAsync((server, client) => { Assert.Equal(-1, server.ReadTimeout); Assert.Equal(-1, server.WriteTimeout); server.ReadTimeout = 100; Assert.InRange(server.ReadTimeout, 100, int.MaxValue); server.ReadTimeout = 100; // same value again Assert.InRange(server.ReadTimeout, 100, int.MaxValue); server.ReadTimeout = -1; Assert.Equal(-1, server.ReadTimeout); server.WriteTimeout = 100; Assert.InRange(server.WriteTimeout, 100, int.MaxValue); server.WriteTimeout = 100; // same value again Assert.InRange(server.WriteTimeout, 100, int.MaxValue); server.WriteTimeout = -1; Assert.Equal(-1, server.WriteTimeout); return Task.CompletedTask; }); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(1024)] [InlineData(4096)] [InlineData(4095)] [InlineData(1024*1024)] public async Task CopyToAsync_AllDataCopied(int byteCount) { await RunWithConnectedNetworkStreamsAsync(async (server, client) => { var results = new MemoryStream(); byte[] dataToCopy = new byte[byteCount]; new Random().NextBytes(dataToCopy); Task copyTask = client.CopyToAsync(results); await server.WriteAsync(dataToCopy, 0, dataToCopy.Length); server.Dispose(); await copyTask; Assert.Equal(dataToCopy, results.ToArray()); }); } [Fact] public async Task CopyToAsync_InvalidArguments_Throws() { await RunWithConnectedNetworkStreamsAsync((stream, _) => { // Null destination Assert.Throws<ArgumentNullException>("destination", () => { stream.CopyToAsync(null); }); // Buffer size out-of-range Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { stream.CopyToAsync(new MemoryStream(), 0); }); Assert.Throws<ArgumentOutOfRangeException>("bufferSize", () => { stream.CopyToAsync(new MemoryStream(), -1, CancellationToken.None); }); // Copying to non-writable stream Assert.Throws<NotSupportedException>(() => { stream.CopyToAsync(new MemoryStream(new byte[0], writable: false)); }); // Copying to a disposed stream Assert.Throws<ObjectDisposedException>(() => { var disposedTarget = new MemoryStream(); disposedTarget.Dispose(); stream.CopyToAsync(disposedTarget); }); // Already canceled Assert.Equal(TaskStatus.Canceled, stream.CopyToAsync(new MemoryStream(new byte[1]), 1, new CancellationToken(canceled: true)).Status); return Task.CompletedTask; }); } [ActiveIssue(16611, TestPlatforms.AnyUnix)] [Fact] public async Task CopyToAsync_DisposedSourceStream_Throws() { await RunWithConnectedNetworkStreamsAsync(async (stream, _) => { // Copying while and then after disposing the stream Task copyTask = stream.CopyToAsync(new MemoryStream()); stream.Dispose(); await Assert.ThrowsAsync<IOException>(() => copyTask); Assert.Throws<ObjectDisposedException>(() => { stream.CopyToAsync(new MemoryStream()); }); }); } [Fact] public async Task CopyToAsync_NonReadableSourceStream_Throws() { await RunWithConnectedNetworkStreamsAsync((stream, _) => { // Copying from non-readable stream Assert.Throws<NotSupportedException>(() => { stream.CopyToAsync(new MemoryStream()); }); return Task.CompletedTask; }, serverAccess:FileAccess.Write); } /// <summary> /// Creates a pair of connected NetworkStreams and invokes the provided <paramref name="func"/> /// with them as arguments. /// </summary> private static async Task RunWithConnectedNetworkStreamsAsync(Func<NetworkStream, NetworkStream, Task> func, FileAccess serverAccess = FileAccess.ReadWrite, FileAccess clientAccess = FileAccess.ReadWrite) { var listener = new TcpListener(IPAddress.Loopback, 0); try { listener.Start(1); var clientEndpoint = (IPEndPoint)listener.LocalEndpoint; using (var client = new TcpClient(clientEndpoint.AddressFamily)) { Task<TcpClient> remoteTask = listener.AcceptTcpClientAsync(); Task clientConnectTask = client.ConnectAsync(clientEndpoint.Address, clientEndpoint.Port); await Task.WhenAll(remoteTask, clientConnectTask); using (TcpClient remote = remoteTask.Result) using (NetworkStream serverStream = new NetworkStream(remote.Client, serverAccess, ownsSocket:true)) using (NetworkStream clientStream = new NetworkStream(client.Client, clientAccess, ownsSocket: true)) { await func(serverStream, clientStream); } } } finally { listener.Stop(); } } private sealed class DerivedNetworkStream : NetworkStream { public DerivedNetworkStream(Socket socket) : base(socket) { } public new Socket Socket => base.Socket; public new bool Readable { get { return base.Readable; } set { base.Readable = value; } } public new bool Writeable { get { return base.Writeable; } set { base.Writeable = value; } } } } }
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using System; using System.Collections.Generic; using System.Diagnostics; using System.Security.Claims; using System.Security.Principal; namespace IdentityServer4.Extensions { /// <summary> /// Extension methods for <see cref="System.Security.Principal.IPrincipal"/> and <see cref="System.Security.Principal.IIdentity"/> . /// </summary> public static class PrincipalExtensions { /// <summary> /// Gets the authentication time. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static DateTime GetAuthenticationTime(this IPrincipal principal) { return ((int)principal.GetAuthenticationTimeEpoch()).ToDateTimeFromEpoch(); } /// <summary> /// Gets the authentication epoch time. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static long GetAuthenticationTimeEpoch(this IPrincipal principal) { return principal.Identity.GetAuthenticationTimeEpoch(); } /// <summary> /// Gets the authentication epoch time. /// </summary> /// <param name="identity">The identity.</param> /// <returns></returns> [DebuggerStepThrough] public static long GetAuthenticationTimeEpoch(this IIdentity identity) { var id = identity as ClaimsIdentity; var claim = id.FindFirst(JwtClaimTypes.AuthenticationTime); if (claim == null) throw new InvalidOperationException("auth_time is missing."); return long.Parse(claim.Value); } /// <summary> /// Gets the subject identifier. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static string GetSubjectId(this IPrincipal principal) { return principal.Identity.GetSubjectId(); } /// <summary> /// Gets the subject identifier. /// </summary> /// <param name="identity">The identity.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">sub claim is missing</exception> [DebuggerStepThrough] public static string GetSubjectId(this IIdentity identity) { var id = identity as ClaimsIdentity; var claim = id.FindFirst(JwtClaimTypes.Subject); if (claim == null) throw new InvalidOperationException("sub claim is missing"); return claim.Value; } /// <summary> /// Gets the name. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] [Obsolete("This method will be removed in a future version. Use GetDisplayName instead.")] public static string GetName(this IPrincipal principal) { return principal.Identity.GetName(); } /// <summary> /// Gets the name. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static string GetDisplayName(this ClaimsPrincipal principal) { var name = principal.Identity.Name; if (name.IsPresent()) return name; var sub = principal.FindFirst(JwtClaimTypes.Subject); if (sub != null) return sub.Value; return ""; } /// <summary> /// Gets the name. /// </summary> /// <param name="identity">The identity.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">name claim is missing</exception> [DebuggerStepThrough] [Obsolete("This method will be removed in a future version. Use GetDisplayName instead.")] public static string GetName(this IIdentity identity) { var id = identity as ClaimsIdentity; var claim = id.FindFirst(JwtClaimTypes.Name); if (claim == null) throw new InvalidOperationException("name claim is missing"); return claim.Value; } /// <summary> /// Gets the authentication method. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static string GetAuthenticationMethod(this IPrincipal principal) { return principal.Identity.GetAuthenticationMethod(); } /// <summary> /// Gets the authentication method claims. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static IEnumerable<Claim> GetAuthenticationMethods(this IPrincipal principal) { return principal.Identity.GetAuthenticationMethods(); } /// <summary> /// Gets the authentication method. /// </summary> /// <param name="identity">The identity.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">amr claim is missing</exception> [DebuggerStepThrough] public static string GetAuthenticationMethod(this IIdentity identity) { var id = identity as ClaimsIdentity; var claim = id.FindFirst(JwtClaimTypes.AuthenticationMethod); if (claim == null) throw new InvalidOperationException("amr claim is missing"); return claim.Value; } /// <summary> /// Gets the authentication method claims. /// </summary> /// <param name="identity">The identity.</param> /// <returns></returns> [DebuggerStepThrough] public static IEnumerable<Claim> GetAuthenticationMethods(this IIdentity identity) { var id = identity as ClaimsIdentity; return id.FindAll(JwtClaimTypes.AuthenticationMethod); } /// <summary> /// Gets the identity provider. /// </summary> /// <param name="principal">The principal.</param> /// <returns></returns> [DebuggerStepThrough] public static string GetIdentityProvider(this IPrincipal principal) { return principal.Identity.GetIdentityProvider(); } /// <summary> /// Gets the identity provider. /// </summary> /// <param name="identity">The identity.</param> /// <returns></returns> /// <exception cref="System.InvalidOperationException">idp claim is missing</exception> [DebuggerStepThrough] public static string GetIdentityProvider(this IIdentity identity) { var id = identity as ClaimsIdentity; var claim = id.FindFirst(JwtClaimTypes.IdentityProvider); if (claim == null) throw new InvalidOperationException("idp claim is missing"); return claim.Value; } /// <summary> /// Determines whether this instance is authenticated. /// </summary> /// <param name="principal">The principal.</param> /// <returns> /// <c>true</c> if the specified principal is authenticated; otherwise, <c>false</c>. /// </returns> [DebuggerStepThrough] public static bool IsAuthenticated(this IPrincipal principal) { return principal != null && principal.Identity != null && principal.Identity.IsAuthenticated; } } }
using System; using System.Text; using System.Collections; using System.Collections.Generic; namespace Com.Aspose.Cells.Model { public class PivotTable { public string AltTextDescription { get; set; } public string AltTextTitle { get; set; } public string AutoFormatType { get; set; } public List<PivotField> BaseFields { get; set; } public List<PivotField> ColumnFields { get; set; } public bool? ColumnGrand { get; set; } public string ColumnHeaderCaption { get; set; } public CellArea ColumnRange { get; set; } public bool? CustomListSort { get; set; } public CellArea DataBodyRange { get; set; } public PivotField DataField { get; set; } public List<PivotField> DataFields { get; set; } public List<string> DataSource { get; set; } public bool? DisplayErrorString { get; set; } public bool? DisplayImmediateItems { get; set; } public bool? DisplayNullString { get; set; } public bool? EnableDataValueEditing { get; set; } public bool? EnableDrilldown { get; set; } public bool? EnableFieldDialog { get; set; } public bool? EnableFieldList { get; set; } public bool? EnableWizard { get; set; } public string ErrorString { get; set; } public bool? FieldListSortAscending { get; set; } public string GrandTotalName { get; set; } public bool? HasBlankRows { get; set; } public int? Indent { get; set; } public bool? IsAutoFormat { get; set; } public bool? IsGridDropZones { get; set; } public bool? IsMultipleFieldFilters { get; set; } public bool? IsSelected { get; set; } public bool? ItemPrintTitles { get; set; } public bool? ManualUpdate { get; set; } public bool? MergeLabels { get; set; } public string MissingItemsLimit { get; set; } public string Name { get; set; } public string NullString { get; set; } public string PageFieldOrder { get; set; } public List<PivotField> PageFields { get; set; } public int? PageFieldWrapCount { get; set; } public List<PivotFilter> PivotFilters { get; set; } public string PivotTableStyleName { get; set; } public string PivotTableStyleType { get; set; } public bool? PreserveFormatting { get; set; } public bool? PrintDrill { get; set; } public bool? PrintTitles { get; set; } public bool? RefreshDataFlag { get; set; } public bool? RefreshDataOnOpeningFile { get; set; } public List<PivotField> RowFields { get; set; } public bool? RowGrand { get; set; } public string RowHeaderCaption { get; set; } public CellArea RowRange { get; set; } public bool? SaveData { get; set; } public bool? ShowDataTips { get; set; } public bool? ShowDrill { get; set; } public bool? ShowEmptyCol { get; set; } public bool? ShowEmptyRow { get; set; } public bool? ShowMemberPropertyTips { get; set; } public bool? ShowPivotStyleColumnHeader { get; set; } public bool? ShowPivotStyleColumnStripes { get; set; } public bool? ShowPivotStyleLastColumn { get; set; } public bool? ShowPivotStyleRowHeader { get; set; } public bool? ShowPivotStyleRowStripes { get; set; } public bool? ShowRowHeaderCaption { get; set; } public bool? ShowValuesRow { get; set; } public bool? SubtotalHiddenPageItems { get; set; } public CellArea TableRange1 { get; set; } public CellArea TableRange2 { get; set; } public string Tag { get; set; } public Link link { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.Append("class PivotTable {\n"); sb.Append(" AltTextDescription: ").Append(AltTextDescription).Append("\n"); sb.Append(" AltTextTitle: ").Append(AltTextTitle).Append("\n"); sb.Append(" AutoFormatType: ").Append(AutoFormatType).Append("\n"); sb.Append(" BaseFields: ").Append(BaseFields).Append("\n"); sb.Append(" ColumnFields: ").Append(ColumnFields).Append("\n"); sb.Append(" ColumnGrand: ").Append(ColumnGrand).Append("\n"); sb.Append(" ColumnHeaderCaption: ").Append(ColumnHeaderCaption).Append("\n"); sb.Append(" ColumnRange: ").Append(ColumnRange).Append("\n"); sb.Append(" CustomListSort: ").Append(CustomListSort).Append("\n"); sb.Append(" DataBodyRange: ").Append(DataBodyRange).Append("\n"); sb.Append(" DataField: ").Append(DataField).Append("\n"); sb.Append(" DataFields: ").Append(DataFields).Append("\n"); sb.Append(" DataSource: ").Append(DataSource).Append("\n"); sb.Append(" DisplayErrorString: ").Append(DisplayErrorString).Append("\n"); sb.Append(" DisplayImmediateItems: ").Append(DisplayImmediateItems).Append("\n"); sb.Append(" DisplayNullString: ").Append(DisplayNullString).Append("\n"); sb.Append(" EnableDataValueEditing: ").Append(EnableDataValueEditing).Append("\n"); sb.Append(" EnableDrilldown: ").Append(EnableDrilldown).Append("\n"); sb.Append(" EnableFieldDialog: ").Append(EnableFieldDialog).Append("\n"); sb.Append(" EnableFieldList: ").Append(EnableFieldList).Append("\n"); sb.Append(" EnableWizard: ").Append(EnableWizard).Append("\n"); sb.Append(" ErrorString: ").Append(ErrorString).Append("\n"); sb.Append(" FieldListSortAscending: ").Append(FieldListSortAscending).Append("\n"); sb.Append(" GrandTotalName: ").Append(GrandTotalName).Append("\n"); sb.Append(" HasBlankRows: ").Append(HasBlankRows).Append("\n"); sb.Append(" Indent: ").Append(Indent).Append("\n"); sb.Append(" IsAutoFormat: ").Append(IsAutoFormat).Append("\n"); sb.Append(" IsGridDropZones: ").Append(IsGridDropZones).Append("\n"); sb.Append(" IsMultipleFieldFilters: ").Append(IsMultipleFieldFilters).Append("\n"); sb.Append(" IsSelected: ").Append(IsSelected).Append("\n"); sb.Append(" ItemPrintTitles: ").Append(ItemPrintTitles).Append("\n"); sb.Append(" ManualUpdate: ").Append(ManualUpdate).Append("\n"); sb.Append(" MergeLabels: ").Append(MergeLabels).Append("\n"); sb.Append(" MissingItemsLimit: ").Append(MissingItemsLimit).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" NullString: ").Append(NullString).Append("\n"); sb.Append(" PageFieldOrder: ").Append(PageFieldOrder).Append("\n"); sb.Append(" PageFields: ").Append(PageFields).Append("\n"); sb.Append(" PageFieldWrapCount: ").Append(PageFieldWrapCount).Append("\n"); sb.Append(" PivotFilters: ").Append(PivotFilters).Append("\n"); sb.Append(" PivotTableStyleName: ").Append(PivotTableStyleName).Append("\n"); sb.Append(" PivotTableStyleType: ").Append(PivotTableStyleType).Append("\n"); sb.Append(" PreserveFormatting: ").Append(PreserveFormatting).Append("\n"); sb.Append(" PrintDrill: ").Append(PrintDrill).Append("\n"); sb.Append(" PrintTitles: ").Append(PrintTitles).Append("\n"); sb.Append(" RefreshDataFlag: ").Append(RefreshDataFlag).Append("\n"); sb.Append(" RefreshDataOnOpeningFile: ").Append(RefreshDataOnOpeningFile).Append("\n"); sb.Append(" RowFields: ").Append(RowFields).Append("\n"); sb.Append(" RowGrand: ").Append(RowGrand).Append("\n"); sb.Append(" RowHeaderCaption: ").Append(RowHeaderCaption).Append("\n"); sb.Append(" RowRange: ").Append(RowRange).Append("\n"); sb.Append(" SaveData: ").Append(SaveData).Append("\n"); sb.Append(" ShowDataTips: ").Append(ShowDataTips).Append("\n"); sb.Append(" ShowDrill: ").Append(ShowDrill).Append("\n"); sb.Append(" ShowEmptyCol: ").Append(ShowEmptyCol).Append("\n"); sb.Append(" ShowEmptyRow: ").Append(ShowEmptyRow).Append("\n"); sb.Append(" ShowMemberPropertyTips: ").Append(ShowMemberPropertyTips).Append("\n"); sb.Append(" ShowPivotStyleColumnHeader: ").Append(ShowPivotStyleColumnHeader).Append("\n"); sb.Append(" ShowPivotStyleColumnStripes: ").Append(ShowPivotStyleColumnStripes).Append("\n"); sb.Append(" ShowPivotStyleLastColumn: ").Append(ShowPivotStyleLastColumn).Append("\n"); sb.Append(" ShowPivotStyleRowHeader: ").Append(ShowPivotStyleRowHeader).Append("\n"); sb.Append(" ShowPivotStyleRowStripes: ").Append(ShowPivotStyleRowStripes).Append("\n"); sb.Append(" ShowRowHeaderCaption: ").Append(ShowRowHeaderCaption).Append("\n"); sb.Append(" ShowValuesRow: ").Append(ShowValuesRow).Append("\n"); sb.Append(" SubtotalHiddenPageItems: ").Append(SubtotalHiddenPageItems).Append("\n"); sb.Append(" TableRange1: ").Append(TableRange1).Append("\n"); sb.Append(" TableRange2: ").Append(TableRange2).Append("\n"); sb.Append(" Tag: ").Append(Tag).Append("\n"); sb.Append(" link: ").Append(link).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
#region License /*---------------------------------------------------------------------------------*\ Distributed under the terms of an MIT-style license: The MIT License Copyright (c) 2006-2009 Stephen M. McKamey 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 License using System; using System.IO; using System.ComponentModel; using System.Collections; using System.Collections.Generic; using System.Text; using System.Reflection; using System.Xml; namespace JsonFx.Json { /// <summary> /// Represents a proxy method for serialization of types which do not implement IJsonSerializable. /// </summary> /// <typeparam name="T">the type for this proxy</typeparam> /// <param name="writer">the JsonWriter to serialize to</param> /// <param name="value">the value to serialize</param> public delegate void WriteDelegate<T>(JsonWriter writer, T value); /// <summary> /// Writer for producing JSON data. /// </summary> public class JsonWriter : IDisposable { #region Constants public const string JsonMimeType = "application/json"; private const string AnonymousTypePrefix = "<>f__AnonymousType"; private const string ErrorMaxDepth = "The maxiumum depth of {0} was exceeded. Check for cycles in object graph."; #endregion Constants #region Fields private readonly TextWriter writer = null; private string typeHintName = null; private bool strictConformance = true; private bool prettyPrint = false; private bool skipNullValue = false; private bool useXmlSerializationAttributes = false; private int depth = 0; private int maxDepth = 25; private string tab = "\t"; private WriteDelegate<DateTime> dateTimeSerializer = null; #endregion Fields #region Init /// <summary> /// Ctor. /// </summary> /// <param name="output">TextWriter for writing</param> public JsonWriter(TextWriter output) { this.writer = output; } /// <summary> /// Ctor. /// </summary> /// <param name="output">Stream for writing</param> public JsonWriter(Stream output) { this.writer = new StreamWriter(output, Encoding.UTF8); } /// <summary> /// Ctor. /// </summary> /// <param name="output">File name for writing</param> public JsonWriter(string outputFileName) { Stream stream = new FileStream(outputFileName, FileMode.Create, FileAccess.Write, FileShare.Read); this.writer = new StreamWriter(stream, Encoding.UTF8); } /// <summary> /// Ctor. /// </summary> /// <param name="output">StringBuilder for appending</param> public JsonWriter(StringBuilder output) { this.writer = new StringWriter(output, System.Globalization.CultureInfo.InvariantCulture); } #endregion Init #region Properties /// <summary> /// Gets and sets the property name used for type hinting. /// </summary> public string TypeHintName { get { return this.typeHintName; } set { this.typeHintName = value; } } /// <summary> /// Gets and sets if JSON will be formatted for human reading. /// </summary> public bool PrettyPrint { get { return this.prettyPrint; } set { this.prettyPrint = value; } } /// <summary> /// Gets and sets the string to use for indentation /// </summary> public string Tab { get { return this.tab; } set { this.tab = value; } } /// <summary> /// Gets and sets the line terminator string /// </summary> public string NewLine { get { return this.writer.NewLine; } set { this.writer.NewLine = value; } } /// <summary> /// Gets and sets the maximum depth to be serialized. /// </summary> public int MaxDepth { get { return this.maxDepth; } set { if (value < 1) { throw new ArgumentOutOfRangeException("MaxDepth must be a positive integer as it controls the maximum nesting level of serialized objects."); } this.maxDepth = value; } } /// <summary> /// Gets and sets if should use XmlSerialization Attributes. /// </summary> /// <remarks> /// Respects XmlIgnoreAttribute, ... /// </remarks> public bool UseXmlSerializationAttributes { get { return this.useXmlSerializationAttributes; } set { this.useXmlSerializationAttributes = value; } } /// <summary> /// Gets and sets if should conform strictly to JSON spec. /// </summary> /// <remarks> /// Setting to true causes NaN, Infinity, -Infinity to serialize as null. /// </remarks> public bool StrictConformance { get { return this.strictConformance; } set { this.strictConformance = value; } } public bool SkipNullValue { get { return skipNullValue; } set { skipNullValue = value; } } /// <summary> /// Gets and sets a proxy formatter to use for DateTime serialization /// </summary> public WriteDelegate<DateTime> DateTimeSerializer { get { return this.dateTimeSerializer; } set { this.dateTimeSerializer = value; } } /// <summary> /// Gets the underlying TextWriter. /// </summary> public TextWriter TextWriter { get { return this.writer; } } #endregion Properties #region Static Methods /// <summary> /// A fast method for serializing an object to JSON /// </summary> /// <param name="value"></param> /// <returns></returns> public static string Serialize(object value) { StringBuilder output = new StringBuilder(); using (JsonWriter writer = new JsonWriter(output)) { writer.Write(value); } return output.ToString(); } #endregion Static Methods #region Public Methods public void Write(object value) { this.Write(value, false); } protected virtual void Write(object value, bool isProperty) { if (isProperty && this.prettyPrint) { this.writer.Write(' '); } if (value == null) { this.writer.Write(JsonReader.LiteralNull); return; } if (value is IJsonSerializable) { try { if (isProperty) { this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } this.WriteLine(); } ((IJsonSerializable)value).WriteJson(this); } finally { if (isProperty) { this.depth--; } } return; } // must test enumerations before value types if (value is Enum) { this.Write((Enum)value); return; } // Type.GetTypeCode() allows us to more efficiently switch type // plus cannot use 'is' for ValueTypes Type type = value.GetType(); switch (Type.GetTypeCode(type)) { case TypeCode.Boolean: { this.Write((Boolean)value); return; } case TypeCode.Byte: { this.Write((Byte)value); return; } case TypeCode.Char: { this.Write((Char)value); return; } case TypeCode.DateTime: { this.Write((DateTime)value); return; } case TypeCode.DBNull: case TypeCode.Empty: { this.writer.Write(JsonReader.LiteralNull); return; } case TypeCode.Decimal: { // From MSDN: // Conversions from Char, SByte, Int16, Int32, Int64, Byte, UInt16, UInt32, and UInt64 // to Decimal are widening conversions that never lose information or throw exceptions. // Conversions from Single or Double to Decimal throw an OverflowException // if the result of the conversion is not representable as a Decimal. this.Write((Decimal)value); return; } case TypeCode.Double: { this.Write((Double)value); return; } case TypeCode.Int16: { this.Write((Int16)value); return; } case TypeCode.Int32: { this.Write((Int32)value); return; } case TypeCode.Int64: { this.Write((Int64)value); return; } case TypeCode.SByte: { this.Write((SByte)value); return; } case TypeCode.Single: { this.Write((Single)value); return; } case TypeCode.String: { this.Write((String)value); return; } case TypeCode.UInt16: { this.Write((UInt16)value); return; } case TypeCode.UInt32: { this.Write((UInt32)value); return; } case TypeCode.UInt64: { this.Write((UInt64)value); return; } default: case TypeCode.Object: { // all others must be explicitly tested break; } } if (value is Guid) { this.Write((Guid)value); return; } if (value is Uri) { this.Write((Uri)value); return; } if (value is TimeSpan) { this.Write((TimeSpan)value); return; } if (value is Version) { this.Write((Version)value); return; } // IDictionary test must happen BEFORE IEnumerable test // since IDictionary implements IEnumerable if (value is IDictionary) { try { if (isProperty) { this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } this.WriteLine(); } this.WriteObject((IDictionary)value); } finally { if (isProperty) { this.depth--; } } return; } if (type.GetInterface(JsonReader.TypeGenericIDictionary) != null) { throw new JsonSerializationException(String.Format(JsonReader.ErrorGenericIDictionary, type)); } // IDictionary test must happen BEFORE IEnumerable test // since IDictionary implements IEnumerable if (value is IEnumerable) { if (value is XmlNode) { this.Write((System.Xml.XmlNode)value); return; } try { if (isProperty) { this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } this.WriteLine(); } this.WriteArray((IEnumerable)value); } finally { if (isProperty) { this.depth--; } } return; } // structs and classes try { if (isProperty) { this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } this.WriteLine(); } this.WriteObject(value, type); } finally { if (isProperty) { this.depth--; } } } public virtual void WriteBase64(byte[] value) { this.Write(Convert.ToBase64String(value)); } public virtual void WriteHexString(byte[] value) { if (value == null || value.Length == 0) { this.Write(String.Empty); return; } StringBuilder builder = new StringBuilder(); // Loop through each byte of the binary data // and format each one as a hexadecimal string for (int i=0; i<value.Length; i++) { builder.Append(value[i].ToString("x2")); } // the hexadecimal string this.Write(builder.ToString()); } public virtual void Write(DateTime value) { if (this.dateTimeSerializer != null) { this.dateTimeSerializer(this, value); return; } switch (value.Kind) { case DateTimeKind.Local: { value = value.ToUniversalTime(); goto case DateTimeKind.Utc; } case DateTimeKind.Utc: { // UTC DateTime in ISO-8601 this.Write(String.Format("{0:s}Z", value)); break; } default: { // DateTime in ISO-8601 this.Write(String.Format("{0:s}", value)); break; } } } public virtual void Write(Guid value) { this.Write(value.ToString("D")); } public virtual void Write(Enum value) { string enumName = null; Type type = value.GetType(); if (type.IsDefined(typeof(FlagsAttribute), true) && !Enum.IsDefined(type, value)) { Enum[] flags = JsonWriter.GetFlagList(type, value); string[] flagNames = new string[flags.Length]; for (int i=0; i<flags.Length; i++) { flagNames[i] = JsonNameAttribute.GetJsonName(flags[i]); if (String.IsNullOrEmpty(flagNames[i])) { flagNames[i] = flags[i].ToString("f"); } } enumName = String.Join(", ", flagNames); } else { enumName = JsonNameAttribute.GetJsonName(value); if (String.IsNullOrEmpty(enumName)) { enumName = value.ToString("f"); } } this.Write(enumName); } public virtual void Write(string value) { if (value == null) { this.writer.Write(JsonReader.LiteralNull); return; } int length = value.Length; int start = 0; this.writer.Write(JsonReader.OperatorStringDelim); for (int i = start; i < length; i++) { if (value[i] <= '\u001F' || value[i] >= '\u007F' || value[i] == '<' || value[i] == '\t' || value[i] == JsonReader.OperatorStringDelim || value[i] == JsonReader.OperatorCharEscape) { this.writer.Write(value.Substring(start, i-start)); start = i+1; switch (value[i]) { case JsonReader.OperatorStringDelim: case JsonReader.OperatorCharEscape: { this.writer.Write(JsonReader.OperatorCharEscape); this.writer.Write(value[i]); continue; } case '\b': { this.writer.Write("\\b"); continue; } case '\f': { this.writer.Write("\\f"); continue; } case '\n': { this.writer.Write("\\n"); continue; } case '\r': { this.writer.Write("\\r"); continue; } case '\t': { this.writer.Write("\\t"); continue; } default: { this.writer.Write("\\u{0:X4}", Char.ConvertToUtf32(value, i)); continue; } } } } this.writer.Write(value.Substring(start, length-start)); this.writer.Write(JsonReader.OperatorStringDelim); } #endregion Public Methods #region Primative Writer Methods public virtual void Write(bool value) { this.writer.Write(value ? JsonReader.LiteralTrue : JsonReader.LiteralFalse); } public virtual void Write(byte value) { this.writer.Write("{0:g}", value); } public virtual void Write(sbyte value) { this.writer.Write("{0:g}", value); } public virtual void Write(short value) { this.writer.Write("{0:g}", value); } public virtual void Write(ushort value) { this.writer.Write("{0:g}", value); } public virtual void Write(int value) { this.writer.Write("{0:g}", value); } public virtual void Write(uint value) { this.writer.Write("{0:g}", value); } public virtual void Write(long value) { this.writer.Write("{0:g}", value); } public virtual void Write(ulong value) { this.writer.Write("{0:g}", value); } public virtual void Write(float value) { if (this.StrictConformance && (Single.IsNaN(value) || Single.IsInfinity(value))) { this.writer.Write(JsonReader.LiteralNull); } else { this.writer.Write("{0:r}", value); } } public virtual void Write(double value) { if (this.StrictConformance && (Double.IsNaN(value) || Double.IsInfinity(value))) { this.writer.Write(JsonReader.LiteralNull); } else { this.writer.Write("{0:r}", value); } } public virtual void Write(decimal value) { this.writer.Write("{0:g}", value); } public virtual void Write(char value) { this.Write(new String(value, 1)); } public virtual void Write(TimeSpan value) { this.Write(value.Ticks); } public virtual void Write(Uri value) { this.Write(value.ToString()); } public virtual void Write(Version value) { this.Write(value.ToString()); } public virtual void Write(XmlNode value) { // TODO: auto-translate XML to JsonML this.Write(value.OuterXml); } #endregion Primative Writer Methods #region Writer Methods protected internal virtual void WriteArray(IEnumerable value) { bool appendDelim = false; this.writer.Write(JsonReader.OperatorArrayStart); this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } try { foreach (object item in value) { if (appendDelim) { this.writer.Write(JsonReader.OperatorValueDelim); } else { appendDelim = true; } this.WriteLine(); this.Write(item, false); } } finally { this.depth--; } if (appendDelim) { this.WriteLine(); } this.writer.Write(JsonReader.OperatorArrayEnd); } protected virtual void WriteObject(IDictionary value) { bool appendDelim = false; this.writer.Write(JsonReader.OperatorObjectStart); this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } try { foreach (object name in value.Keys) { if (appendDelim) { this.writer.Write(JsonReader.OperatorValueDelim); } else { appendDelim = true; } this.WriteLine(); this.Write((String)name); this.writer.Write(JsonReader.OperatorNameDelim); this.Write(value[name], true); } } finally { this.depth--; } if (appendDelim) { this.WriteLine(); } this.writer.Write(JsonReader.OperatorObjectEnd); } protected virtual void WriteObject(object value, Type type) { bool appendDelim = false; this.writer.Write(JsonReader.OperatorObjectStart); this.depth++; if (this.depth > this.maxDepth) { throw new JsonSerializationException(String.Format(JsonWriter.ErrorMaxDepth, this.maxDepth)); } try { if (!String.IsNullOrEmpty(this.TypeHintName)) { if (appendDelim) { this.writer.Write(JsonReader.OperatorValueDelim); } else { appendDelim = true; } this.WriteLine(); this.Write(this.TypeHintName); this.writer.Write(JsonReader.OperatorNameDelim); this.Write(type.FullName+", "+type.Assembly.GetName().Name, true); } bool anonymousType = type.IsGenericType && type.Name.StartsWith(JsonWriter.AnonymousTypePrefix); // serialize public properties PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { if (!property.CanRead) { continue; } if (!property.CanWrite && !anonymousType) { continue; } if (this.IsIgnored(type, property, value)) { continue; } object propertyValue = property.GetValue(value, null); if ((propertyValue == null) && SkipNullValue) { continue; } if (this.IsDefaultValue(property, propertyValue)) { continue; } if (appendDelim) { this.writer.Write(JsonReader.OperatorValueDelim); } else { appendDelim = true; } string propertyName = JsonNameAttribute.GetJsonName(property); if (String.IsNullOrEmpty(propertyName)) { propertyName = property.Name; } this.WriteLine(); this.Write(propertyName); this.writer.Write(JsonReader.OperatorNameDelim); this.Write(propertyValue, true); } // serialize public fields FieldInfo[] fields = type.GetFields(); foreach (FieldInfo field in fields) { if (!field.IsPublic || field.IsStatic) { continue; } if (this.IsIgnored(type, field, value)) { continue; } object fieldValue = field.GetValue(value); if (this.IsDefaultValue(field, fieldValue)) { continue; } if (appendDelim) { this.writer.Write(JsonReader.OperatorValueDelim); this.WriteLine(); } else { appendDelim = true; } string fieldName = JsonNameAttribute.GetJsonName(field); if (String.IsNullOrEmpty(fieldName)) { fieldName = field.Name; } // use Attributes here to control naming this.Write(fieldName); this.writer.Write(JsonReader.OperatorNameDelim); this.Write(fieldValue, true); } } finally { this.depth--; } if (appendDelim) { this.WriteLine(); } this.writer.Write(JsonReader.OperatorObjectEnd); } protected virtual void WriteLine() { if (!this.prettyPrint) { return; } this.writer.WriteLine(); for (int i=0; i<this.depth; i++) { this.writer.Write(this.tab); } } #endregion Writer Methods #region Private Methods /// <summary> /// Determines if the property or field should not be serialized. /// </summary> /// <param name="objType"></param> /// <param name="member"></param> /// <param name="value"></param> /// <returns></returns> /// <remarks> /// Checks these in order, if any returns true then this is true: /// - is flagged with the JsonIgnoreAttribute property /// - has a JsonSpecifiedProperty which returns false /// </remarks> private bool IsIgnored(Type objType, MemberInfo member, object obj) { if (JsonIgnoreAttribute.IsJsonIgnore(member)) { return true; } string specifiedProperty = JsonSpecifiedPropertyAttribute.GetJsonSpecifiedProperty(member); if (!String.IsNullOrEmpty(specifiedProperty)) { PropertyInfo specProp = objType.GetProperty(specifiedProperty); if (specProp != null) { object isSpecified = specProp.GetValue(obj, null); if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified)) { return true; } } } if (this.UseXmlSerializationAttributes) { if (JsonIgnoreAttribute.IsXmlIgnore(member)) { return true; } PropertyInfo specProp = objType.GetProperty(member.Name+"Specified"); if (specProp != null) { object isSpecified = specProp.GetValue(obj, null); if (isSpecified is Boolean && !Convert.ToBoolean(isSpecified)) { return true; } } } return false; } /// <summary> /// Determines if the member value matches the DefaultValue attribute /// </summary> /// <returns>if has a value equivalent to the DefaultValueAttribute</returns> private bool IsDefaultValue(MemberInfo member, object value) { DefaultValueAttribute attribute = Attribute.GetCustomAttribute(member, typeof(DefaultValueAttribute)) as DefaultValueAttribute; if (attribute == null) { return false; } if (attribute.Value == null) { return (value == null); } return (attribute.Value.Equals(value)); } #region GetFlagList /// <summary> /// Splits a bitwise-OR'd set of enums into a list. /// </summary> /// <param name="enumType">the enum type</param> /// <param name="value">the combined value</param> /// <returns>list of flag enums</returns> /// <remarks> /// from PseudoCode.EnumHelper /// </remarks> private static Enum[] GetFlagList(Type enumType, object value) { ulong longVal = Convert.ToUInt64(value); Array enumValues = Enum.GetValues(enumType); List<Enum> enums = new List<Enum>(enumValues.Length); // check for empty if (longVal == 0L) { // Return the value of empty, or zero if none exists if (Convert.ToUInt64(enumValues.GetValue(0)) == 0L) enums.Add(enumValues.GetValue(0) as Enum); else enums.Add(null); return enums.ToArray(); } for (int i = enumValues.Length-1; i >= 0; i--) { ulong enumValue = Convert.ToUInt64(enumValues.GetValue(i)); if ((i == 0) && (enumValue == 0L)) continue; // matches a value in enumeration if ((longVal & enumValue) == enumValue) { // remove from val longVal -= enumValue; // add enum to list enums.Add(enumValues.GetValue(i) as Enum); } } if (longVal != 0x0L) enums.Add(Enum.ToObject(enumType, longVal) as Enum); return enums.ToArray(); } #endregion GetFlagList #endregion Private Methods #region Utility Methods /// <summary> /// Verifies is a valid EcmaScript variable expression. /// </summary> /// <param name="varExpr">the variable expression</param> /// <returns>varExpr</returns> public static string EnsureValidIdentifier(string varExpr, bool nested) { return JsonWriter.EnsureValidIdentifier(varExpr, nested, true); } /// <summary> /// Verifies is a valid EcmaScript variable expression. /// </summary> /// <param name="varExpr">the variable expression</param> /// <returns>varExpr</returns> /// <remarks> /// http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf /// /// IdentifierName = /// IdentifierStart | IdentifierName IdentifierPart /// IdentifierStart = /// Letter | '$' | '_' /// IdentifierPart = /// IdentifierStart | Digit /// </remarks> public static string EnsureValidIdentifier(string varExpr, bool nested, bool throwOnEmpty) { if (String.IsNullOrEmpty(varExpr)) { if (throwOnEmpty) { throw new ArgumentException("Variable expression is empty."); } return String.Empty; } varExpr = varExpr.Replace(" ", ""); bool indentPart = false; // TODO: ensure not a keyword foreach (char ch in varExpr) { if (indentPart) { if (ch == '.' && nested) { // reset to IndentifierStart indentPart = false; continue; } if (Char.IsDigit(ch)) { continue; } } // can be start or part if (Char.IsLetterOrDigit(ch) || ch == '_' || ch == '$'||ch=='-') { indentPart = true; continue; } throw new ArgumentException("Variable expression \""+varExpr+"\" is not supported."); } return varExpr; } #endregion Utility Methods #region IDisposable Members void IDisposable.Dispose() { if (this.writer != null) { this.writer.Dispose(); } } #endregion IDisposable Members } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Orleans.Runtime; using Orleans.Concurrency; using Orleans.Runtime.Configuration; namespace Orleans { /// <summary> /// Interface for Membership Table. /// </summary> public interface IMembershipTable { /// <summary> /// Initializes the membership table, will be called before all other methods /// </summary> /// <param name="globalConfiguration">the give global configuration</param> /// <param name="tryInitTableVersion">whether an attempt will be made to init the underlying table</param> /// <param name="traceLogger">the logger used by the membership table</param> Task InitializeMembershipTable(GlobalConfiguration globalConfiguration, bool tryInitTableVersion, TraceLogger traceLogger); /// <summary> /// Deletes all table entries of the given deploymentId /// </summary> Task DeleteMembershipTableEntries(string deploymentId); /// <summary> /// Atomically reads the Membership Table information about a given silo. /// The returned MembershipTableData includes one MembershipEntry entry for a given silo and the /// TableVersion for this table. The MembershipEntry and the TableVersion have to be read atomically. /// </summary> /// <param name="entry">The address of the silo whose membership information needs to be read.</param> /// <returns>The membership information for a given silo: MembershipTableData consisting one MembershipEntry entry and /// TableVersion, read atomically.</returns> Task<MembershipTableData> ReadRow(SiloAddress key); /// <summary> /// Atomically reads the full content of the Membership Table. /// The returned MembershipTableData includes all MembershipEntry entry for all silos in the table and the /// TableVersion for this table. The MembershipEntries and the TableVersion have to be read atomically. /// </summary> /// <returns>The membership information for a given table: MembershipTableData consisting multiple MembershipEntry entries and /// TableVersion, all read atomically.</returns> Task<MembershipTableData> ReadAll(); /// <summary> /// Atomically tries to insert (add) a new MembershipEntry for one silo and also update the TableVersion. /// If operation succeeds, the following changes would be made to the table: /// 1) New MembershipEntry will be added to the table. /// 2) The newly added MembershipEntry will also be added with the new unique automatically generated eTag. /// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version. /// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag. /// All those changes to the table, insert of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects. /// The operation should fail in each of the following conditions: /// 1) A MembershipEntry for a given silo already exist in the table /// 2) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table. /// </summary> /// <param name="entry">MembershipEntry to be inserted.</param> /// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param> /// <returns>True if the insert operation succeeded and false otherwise.</returns> Task<bool> InsertRow(MembershipEntry entry, TableVersion tableVersion); /// <summary> /// Atomically tries to update the MembershipEntry for one silo and also update the TableVersion. /// If operation succeeds, the following changes would be made to the table: /// 1) The MembershipEntry for this silo will be updated to the new MembershipEntry (the old entry will be fully substitued by the new entry) /// 2) The eTag for the updated MembershipEntry will also be eTag with the new unique automatically generated eTag. /// 3) TableVersion.Version in the table will be updated to the new TableVersion.Version. /// 4) TableVersion etag in the table will be updated to the new unique automatically generated eTag. /// All those changes to the table, update of a new row and update of the table version and the associated etags, should happen atomically, or fail atomically with no side effects. /// The operation should fail in each of the following conditions: /// 1) A MembershipEntry for a given silo does not exist in the table /// 2) A MembershipEntry for a given silo exist in the table but its etag in the table does not match the provided etag. /// 3) Update of the TableVersion failed since the given TableVersion etag (as specified by the TableVersion.VersionEtag property) did not match the TableVersion etag in the table. /// </summary> /// <param name="entry">MembershipEntry to be updated.</param> /// <param name="etag">The etag for the given MembershipEntry.</param> /// <param name="tableVersion">The new TableVersion for this table, along with its etag.</param> /// <returns>True if the update operation succeeded and false otherwise.</returns> Task<bool> UpdateRow(MembershipEntry entry, string etag, TableVersion tableVersion); /// <summary> /// Updates the IAmAlive part (column) of the MembershipEntry for this silo. /// This operation should only update the IAmAlive collumn and not change other columns. /// This operation is a "dirty write" or "in place update" and is performed without etag validation. /// With regards to eTags update: /// This operation may automatically update the eTag associated with the given silo row, but it does not have to. It can also leave the etag not changed ("dirty write"). /// With regards to TableVersion: /// this operation should not change the TableVersion of the table. It should leave it untouched. /// There is no scenario where this operation could fail due to table semantical reasons. It can only fail due to network problems or table unavailability. /// </summary> /// <param name="entry"></param> /// <returns>Task representing the successful execution of this operation. </returns> Task UpdateIAmAlive(MembershipEntry entry); } /// <summary> /// Membership table interface for grain based implementation. /// </summary> [Unordered] public interface IMembershipTableGrain : IGrainWithGuidKey, IMembershipTable { } [Serializable] [Immutable] public class TableVersion { /// <summary> /// The version part of this TableVersion. Monotonically increasing number. /// </summary> public int Version { get; private set; } /// <summary> /// The etag of this TableVersion, used for validation of table update operations. /// </summary> public string VersionEtag { get; private set; } public TableVersion(int version, string eTag) { Version = version; VersionEtag = eTag; } public TableVersion Next() { return new TableVersion(Version + 1, VersionEtag); } public override string ToString() { return string.Format("<{0}, {1}>", Version, VersionEtag); } } [Serializable] public class MembershipTableData { public IReadOnlyList<Tuple<MembershipEntry, string>> Members { get; private set; } public TableVersion Version { get; private set; } public MembershipTableData(List<Tuple<MembershipEntry, string>> list, TableVersion version) { // put deads at the end, just for logging. list.Sort( (x, y) => { if (x.Item1.Status.Equals(SiloStatus.Dead)) return 1; // put Deads at the end if (y.Item1.Status.Equals(SiloStatus.Dead)) return -1; // put Deads at the end return String.Compare(x.Item1.InstanceName, y.Item1.InstanceName, StringComparison.Ordinal); }); Members = list.AsReadOnly(); Version = version; } public MembershipTableData(Tuple<MembershipEntry, string> tuple, TableVersion version) { Members = (new List<Tuple<MembershipEntry, string>> { tuple }).AsReadOnly(); Version = version; } public MembershipTableData(TableVersion version) { Members = (new List<Tuple<MembershipEntry, string>>()).AsReadOnly(); Version = version; } public Tuple<MembershipEntry, string> Get(SiloAddress silo) { return Members.First(tuple => tuple.Item1.SiloAddress.Equals(silo)); } public bool Contains(SiloAddress silo) { return Members.Any(tuple => tuple.Item1.SiloAddress.Equals(silo)); } public override string ToString() { int active = Members.Count(e => e.Item1.Status == SiloStatus.Active); int dead = Members.Count(e => e.Item1.Status == SiloStatus.Dead); int created = Members.Count(e => e.Item1.Status == SiloStatus.Created); int joining = Members.Count(e => e.Item1.Status == SiloStatus.Joining); int shuttingDown = Members.Count(e => e.Item1.Status == SiloStatus.ShuttingDown); int stopping = Members.Count(e => e.Item1.Status == SiloStatus.Stopping); string otherCounts = String.Format("{0}{1}{2}{3}", created > 0 ? (", " + created + " are Created") : "", joining > 0 ? (", " + joining + " are Joining") : "", shuttingDown > 0 ? (", " + shuttingDown + " are ShuttingDown") : "", stopping > 0 ? (", " + stopping + " are Stopping") : ""); return string.Format("{0} silos, {1} are Active, {2} are Dead{3}, Version={4}. All silos: {5}", Members.Count, active, dead, otherCounts, Version, Utils.EnumerableToString(Members, tuple => tuple.Item1.ToFullString())); } // return a copy of the table removing all dead appereances of dead nodes, except for the last one. public MembershipTableData SupressDuplicateDeads() { var dead = new Dictionary<IPEndPoint, Tuple<MembershipEntry, string>>(); // pick only latest Dead for each instance foreach (var next in Members.Where(item => item.Item1.Status == SiloStatus.Dead)) { var ipEndPoint = next.Item1.SiloAddress.Endpoint; Tuple<MembershipEntry, string> prev; if (!dead.TryGetValue(ipEndPoint, out prev)) { dead[ipEndPoint] = next; } else { // later dead. if (next.Item1.SiloAddress.Generation.CompareTo(prev.Item1.SiloAddress.Generation) > 0) dead[ipEndPoint] = next; } } //now add back non-dead List<Tuple<MembershipEntry, string>> all = dead.Values.ToList(); all.AddRange(Members.Where(item => item.Item1.Status != SiloStatus.Dead)); return new MembershipTableData(all, Version); } } [Serializable] public class MembershipEntry { public SiloAddress SiloAddress { get; set; } public string HostName { get; set; } public SiloStatus Status { get; set; } public int ProxyPort { get; set; } public string RoleName { get; set; } // Optional - only for Azure role public string InstanceName { get; set; } // Optional - only for Azure role public int UpdateZone { get; set; } // Optional - only for Azure role public int FaultZone { get; set; } // Optional - only for Azure role public DateTime StartTime { get; set; } // Time this silo was started. For diagnostics. public DateTime IAmAliveTime { get; set; } // Time this silo updated it was alive. For diagnostics. public List<Tuple<SiloAddress, DateTime>> SuspectTimes { get; set; } private static readonly List<Tuple<SiloAddress, DateTime>> EmptyList = new List<Tuple<SiloAddress, DateTime>>(0); public void AddSuspector(SiloAddress suspectingSilo, DateTime suspectingTime) { if (SuspectTimes == null) SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(); var suspector = new Tuple<SiloAddress, DateTime>(suspectingSilo, suspectingTime); SuspectTimes.Add(suspector); } // partialUpdate arrivies via gossiping with other oracles. In such a case only take the status. internal void Update(MembershipEntry updatedSiloEntry) { SiloAddress = updatedSiloEntry.SiloAddress; Status = updatedSiloEntry.Status; //--- HostName = updatedSiloEntry.HostName; ProxyPort = updatedSiloEntry.ProxyPort; RoleName = updatedSiloEntry.RoleName; InstanceName = updatedSiloEntry.InstanceName; UpdateZone = updatedSiloEntry.UpdateZone; FaultZone = updatedSiloEntry.FaultZone; SuspectTimes = updatedSiloEntry.SuspectTimes; StartTime = updatedSiloEntry.StartTime; IAmAliveTime = updatedSiloEntry.IAmAliveTime; } internal List<Tuple<SiloAddress, DateTime>> GetFreshVotes(TimeSpan expiration) { if (SuspectTimes == null) return EmptyList; DateTime now = DateTime.UtcNow; return SuspectTimes.FindAll(voter => { DateTime otherVoterTime = voter.Item2; // If now is smaller than otherVoterTime, than assume the otherVoterTime is fresh. // This could happen if clocks are not synchronized and the other voter clock is ahead of mine. if (now < otherVoterTime) return true; return now.Subtract(otherVoterTime) < expiration; }); } internal void TryUpdateStartTime(DateTime startTime) { if (StartTime.Equals(default(DateTime))) StartTime = startTime; } public override string ToString() { return string.Format("SiloAddress={0} InstanceName={1} Status={2}", SiloAddress.ToLongString(), InstanceName, Status); } internal string ToFullString(bool full = false) { if (!full) return ToString(); List<SiloAddress> suspecters = SuspectTimes == null ? null : SuspectTimes.Select(tuple => tuple.Item1).ToList(); List<DateTime> timestamps = SuspectTimes == null ? null : SuspectTimes.Select(tuple => tuple.Item2).ToList(); return string.Format("[SiloAddress={0} InstanceName={1} Status={2} HostName={3} ProxyPort={4} " + "RoleName={5} UpdateZone={6} FaultZone={7} StartTime = {8} IAmAliveTime = {9} {10} {11}]", SiloAddress.ToLongString(), InstanceName, Status, HostName, ProxyPort, RoleName, UpdateZone, FaultZone, TraceLogger.PrintDate(StartTime), TraceLogger.PrintDate(IAmAliveTime), suspecters == null ? "" : "Suspecters = " + Utils.EnumerableToString(suspecters, sa => sa.ToLongString()), timestamps == null ? "" : "SuspectTimes = " + Utils.EnumerableToString(timestamps, TraceLogger.PrintDate) ); } } }
// MIT License // // Copyright(c) 2022 ICARUS Consulting GmbH // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; namespace Yaapii.Atoms.Func { /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <typeparam name="In"></typeparam> /// <typeparam name="Out"></typeparam> public sealed class FuncWithFallback<In, Out> : IFunc<In, Out> { /// <summary> /// func to call /// </summary> private readonly IFunc<In, Out> fund; /// <summary> /// fallback to call when necessary /// </summary> private readonly IFunc<Exception, Out> fallback; /// <summary> /// a followup function /// </summary> private readonly IFunc<Out, Out> follow; /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public FuncWithFallback(System.Func<In, Out> func, System.Func<Exception, Out> fallback) : this( new FuncOf<In, Out>((X) => func(X)), new FuncOf<Exception, Out>((e) => fallback(e))) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public FuncWithFallback(System.Func<In, Out> func, Atoms.IFunc<Exception, Out> fallback) : this( new FuncOf<In, Out>((X) => func(X)), fallback) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> public FuncWithFallback(IFunc<In, Out> fnc, IFunc<Exception, Out> fbk) : this( fnc, fbk, new FuncOf<Out, Out>((input) => input)) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> /// <param name="flw">func to call afterwards</param> public FuncWithFallback(System.Func<In, Out> func, System.Func<Exception, Out> fallback, System.Func<Out, Out> flw) : this( new FuncOf<In, Out>((X) => func(X)), new FuncOf<Exception, Out>((e) => fallback(e)), new FuncOf<Out, Out>(flw)) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> /// <param name="flw">func to call afterwards</param> public FuncWithFallback(IFunc<In, Out> fnc, IFunc<Exception, Out> fbk, IFunc<Out, Out> flw) { this.fund = fnc; this.fallback = fbk; this.follow = flw; } /// <summary> /// invoke function with input and retrieve output. /// </summary> /// <param name="input">input argument</param> /// <returns>the result</returns> public Out Invoke(In input) { Out result; try { result = this.fund.Invoke(input); } catch (Exception ex) { result = this.fallback.Invoke(ex); } return this.follow.Invoke(result); } } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <typeparam name="Out">Return type</typeparam> public sealed class FuncWithFallback<Out> : IFunc<Out> { /// <summary> /// func to call /// </summary> private readonly IFunc<Out> func; /// <summary> /// fallback to call when necessary /// </summary> private readonly IFunc<Exception, Out> fallback; /// <summary> /// a followup function /// </summary> private readonly IFunc<Out, Out> follow; /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public FuncWithFallback(System.Func<Out> func, System.Func<Exception, Out> fallback) : this( new FuncOf<Out>(() => func()), new FuncOf<Exception, Out>((e) => fallback(e))) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public FuncWithFallback(System.Func<Out> func, Atoms.IFunc<Exception, Out> fallback) : this( new FuncOf<Out>(() => func()), fallback) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> public FuncWithFallback(IFunc<Out> fnc, IFunc<Exception, Out> fbk) : this( fnc, fbk, new FuncOf<Out, Out>((input) => input)) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> /// <param name="flw">func to call afterwards</param> public FuncWithFallback(System.Func<Out> func, System.Func<Exception, Out> fallback, System.Func<Out, Out> flw) : this( new FuncOf<Out>(() => func()), new FuncOf<Exception, Out>((e) => fallback(e)), new FuncOf<Out, Out>(flw)) { } /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> /// <param name="flw">func to call afterwards</param> public FuncWithFallback(IFunc<Out> fnc, IFunc<Exception, Out> fbk, IFunc<Out, Out> flw) { this.func = fnc; this.fallback = fbk; this.follow = flw; } /// <summary> /// Get output /// </summary> /// <returns></returns> public Out Invoke() { Out result; try { result = this.func.Invoke(); } catch (Exception ex) { result = this.fallback.Invoke(ex); } return this.follow.Invoke(result); } } public static class FuncWithFallback { /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public static IFunc<In, Out> New<In, Out>(System.Func<In, Out> func, System.Func<Exception, Out> fallback) => new FuncWithFallback<In, Out>(func, fallback); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public static IFunc<In, Out> New<In, Out>(System.Func<In, Out> func, Atoms.IFunc<Exception, Out> fallback) => new FuncWithFallback<In, Out>(func, fallback); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> public static IFunc<In, Out> New<In, Out>(IFunc<In, Out> fnc, IFunc<Exception, Out> fbk) => new FuncWithFallback<In, Out>(fnc, fbk); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> /// <param name="flw">func to call afterwards</param> public static IFunc<In, Out> New<In, Out>(System.Func<In, Out> func, System.Func<Exception, Out> fallback, System.Func<Out, Out> flw) => new FuncWithFallback<In, Out>(func, fallback, flw); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> /// <param name="flw">func to call afterwards</param> public static IFunc<In, Out> New<In, Out>(IFunc<In, Out> fnc, IFunc<Exception, Out> fbk, IFunc<Out, Out> flw) => new FuncWithFallback<In, Out>(fnc, fbk, flw); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public static IFunc<Out> New<Out>(System.Func<Out> func, System.Func<Exception, Out> fallback) => new FuncWithFallback<Out>(func, fallback); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> public static IFunc<Out> New<Out>(System.Func<Out> func, Atoms.IFunc<Exception, Out> fallback) => new FuncWithFallback<Out>(func, fallback); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> public static IFunc<Out> New<Out>(IFunc<Out> fnc, IFunc<Exception, Out> fbk) => new FuncWithFallback<Out>(fnc, fbk); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="func">func to call</param> /// <param name="fallback">fallback func</param> /// <param name="flw">func to call afterwards</param> public static IFunc<Out> New<Out>(System.Func<Out> func, System.Func<Exception, Out> fallback, System.Func<Out, Out> flw) => new FuncWithFallback<Out>(func, fallback, flw); /// <summary> /// A function that executes a callback if it fails (= an <see cref="Exception"/> occurs). /// </summary> /// <param name="fnc">func to call</param> /// <param name="fbk">fallback func</param> /// <param name="flw">func to call afterwards</param> public static IFunc<Out> New<Out>(IFunc<Out> fnc, IFunc<Exception, Out> fbk, IFunc<Out, Out> flw) => new FuncWithFallback<Out>(fnc, fbk, flw); } }
using System.Text.RegularExpressions; using System.Diagnostics; using System; using System.Drawing.Drawing2D; using System.Windows.Forms; using System.Collections; using System.Drawing; using Microsoft.VisualBasic; using System.Data.SqlClient; using System.Data; using System.Collections.Generic; using WeifenLuo.WinFormsUI; using Microsoft.Win32; using WeifenLuo; namespace SoftLogik.Win { namespace Security { [global::Microsoft.VisualBasic.CompilerServices.DesignerGenerated()]public partial class SecurityForm : UI.DockableForm { //Form overrides dispose to clean up the component list. [System.Diagnostics.DebuggerNonUserCode()]protected override void Dispose(bool disposing) { try { if (disposing && (components != null)) { components.Dispose(); } } finally { base.Dispose(disposing); } } //Required by the Windows Form Designer private System.ComponentModel.Container components = null; //NOTE: The following procedure is required by the Windows Form Designer //It can be modified using the Windows Form Designer. //Do not modify it using the code editor. [System.Diagnostics.DebuggerStepThrough()]private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SecurityForm)); this.SplitContainer = new System.Windows.Forms.SplitContainer(); this.tvwSecurity = new System.Windows.Forms.TreeView(); this.splSecurity = new System.Windows.Forms.SplitContainer(); this.pnlApplication = new System.Windows.Forms.Panel(); this.lblNote = new System.Windows.Forms.Label(); this.lblAppName = new System.Windows.Forms.Label(); this.txtAppNote = new System.Windows.Forms.TextBox(); this.txtAppName = new System.Windows.Forms.TextBox(); this.pnlRole = new System.Windows.Forms.Panel(); this.gbxRoleCreated = new System.Windows.Forms.GroupBox(); this.Label7 = new System.Windows.Forms.Label(); this.Label8 = new System.Windows.Forms.Label(); this.Label9 = new System.Windows.Forms.Label(); this.Label10 = new System.Windows.Forms.Label(); this.txtRoleNote = new System.Windows.Forms.TextBox(); this.lblRoleNote = new System.Windows.Forms.Label(); this.txtRoleName = new System.Windows.Forms.TextBox(); this.lblRoleName = new System.Windows.Forms.Label(); this.pnlUser = new System.Windows.Forms.Panel(); this.gbxUserCreated = new System.Windows.Forms.GroupBox(); this.lblModifiedDate = new System.Windows.Forms.Label(); this.lblUserCreateDate = new System.Windows.Forms.Label(); this.lblUserModified = new System.Windows.Forms.Label(); this.Label2 = new System.Windows.Forms.Label(); this.txtUserCreated = new System.Windows.Forms.Label(); this.lblUserCreated = new System.Windows.Forms.Label(); this.txtUserNote = new System.Windows.Forms.TextBox(); this.lblUserNote = new System.Windows.Forms.Label(); this.txtLName = new System.Windows.Forms.TextBox(); this.txtFName = new System.Windows.Forms.TextBox(); this.lblLName = new System.Windows.Forms.Label(); this.lblFName = new System.Windows.Forms.Label(); this.txtUserName = new System.Windows.Forms.TextBox(); this.lblUserName = new System.Windows.Forms.Label(); this.tvwPolicy = new System.Windows.Forms.TreeView(); this.SPApplicationBindingSource = new System.Windows.Forms.BindingSource(this.components); this.SPUserBindingSource = new System.Windows.Forms.BindingSource(this.components); this.m_dsUserSecurity = new SoftLogik.Win.dsUserSecurity(); this.TreeNodeImageList = new System.Windows.Forms.ImageList(this.components); ((System.ComponentModel.ISupportInitialize) this.ErrorNotify).BeginInit(); this.SplitContainer.Panel1.SuspendLayout(); this.SplitContainer.Panel2.SuspendLayout(); this.SplitContainer.SuspendLayout(); this.splSecurity.Panel1.SuspendLayout(); this.splSecurity.Panel2.SuspendLayout(); this.splSecurity.SuspendLayout(); this.pnlApplication.SuspendLayout(); this.pnlRole.SuspendLayout(); this.gbxRoleCreated.SuspendLayout(); this.pnlUser.SuspendLayout(); this.gbxUserCreated.SuspendLayout(); ((System.ComponentModel.ISupportInitialize) this.SPApplicationBindingSource).BeginInit(); ((System.ComponentModel.ISupportInitialize) this.SPUserBindingSource).BeginInit(); ((System.ComponentModel.ISupportInitialize) this.m_dsUserSecurity).BeginInit(); this.SuspendLayout(); // //SplitContainer // this.SplitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.SplitContainer.Location = new System.Drawing.Point(0, 0); this.SplitContainer.Name = "SplitContainer"; // //SplitContainer.Panel1 // this.SplitContainer.Panel1.Controls.Add(this.tvwSecurity); // //SplitContainer.Panel2 // this.SplitContainer.Panel2.Controls.Add(this.splSecurity); this.SplitContainer.Size = new System.Drawing.Size(858, 449); this.SplitContainer.SplitterDistance = 193; this.SplitContainer.TabIndex = 1; this.SplitContainer.Text = "SplitContainer1"; // //tvwSecurity // this.tvwSecurity.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwSecurity.HotTracking = true; this.tvwSecurity.Location = new System.Drawing.Point(0, 0); this.tvwSecurity.Name = "tvwSecurity"; this.tvwSecurity.ShowLines = false; this.tvwSecurity.Size = new System.Drawing.Size(193, 449); this.tvwSecurity.TabIndex = 0; // //splSecurity // this.splSecurity.Dock = System.Windows.Forms.DockStyle.Fill; this.splSecurity.Location = new System.Drawing.Point(0, 0); this.splSecurity.Name = "splSecurity"; this.splSecurity.Orientation = System.Windows.Forms.Orientation.Horizontal; // //splSecurity.Panel1 // this.splSecurity.Panel1.Controls.Add(this.pnlApplication); this.splSecurity.Panel1.Controls.Add(this.pnlRole); this.splSecurity.Panel1.Controls.Add(this.pnlUser); // //splSecurity.Panel2 // this.splSecurity.Panel2.Controls.Add(this.tvwPolicy); this.splSecurity.Size = new System.Drawing.Size(661, 449); this.splSecurity.SplitterDistance = 241; this.splSecurity.TabIndex = 3; // //pnlApplication // this.pnlApplication.Controls.Add(this.lblNote); this.pnlApplication.Controls.Add(this.lblAppName); this.pnlApplication.Controls.Add(this.txtAppNote); this.pnlApplication.Controls.Add(this.txtAppName); this.pnlApplication.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlApplication.Location = new System.Drawing.Point(0, 0); this.pnlApplication.Name = "pnlApplication"; this.pnlApplication.Size = new System.Drawing.Size(661, 241); this.pnlApplication.TabIndex = 10; // //lblNote // this.lblNote.AutoSize = true; this.lblNote.Location = new System.Drawing.Point(37, 86); this.lblNote.Name = "lblNote"; this.lblNote.Size = new System.Drawing.Size(33, 13); this.lblNote.TabIndex = 15; this.lblNote.Text = "&Note:"; // //lblAppName // this.lblAppName.AutoSize = true; this.lblAppName.Location = new System.Drawing.Point(36, 60); this.lblAppName.Name = "lblAppName"; this.lblAppName.Size = new System.Drawing.Size(38, 13); this.lblAppName.TabIndex = 14; this.lblAppName.Text = "Name:"; // //txtAppNote // this.txtAppNote.BackColor = System.Drawing.SystemColors.Control; this.txtAppNote.ForeColor = System.Drawing.SystemColors.Highlight; this.txtAppNote.Location = new System.Drawing.Point(76, 83); this.txtAppNote.Multiline = true; this.txtAppNote.Name = "txtAppNote"; this.txtAppNote.ReadOnly = true; this.txtAppNote.Size = new System.Drawing.Size(353, 88); this.txtAppNote.TabIndex = 13; // //txtAppName // this.txtAppName.BackColor = System.Drawing.SystemColors.Control; this.txtAppName.ForeColor = System.Drawing.SystemColors.Highlight; this.txtAppName.Location = new System.Drawing.Point(76, 57); this.txtAppName.Name = "txtAppName"; this.txtAppName.ReadOnly = true; this.txtAppName.Size = new System.Drawing.Size(318, 20); this.txtAppName.TabIndex = 12; // //pnlRole // this.pnlRole.Controls.Add(this.gbxRoleCreated); this.pnlRole.Controls.Add(this.txtRoleNote); this.pnlRole.Controls.Add(this.lblRoleNote); this.pnlRole.Controls.Add(this.txtRoleName); this.pnlRole.Controls.Add(this.lblRoleName); this.pnlRole.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlRole.Location = new System.Drawing.Point(0, 0); this.pnlRole.Name = "pnlRole"; this.pnlRole.Size = new System.Drawing.Size(661, 241); this.pnlRole.TabIndex = 8; // //gbxRoleCreated // this.gbxRoleCreated.Controls.Add(this.Label7); this.gbxRoleCreated.Controls.Add(this.Label8); this.gbxRoleCreated.Controls.Add(this.Label9); this.gbxRoleCreated.Controls.Add(this.Label10); this.gbxRoleCreated.Location = new System.Drawing.Point(405, 7); this.gbxRoleCreated.Name = "gbxRoleCreated"; this.gbxRoleCreated.Size = new System.Drawing.Size(189, 180); this.gbxRoleCreated.TabIndex = 22; this.gbxRoleCreated.TabStop = false; this.gbxRoleCreated.Text = "More Information"; // //Label7 // this.Label7.AutoSize = true; this.Label7.Location = new System.Drawing.Point(104, 41); this.Label7.Name = "Label7"; this.Label7.Size = new System.Drawing.Size(0, 13); this.Label7.TabIndex = 13; // //Label8 // this.Label8.AutoSize = true; this.Label8.Location = new System.Drawing.Point(8, 41); this.Label8.Name = "Label8"; this.Label8.Size = new System.Drawing.Size(90, 13); this.Label8.TabIndex = 12; this.Label8.Text = "Last Modified On:"; // //Label9 // this.Label9.AutoSize = true; this.Label9.Location = new System.Drawing.Point(79, 16); this.Label9.Name = "Label9"; this.Label9.Size = new System.Drawing.Size(0, 13); this.Label9.TabIndex = 11; // //Label10 // this.Label10.AutoSize = true; this.Label10.Location = new System.Drawing.Point(6, 16); this.Label10.Name = "Label10"; this.Label10.Size = new System.Drawing.Size(67, 13); this.Label10.TabIndex = 10; this.Label10.Text = "Created On: "; // //txtRoleNote // this.txtRoleNote.Location = new System.Drawing.Point(67, 45); this.txtRoleNote.Multiline = true; this.txtRoleNote.Name = "txtRoleNote"; this.txtRoleNote.Size = new System.Drawing.Size(327, 99); this.txtRoleNote.TabIndex = 21; // //lblRoleNote // this.lblRoleNote.AutoSize = true; this.lblRoleNote.Location = new System.Drawing.Point(11, 48); this.lblRoleNote.Name = "lblRoleNote"; this.lblRoleNote.Size = new System.Drawing.Size(33, 13); this.lblRoleNote.TabIndex = 20; this.lblRoleNote.Text = "&Note:"; // //txtRoleName // this.txtRoleName.Location = new System.Drawing.Point(67, 19); this.txtRoleName.Name = "txtRoleName"; this.txtRoleName.Size = new System.Drawing.Size(291, 20); this.txtRoleName.TabIndex = 19; // //lblRoleName // this.lblRoleName.AutoSize = true; this.lblRoleName.Location = new System.Drawing.Point(11, 22); this.lblRoleName.Name = "lblRoleName"; this.lblRoleName.Size = new System.Drawing.Size(38, 13); this.lblRoleName.TabIndex = 18; this.lblRoleName.Text = "Name:"; // //pnlUser // this.pnlUser.Controls.Add(this.gbxUserCreated); this.pnlUser.Controls.Add(this.txtUserNote); this.pnlUser.Controls.Add(this.lblUserNote); this.pnlUser.Controls.Add(this.txtLName); this.pnlUser.Controls.Add(this.txtFName); this.pnlUser.Controls.Add(this.lblLName); this.pnlUser.Controls.Add(this.lblFName); this.pnlUser.Controls.Add(this.txtUserName); this.pnlUser.Controls.Add(this.lblUserName); this.pnlUser.Dock = System.Windows.Forms.DockStyle.Fill; this.pnlUser.Location = new System.Drawing.Point(0, 0); this.pnlUser.Name = "pnlUser"; this.pnlUser.Size = new System.Drawing.Size(661, 241); this.pnlUser.TabIndex = 9; // //gbxUserCreated // this.gbxUserCreated.Controls.Add(this.lblModifiedDate); this.gbxUserCreated.Controls.Add(this.lblUserCreateDate); this.gbxUserCreated.Controls.Add(this.lblUserModified); this.gbxUserCreated.Controls.Add(this.Label2); this.gbxUserCreated.Controls.Add(this.txtUserCreated); this.gbxUserCreated.Controls.Add(this.lblUserCreated); this.gbxUserCreated.Location = new System.Drawing.Point(401, 3); this.gbxUserCreated.Name = "gbxUserCreated"; this.gbxUserCreated.Size = new System.Drawing.Size(188, 180); this.gbxUserCreated.TabIndex = 21; this.gbxUserCreated.TabStop = false; this.gbxUserCreated.Text = "More Information"; // //lblModifiedDate // this.lblModifiedDate.AutoSize = true; this.lblModifiedDate.Location = new System.Drawing.Point(94, 41); this.lblModifiedDate.Name = "lblModifiedDate"; this.lblModifiedDate.Size = new System.Drawing.Size(42, 13); this.lblModifiedDate.TabIndex = 15; this.lblModifiedDate.Text = "<Date>"; // //lblUserCreateDate // this.lblUserCreateDate.AutoSize = true; this.lblUserCreateDate.Location = new System.Drawing.Point(80, 16); this.lblUserCreateDate.Name = "lblUserCreateDate"; this.lblUserCreateDate.Size = new System.Drawing.Size(42, 13); this.lblUserCreateDate.TabIndex = 14; this.lblUserCreateDate.Text = "<Date>"; // //lblUserModified // this.lblUserModified.AutoSize = true; this.lblUserModified.Location = new System.Drawing.Point(104, 41); this.lblUserModified.Name = "lblUserModified"; this.lblUserModified.Size = new System.Drawing.Size(0, 13); this.lblUserModified.TabIndex = 13; // //Label2 // this.Label2.AutoSize = true; this.Label2.Location = new System.Drawing.Point(8, 41); this.Label2.Name = "Label2"; this.Label2.Size = new System.Drawing.Size(90, 13); this.Label2.TabIndex = 12; this.Label2.Text = "Last Modified On:"; // //txtUserCreated // this.txtUserCreated.AutoSize = true; this.txtUserCreated.Location = new System.Drawing.Point(79, 16); this.txtUserCreated.Name = "txtUserCreated"; this.txtUserCreated.Size = new System.Drawing.Size(0, 13); this.txtUserCreated.TabIndex = 11; // //lblUserCreated // this.lblUserCreated.AutoSize = true; this.lblUserCreated.Location = new System.Drawing.Point(6, 16); this.lblUserCreated.Name = "lblUserCreated"; this.lblUserCreated.Size = new System.Drawing.Size(67, 13); this.lblUserCreated.TabIndex = 10; this.lblUserCreated.Text = "Created On: "; // //txtUserNote // this.txtUserNote.Location = new System.Drawing.Point(76, 84); this.txtUserNote.Multiline = true; this.txtUserNote.Name = "txtUserNote"; this.txtUserNote.Size = new System.Drawing.Size(319, 99); this.txtUserNote.TabIndex = 20; // //lblUserNote // this.lblUserNote.AutoSize = true; this.lblUserNote.Location = new System.Drawing.Point(9, 84); this.lblUserNote.Name = "lblUserNote"; this.lblUserNote.Size = new System.Drawing.Size(33, 13); this.lblUserNote.TabIndex = 19; this.lblUserNote.Text = "&Note:"; // //txtLName // this.txtLName.Location = new System.Drawing.Point(76, 60); this.txtLName.Name = "txtLName"; this.txtLName.Size = new System.Drawing.Size(319, 20); this.txtLName.TabIndex = 18; // //txtFName // this.txtFName.Location = new System.Drawing.Point(76, 35); this.txtFName.Name = "txtFName"; this.txtFName.Size = new System.Drawing.Size(319, 20); this.txtFName.TabIndex = 17; // //lblLName // this.lblLName.AutoSize = true; this.lblLName.Location = new System.Drawing.Point(9, 60); this.lblLName.Name = "lblLName"; this.lblLName.Size = new System.Drawing.Size(61, 13); this.lblLName.TabIndex = 16; this.lblLName.Text = "Last Name:"; // //lblFName // this.lblFName.AutoSize = true; this.lblFName.Location = new System.Drawing.Point(7, 35); this.lblFName.Name = "lblFName"; this.lblFName.Size = new System.Drawing.Size(60, 13); this.lblFName.TabIndex = 15; this.lblFName.Text = "First Name:"; // //txtUserName // this.txtUserName.Location = new System.Drawing.Point(76, 11); this.txtUserName.Name = "txtUserName"; this.txtUserName.Size = new System.Drawing.Size(319, 20); this.txtUserName.TabIndex = 14; // //lblUserName // this.lblUserName.AutoSize = true; this.lblUserName.Location = new System.Drawing.Point(7, 14); this.lblUserName.Name = "lblUserName"; this.lblUserName.Size = new System.Drawing.Size(63, 13); this.lblUserName.TabIndex = 13; this.lblUserName.Text = "User Name:"; // //tvwPolicy // this.tvwPolicy.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwPolicy.Location = new System.Drawing.Point(0, 0); this.tvwPolicy.Name = "tvwPolicy"; this.tvwPolicy.Size = new System.Drawing.Size(661, 204); this.tvwPolicy.TabIndex = 0; // //SPApplicationBindingSource // this.SPApplicationBindingSource.DataMember = "SPApplication"; // //SPUserBindingSource // this.SPUserBindingSource.DataMember = "SPUser"; // //m_dsUserSecurity // this.m_dsUserSecurity.DataSetName = "dsUserSecurity"; this.m_dsUserSecurity.SchemaSerializationMode = System.Data.SchemaSerializationMode.IncludeSchema; // //TreeNodeImageList // this.TreeNodeImageList.ImageStream = (System.Windows.Forms.ImageListStreamer) (resources.GetObject("TreeNodeImageList.ImageStream")); this.TreeNodeImageList.TransparentColor = System.Drawing.Color.Transparent; this.TreeNodeImageList.Images.SetKeyName(0, "ApplicationNode"); this.TreeNodeImageList.Images.SetKeyName(1, "UserNode"); this.TreeNodeImageList.Images.SetKeyName(2, "RoleNode"); this.TreeNodeImageList.Images.SetKeyName(3, "RootNode"); this.TreeNodeImageList.Images.SetKeyName(4, "EditNode"); // //SecurityManager // this.AutoScaleDimensions = new System.Drawing.SizeF(6.0, 13.0); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(858, 449); this.Controls.Add(this.SplitContainer); this.Name = "SecurityManager"; this.Text = "SecurityManager"; ((System.ComponentModel.ISupportInitialize) this.ErrorNotify).EndInit(); this.SplitContainer.Panel1.ResumeLayout(false); this.SplitContainer.Panel2.ResumeLayout(false); this.SplitContainer.ResumeLayout(false); this.splSecurity.Panel1.ResumeLayout(false); this.splSecurity.Panel2.ResumeLayout(false); this.splSecurity.ResumeLayout(false); this.pnlApplication.ResumeLayout(false); this.pnlApplication.PerformLayout(); this.pnlRole.ResumeLayout(false); this.pnlRole.PerformLayout(); this.gbxRoleCreated.ResumeLayout(false); this.gbxRoleCreated.PerformLayout(); this.pnlUser.ResumeLayout(false); this.pnlUser.PerformLayout(); this.gbxUserCreated.ResumeLayout(false); this.gbxUserCreated.PerformLayout(); ((System.ComponentModel.ISupportInitialize) this.SPApplicationBindingSource).EndInit(); ((System.ComponentModel.ISupportInitialize) this.SPUserBindingSource).EndInit(); ((System.ComponentModel.ISupportInitialize) this.m_dsUserSecurity).EndInit(); this.ResumeLayout(false); } internal System.Windows.Forms.SplitContainer SplitContainer; internal System.Windows.Forms.TreeView tvwSecurity; internal System.Windows.Forms.SplitContainer splSecurity; internal System.Windows.Forms.Panel pnlApplication; internal System.Windows.Forms.Label lblNote; internal System.Windows.Forms.Label lblAppName; internal System.Windows.Forms.TextBox txtAppNote; internal System.Windows.Forms.TextBox txtAppName; internal System.Windows.Forms.Panel pnlRole; internal System.Windows.Forms.GroupBox gbxRoleCreated; internal System.Windows.Forms.Label Label7; internal System.Windows.Forms.Label Label8; internal System.Windows.Forms.Label Label9; internal System.Windows.Forms.Label Label10; internal System.Windows.Forms.TextBox txtRoleNote; internal System.Windows.Forms.Label lblRoleNote; internal System.Windows.Forms.TextBox txtRoleName; internal System.Windows.Forms.Label lblRoleName; internal System.Windows.Forms.Panel pnlUser; internal System.Windows.Forms.GroupBox gbxUserCreated; internal System.Windows.Forms.Label lblModifiedDate; internal System.Windows.Forms.Label lblUserCreateDate; internal System.Windows.Forms.Label lblUserModified; internal System.Windows.Forms.Label Label2; internal System.Windows.Forms.Label txtUserCreated; internal System.Windows.Forms.Label lblUserCreated; internal System.Windows.Forms.TextBox txtUserNote; internal System.Windows.Forms.Label lblUserNote; internal System.Windows.Forms.TextBox txtLName; internal System.Windows.Forms.TextBox txtFName; internal System.Windows.Forms.Label lblLName; internal System.Windows.Forms.Label lblFName; internal System.Windows.Forms.TextBox txtUserName; internal System.Windows.Forms.Label lblUserName; internal System.Windows.Forms.TreeView tvwPolicy; internal System.Windows.Forms.BindingSource SPApplicationBindingSource; internal System.Windows.Forms.BindingSource SPUserBindingSource; internal SoftLogik.Win.dsUserSecurity m_dsUserSecurity; internal System.Windows.Forms.ImageList TreeNodeImageList; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Text; using System.Runtime.CompilerServices; using umbraco.BusinessLogic; using Umbraco.Core; using umbraco.DataLayer; namespace umbraco.cms.businesslogic.task { /// <summary> /// An umbraco task is currently only used with the translation workflow in umbraco. But is extendable to cover other taskbased system as well. /// A task represent a simple job, it will always be assigned to a user, related to a node, and contain a comment about the task. /// The user attached to the task can complete the task, and the author of the task can reopen tasks that are not complete correct. /// /// Tasks can in umbraco be used for setting up simple workflows, and contains basic controls structures to determine if the task is completed or not. /// </summary> [Obsolete("Use Umbraco.Core.Service.ITaskService instead")] public class Task { internal Umbraco.Core.Models.Task TaskEntity; #region Properties /// <summary> /// Gets or sets the id. /// </summary> /// <value>The id.</value> public int Id { get { return TaskEntity.Id; } set { TaskEntity.Id = value; } } /// <summary> /// Gets or sets a value indicating whether this <see cref="Task"/> is closed. /// </summary> /// <value><c>true</c> if closed; otherwise, <c>false</c>.</value> public bool Closed { get { return TaskEntity.Closed; } set { TaskEntity.Closed = value; } } private CMSNode _node; /// <summary> /// Gets or sets the node. /// </summary> /// <value>The node.</value> public CMSNode Node { get { return _node ?? (_node = new CMSNode(TaskEntity.EntityId)); } set { _node = value; TaskEntity.EntityId = value.Id; } } private TaskType _type; /// <summary> /// Gets or sets the type. /// </summary> /// <value>The type.</value> public TaskType Type { get { return _type ?? (_type = new TaskType(TaskEntity.TaskType)); } set { _type = value; TaskEntity.TaskType = new Umbraco.Core.Models.TaskType(_type.Alias) { Id = _type.Id }; } } private User _parentUser; /// <summary> /// Gets or sets the parent user. /// </summary> /// <value>The parent user.</value> public User ParentUser { get { return _parentUser ?? (_parentUser = new User(TaskEntity.OwnerUserId)); } set { _parentUser = value; TaskEntity.OwnerUserId = _parentUser.Id; } } /// <summary> /// Gets or sets the comment. /// </summary> /// <value>The comment.</value> public string Comment { get { return TaskEntity.Comment; } set { TaskEntity.Comment = value; } } /// <summary> /// Gets or sets the date. /// </summary> /// <value>The date.</value> public DateTime Date { get { return TaskEntity.CreateDate; } set { TaskEntity.CreateDate = value; } } private User _user; /// <summary> /// Gets or sets the user. /// </summary> /// <value>The user.</value> public User User { get { return _user ?? (_user = new User(TaskEntity.AssigneeUserId)); } set { _user = value; TaskEntity.OwnerUserId = _user.Id; } } /// <summary> /// Gets the SQL helper. /// </summary> /// <value>The SQL helper.</value> protected static ISqlHelper SqlHelper { get { return Application.SqlHelper; } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Task"/> class. /// </summary> public Task() { } internal Task(Umbraco.Core.Models.Task task) { TaskEntity = task; } /// <summary> /// Initializes a new instance of the <see cref="Task"/> class. /// </summary> /// <param name="TaskId">The task id.</param> public Task(int TaskId) { TaskEntity = ApplicationContext.Current.Services.TaskService.GetTaskById(TaskId); if (TaskEntity == null) throw new NullReferenceException("No task found with id " + TaskId); } #endregion #region Public Methods /// <summary> /// Deletes the current task. /// Generally tasks should not be deleted and closed instead. /// </summary> public void Delete() { ApplicationContext.Current.Services.TaskService.Delete(TaskEntity); } /// <summary> /// Saves this instance. /// </summary> public void Save() { ApplicationContext.Current.Services.TaskService.Save(TaskEntity); } #endregion #region static methods /// <summary> /// Returns all tasks by type /// </summary> /// <param name="taskType"></param> /// <returns></returns> public static Tasks GetTasksByType(int taskType) { var foundTaskType = ApplicationContext.Current.Services.TaskService.GetTaskTypeById(taskType); if (foundTaskType == null) return null; var result = new Tasks(); var tasks = ApplicationContext.Current.Services.TaskService.GetTasks(taskTypeAlias: foundTaskType.Alias); foreach (var task in tasks) { result.Add(new Task(task)); } return result; } /// <summary> /// Get all tasks assigned to a node /// </summary> /// <param name="nodeId"></param> /// <returns></returns> public static Tasks GetTasks(int nodeId) { var result = new Tasks(); var tasks = ApplicationContext.Current.Services.TaskService.GetTasks(itemId:nodeId); foreach (var task in tasks) { result.Add(new Task(task)); } return result; } /// <summary> /// Retrieves a collection of open tasks assigned to the user /// </summary> /// <param name="User">The User who have the tasks assigned</param> /// <param name="IncludeClosed">If true both open and closed tasks will be returned</param> /// <returns>A collections of tasks</returns> public static Tasks GetTasks(User User, bool IncludeClosed) { var result = new Tasks(); var tasks = ApplicationContext.Current.Services.TaskService.GetTasks(assignedUser:User.Id, includeClosed:IncludeClosed); foreach (var task in tasks) { result.Add(new Task(task)); } return result; } /// <summary> /// Retrieves a collection of open tasks assigned to the user /// </summary> /// <param name="User">The User who have the tasks assigned</param> /// <param name="IncludeClosed">If true both open and closed tasks will be returned</param> /// <returns>A collections of tasks</returns> public static Tasks GetOwnedTasks(User User, bool IncludeClosed) { var result = new Tasks(); var tasks = ApplicationContext.Current.Services.TaskService.GetTasks(ownerUser:User.Id, includeClosed: IncludeClosed); foreach (var task in tasks) { result.Add(new Task(task)); } return result; } #endregion } }
using System; using System.Windows.Forms; using System.IO; using System.Text.RegularExpressions; using System.Diagnostics; namespace Thinktecture.Tools.Web.Services.ContractFirst { public partial class XsdCodeGenDialog : Form { #region Constructors public XsdCodeGenDialog(string[] xsdfiles) { InitializeComponent(); // Fill the file names text box. tbFileNames.Text = string.Join(";", xsdfiles); } #endregion #region Event handlers private void cbMultipleFiles_CheckedChanged(object sender, EventArgs e) { // Disable the target file name text box if multiple files options is on. tbTargetFileName.Enabled = !cbMultipleFiles.Checked; } private void XsdCodeGenDialog_Load(object sender, EventArgs e) { LoadFormValues(); } private void button1_Click(object sender, EventArgs e) { if (tbTargetFileName.Text.Trim() == "" || tbTargetFileName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) > -1) { MessageBox.Show("Please enter a valid name for the tatget file name", "Web Services Contract-First code generation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } if (tbNamespace.Text.Trim() == "" || !IsMatchingPattern(@"^(?:(?:((?![0-9_])[a-zA-Z0-9_]+)\.?)+)(?<!\.)$", tbNamespace.Text)) { MessageBox.Show("Please enter a valid name for the namespace", "Web Services Contract-First code generation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } DialogResult = DialogResult.OK; SaveFormValues(); Close(); } #endregion #region Properties public bool PublicProperties => cbProperties.Checked; public bool VirtualProperties => cbVirtualProperties.Checked; public bool Collections => cbCollections.Checked; public bool GenericLists => cbGenericList.Checked; public bool DataBinding => cbDataBinding.Checked; public bool OrderIdentifiers => cbOrderIds.Checked; public bool AdjustCasing => cbAdjustCasing.Checked; public bool OverwriteFiles => cbOverwrite.Checked; public bool GenerateMultipleFiles => cbMultipleFiles.Checked; public string Namespace { get => tbNamespace.Text; set => tbNamespace.Text = value; } public string TargetFileName { get => tbTargetFileName.Text; set => tbTargetFileName.Text = value; } #endregion bool IsMatchingPattern(string pattern, string value) { Regex regex = new Regex(pattern); Match match = regex.Match(value); return match.Success; } private void cbCollections_CheckedChanged(object sender, EventArgs e) { if (cbCollections.Checked && cbGenericList.Checked) cbGenericList.Checked = false; } private void cbGenericList_CheckedChanged(object sender, EventArgs e) { if (cbGenericList.Checked && cbCollections.Checked) cbCollections.Checked = false; } private void cbDataBinding_CheckedChanged(object sender, EventArgs e) { if (cbDataBinding.Checked) { cbProperties.Checked = true; cbProperties.Enabled = false; } else { if (!cbVirtualProperties.Checked) { cbProperties.Enabled = true; } } } private void cbVirtualProperties_CheckedChanged(object sender, EventArgs e) { if (cbVirtualProperties.Checked) { cbProperties.Checked = true; cbProperties.Enabled = false; } else { if (!cbDataBinding.Checked) { cbProperties.Enabled = true; } } } private void pbWscf_Click(object sender, EventArgs e) { Process.Start("http://www.thinktecture.com/"); } /// <summary> /// Saves the form values /// </summary> private void SaveFormValues() { ConfigurationManager config = ConfigurationManager.GetConfigurationManager("WSCF05"); if (cbSettings.Checked) { config.Write("xsdProperties", cbProperties.Checked.ToString()); config.Write("xsdVirtualProperties", cbVirtualProperties.Checked.ToString()); config.Write("xsdCollections", cbCollections.Checked.ToString()); config.Write("xsdGenericList", cbGenericList.Checked.ToString()); config.Write("xsdDataBinding", cbDataBinding.Checked.ToString()); config.Write("xsdOrderIdentifiers", cbOrderIds.Checked.ToString()); config.Write("xsdAdjustCasing", cbAdjustCasing.Checked.ToString()); config.Write("xsdMultipleFiles", cbMultipleFiles.Checked.ToString()); config.Write("xsdOverwrite", cbOverwrite.Checked.ToString()); config.Write("xsdRememberSettings", cbSettings.Checked.ToString()); config.Write("xsdDestinationNamespace", tbNamespace.Text); config.Write("xsdDestinationFilename", tbTargetFileName.Text); } else { config.Write("xsdRememberSettings", "false"); } config.Persist(); } /// <summary> /// Loads the values for the UI elements from the persisted storage. /// </summary> private void LoadFormValues() { ConfigurationManager config = ConfigurationManager.GetConfigurationManager("WSCF05"); if ((cbSettings.Checked = config.ReadBoolean("xsdRememberSettings"))) { cbProperties.Checked = config.ReadBoolean("xsdProperties"); cbVirtualProperties.Checked = config.ReadBoolean("xsdVirtualProperties"); cbCollections.Checked = config.ReadBoolean("xsdCollections"); cbGenericList.Checked = config.ReadBoolean("xsdGenericList"); cbDataBinding.Checked = config.ReadBoolean("xsdDataBinding"); cbOrderIds.Checked = config.ReadBoolean("xsdOrderIdentifiers"); cbAdjustCasing.Checked = config.ReadBoolean("xsdAdjustCasing"); cbMultipleFiles.Checked = config.ReadBoolean("xsdMultipleFiles"); cbOverwrite.Checked = config.ReadBoolean("xsdOverwrite"); tbNamespace.Text = config.Read("xsdDestinationNamespace"); tbTargetFileName.Text = config.Read("xsdDestinationFilename"); } } } }
using UnityEngine; using UnityEditor; using System.Collections.Generic; [CanEditMultipleObjects, CustomEditor(typeof(MegaWrap))] public class MegaWrapEditor : Editor { public override void OnInspectorGUI() { MegaWrap mod = (MegaWrap)target; #if !UNITY_5 && !UNITY_2017 EditorGUIUtility.LookLikeControls(); #endif mod.WrapEnabled = EditorGUILayout.Toggle("Enabled", mod.WrapEnabled); mod.target = (MegaModifyObject)EditorGUILayout.ObjectField("Target", mod.target, typeof(MegaModifyObject), true); float max = 1.0f; if ( mod.target ) max = mod.target.bbox.size.magnitude; mod.maxdist = EditorGUILayout.Slider("Max Dist", mod.maxdist, 0.0f, max); //2.0f); //mod.maxdist); if ( mod.maxdist < 0.0f ) mod.maxdist = 0.0f; mod.maxpoints = EditorGUILayout.IntField("Max Points", mod.maxpoints); //mod.maxdist); if ( mod.maxpoints < 1 ) mod.maxpoints = 1; Color col = GUI.backgroundColor; EditorGUILayout.BeginHorizontal(); if ( mod.bindverts == null ) { GUI.backgroundColor = Color.red; if ( GUILayout.Button("Map") ) Attach(mod.target); } else { GUI.backgroundColor = Color.green; if ( GUILayout.Button("ReMap") ) Attach(mod.target); } GUI.backgroundColor = col; if ( GUILayout.Button("Reset") ) mod.ResetMesh(); EditorGUILayout.EndHorizontal(); if ( GUI.changed ) EditorUtility.SetDirty(mod); mod.gap = EditorGUILayout.FloatField("Gap", mod.gap); mod.shrink = EditorGUILayout.Slider("Shrink", mod.shrink, 0.0f, 1.0f); mod.size = EditorGUILayout.Slider("Size", mod.size, 0.001f, 0.04f); if ( mod.bindverts != null ) mod.vertindex = EditorGUILayout.IntSlider("Vert Index", mod.vertindex, 0, mod.bindverts.Length - 1); mod.offset = EditorGUILayout.Vector3Field("Offset", mod.offset); mod.NormalMethod = (MegaNormalMethod)EditorGUILayout.EnumPopup("Normal Method", mod.NormalMethod); #if UNITY_5 || UNITY_2017 mod.UseBakedMesh = EditorGUILayout.Toggle("Use Baked Mesh", mod.UseBakedMesh); #endif if ( mod.bindverts == null || mod.target == null ) EditorGUILayout.LabelField("Object not wrapped"); else EditorGUILayout.LabelField("UnMapped", mod.nomapcount.ToString()); if ( GUI.changed ) EditorUtility.SetDirty(mod); } public void OnSceneGUI() { DisplayDebug(); } void DisplayDebug() { MegaWrap mod = (MegaWrap)target; if ( mod.target ) { if ( mod.bindverts != null && mod.bindverts.Length > 0 ) { if ( mod.targetIsSkin && !mod.sourceIsSkin ) { Color col = Color.black; Handles.matrix = Matrix4x4.identity; MegaBindVert bv = mod.bindverts[mod.vertindex]; for ( int i = 0; i < bv.verts.Count; i++ ) { MegaBindInf bi = bv.verts[i]; float w = bv.verts[i].weight / bv.weight; if ( w > 0.5f ) col = Color.Lerp(Color.green, Color.red, (w - 0.5f) * 2.0f); else col = Color.Lerp(Color.blue, Color.green, w * 2.0f); Handles.color = col; Vector3 p = (mod.skinnedVerts[bv.verts[i].i0] + mod.skinnedVerts[bv.verts[i].i1] + mod.skinnedVerts[bv.verts[i].i2]) / 3.0f; //tm.MultiplyPoint(mod.vr[i].cpos); MegaHandles.DotCap(i, p, Quaternion.identity, mod.size); //0.01f); Vector3 p0 = mod.skinnedVerts[bi.i0]; Vector3 p1 = mod.skinnedVerts[bi.i1]; Vector3 p2 = mod.skinnedVerts[bi.i2]; Vector3 cp = mod.GetCoordMine(p0, p1, p2, bi.bary); Handles.color = Color.gray; Handles.DrawLine(p, cp); Vector3 norm = mod.FaceNormal(p0, p1, p2); Vector3 cp1 = cp + (((bi.dist * mod.shrink) + mod.gap) * norm.normalized); Handles.color = Color.green; Handles.DrawLine(cp, cp1); } } else { Color col = Color.black; Matrix4x4 tm = mod.target.transform.localToWorldMatrix; Handles.matrix = tm; //Matrix4x4.identity; MegaBindVert bv = mod.bindverts[mod.vertindex]; for ( int i = 0; i < bv.verts.Count; i++ ) { MegaBindInf bi = bv.verts[i]; float w = bv.verts[i].weight / bv.weight; if ( w > 0.5f ) col = Color.Lerp(Color.green, Color.red, (w - 0.5f) * 2.0f); else col = Color.Lerp(Color.blue, Color.green, w * 2.0f); Handles.color = col; Vector3 p = (mod.target.sverts[bv.verts[i].i0] + mod.target.sverts[bv.verts[i].i1] + mod.target.sverts[bv.verts[i].i2]) / 3.0f; //tm.MultiplyPoint(mod.vr[i].cpos); MegaHandles.DotCap(i, p, Quaternion.identity, mod.size); //0.01f); Vector3 p0 = mod.target.sverts[bi.i0]; Vector3 p1 = mod.target.sverts[bi.i1]; Vector3 p2 = mod.target.sverts[bi.i2]; Vector3 cp = mod.GetCoordMine(p0, p1, p2, bi.bary); Handles.color = Color.gray; Handles.DrawLine(p, cp); Vector3 norm = mod.FaceNormal(p0, p1, p2); Vector3 cp1 = cp + (((bi.dist * mod.shrink) + mod.gap) * norm.normalized); Handles.color = Color.green; Handles.DrawLine(cp, cp1); } } // Show unmapped verts Handles.color = Color.yellow; for ( int i = 0; i < mod.bindverts.Length; i++ ) { if ( mod.bindverts[i].weight == 0.0f ) { Vector3 pv1 = mod.freeverts[i]; MegaHandles.DotCap(0, pv1, Quaternion.identity, mod.size); //0.01f); } } } if ( mod.verts != null && mod.verts.Length > mod.vertindex ) { Handles.color = Color.red; Handles.matrix = mod.transform.localToWorldMatrix; Vector3 pv = mod.verts[mod.vertindex]; MegaHandles.DotCap(0, pv, Quaternion.identity, mod.size); //0.01f); } } } void Attach(MegaModifyObject modobj) { MegaWrap mod = (MegaWrap)target; mod.targetIsSkin = false; mod.sourceIsSkin = false; if ( mod.mesh && mod.startverts != null ) mod.mesh.vertices = mod.startverts; if ( modobj == null ) { mod.bindverts = null; return; } mod.nomapcount = 0; if ( mod.mesh ) mod.mesh.vertices = mod.startverts; MeshFilter mf = mod.GetComponent<MeshFilter>(); Mesh srcmesh = null; if ( mf != null ) { //skinned = false; srcmesh = mf.sharedMesh; } else { SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)mod.GetComponent(typeof(SkinnedMeshRenderer)); if ( smesh != null ) { //skinned = true; srcmesh = smesh.sharedMesh; mod.sourceIsSkin = true; } } if ( srcmesh == null ) { Debug.LogWarning("No Mesh found on the target object, make sure target has a mesh and MegaFiers modifier attached!"); return; } if ( mod.mesh == null ) mod.mesh = mod.CloneMesh(srcmesh); //mf.mesh); if ( mf ) mf.mesh = mod.mesh; else { SkinnedMeshRenderer smesh = (SkinnedMeshRenderer)mod.GetComponent(typeof(SkinnedMeshRenderer)); smesh.sharedMesh = mod.mesh; } if ( mod.sourceIsSkin == false ) { SkinnedMeshRenderer tmesh = (SkinnedMeshRenderer)modobj.GetComponent(typeof(SkinnedMeshRenderer)); if ( tmesh != null ) { mod.targetIsSkin = true; if ( !mod.sourceIsSkin ) { Mesh sm = tmesh.sharedMesh; mod.bindposes = sm.bindposes; mod.boneweights = sm.boneWeights; mod.bones = tmesh.bones; mod.skinnedVerts = sm.vertices; //new Vector3[sm.vertexCount]; } } } if ( mod.targetIsSkin ) { if ( mod.boneweights == null || mod.boneweights.Length == 0 ) mod.targetIsSkin = false; } mod.neededVerts.Clear(); mod.verts = mod.mesh.vertices; mod.startverts = mod.mesh.vertices; mod.freeverts = new Vector3[mod.startverts.Length]; Vector3[] baseverts = modobj.verts; //basemesh.vertices; int[] basefaces = modobj.tris; //basemesh.triangles; mod.bindverts = new MegaBindVert[mod.verts.Length]; // matrix to get vertex into local space of target Matrix4x4 tm = mod.transform.localToWorldMatrix * modobj.transform.worldToLocalMatrix; List<MegaCloseFace> closefaces = new List<MegaCloseFace>(); Vector3 p0 = Vector3.zero; Vector3 p1 = Vector3.zero; Vector3 p2 = Vector3.zero; Vector3[] tverts = new Vector3[mod.target.sverts.Length]; int tcount = 10; for ( int i = 0; i < tverts.Length; i++ ) { tcount--; if ( tcount < 0 ) { tcount = 10; EditorUtility.DisplayProgressBar("Calc vertex positions", "Vertex " + i + " of " + tverts.Length, (float)i / (float)tverts.Length); } if ( mod.targetIsSkin && !mod.sourceIsSkin ) tverts[i] = modobj.transform.InverseTransformPoint(mod.GetSkinPos(i)); else tverts[i] = baseverts[i]; } EditorUtility.ClearProgressBar(); for ( int i = 0; i < mod.verts.Length; i++ ) { if ( EditorUtility.DisplayCancelableProgressBar("Wrap Mapping", "Mapping Vertex " + i + " of " + mod.verts.Length, (float)i / (float)mod.verts.Length) ) { mod.bindverts = null; break; } MegaBindVert bv = new MegaBindVert(); mod.bindverts[i] = bv; Vector3 p = tm.MultiplyPoint(mod.verts[i]); p = mod.transform.TransformPoint(mod.verts[i]); p = modobj.transform.InverseTransformPoint(p); mod.freeverts[i] = p; closefaces.Clear(); for ( int t = 0; t < basefaces.Length; t += 3 ) { p0 = tverts[basefaces[t]]; p1 = tverts[basefaces[t + 1]]; p2 = tverts[basefaces[t + 2]]; //if ( mod.targetIsSkin && !mod.sourceIsSkin ) //{ //p0 = modobj.transform.InverseTransformPoint(mod.GetSkinPos(basefaces[t])); //p1 = modobj.transform.InverseTransformPoint(mod.GetSkinPos(basefaces[t + 1])); //p2 = modobj.transform.InverseTransformPoint(mod.GetSkinPos(basefaces[t + 2])); //} //else //{ //p0 = baseverts[basefaces[t]]; // p1 = baseverts[basefaces[t + 1]]; //p2 = baseverts[basefaces[t + 2]]; //} float dist = mod.GetDistance(p, p0, p1, p2); if ( Mathf.Abs(dist) < mod.maxdist ) { MegaCloseFace cf = new MegaCloseFace(); cf.dist = Mathf.Abs(dist); cf.face = t; bool inserted = false; for ( int k = 0; k < closefaces.Count; k++ ) { if ( cf.dist < closefaces[k].dist ) { closefaces.Insert(k, cf); inserted = true; break; } } if ( !inserted ) closefaces.Add(cf); } } float tweight = 0.0f; int maxp = mod.maxpoints; if ( maxp == 0 ) maxp = closefaces.Count; for ( int j = 0; j < maxp; j++ ) { if ( j < closefaces.Count ) { int t = closefaces[j].face; p0 = tverts[basefaces[t]]; p1 = tverts[basefaces[t + 1]]; p2 = tverts[basefaces[t + 2]]; //if ( mod.targetIsSkin && !mod.sourceIsSkin ) //{ //p0 = modobj.transform.InverseTransformPoint(mod.GetSkinPos(basefaces[t])); //p1 = modobj.transform.InverseTransformPoint(mod.GetSkinPos(basefaces[t + 1])); //p2 = modobj.transform.InverseTransformPoint(mod.GetSkinPos(basefaces[t + 2])); //} //else //{ //p0 = baseverts[basefaces[t]]; //p1 = baseverts[basefaces[t + 1]]; //p2 = baseverts[basefaces[t + 2]]; //} Vector3 normal = mod.FaceNormal(p0, p1, p2); float dist = closefaces[j].dist; //GetDistance(p, p0, p1, p2); MegaBindInf bi = new MegaBindInf(); bi.dist = mod.GetPlaneDistance(p, p0, p1, p2); //dist; bi.face = t; bi.i0 = basefaces[t]; bi.i1 = basefaces[t + 1]; bi.i2 = basefaces[t + 2]; bi.bary = mod.CalcBary(p, p0, p1, p2); bi.weight = 1.0f / (1.0f + dist); bi.area = normal.magnitude * 0.5f; //CalcArea(baseverts[basefaces[t]], baseverts[basefaces[t + 1]], baseverts[basefaces[t + 2]]); // Could calc once at start tweight += bi.weight; bv.verts.Add(bi); } } if ( mod.maxpoints > 0 && mod.maxpoints < bv.verts.Count ) bv.verts.RemoveRange(mod.maxpoints, bv.verts.Count - mod.maxpoints); // Only want to calculate skin vertices we use if ( !mod.sourceIsSkin && mod.targetIsSkin ) { for ( int fi = 0; fi < bv.verts.Count; fi++ ) { if ( !mod.neededVerts.Contains(bv.verts[fi].i0) ) mod.neededVerts.Add(bv.verts[fi].i0); if ( !mod.neededVerts.Contains(bv.verts[fi].i1) ) mod.neededVerts.Add(bv.verts[fi].i1); if ( !mod.neededVerts.Contains(bv.verts[fi].i2) ) mod.neededVerts.Add(bv.verts[fi].i2); } } if ( tweight == 0.0f ) { mod.nomapcount++; break; } bv.weight = tweight; } EditorUtility.ClearProgressBar(); } }
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using YamlDotNet.Core.Tokens; using MappingStyle = YamlDotNet.Core.Events.MappingStyle; using ParsingEvent = YamlDotNet.Core.Events.ParsingEvent; using SequenceStyle = YamlDotNet.Core.Events.SequenceStyle; namespace YamlDotNet.Core { /// <summary> /// Parses YAML streams. /// </summary> public class Parser : IParser { private readonly Stack<ParserState> states = new Stack<ParserState>(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private ParserState state; private readonly IScanner scanner; private ParsingEvent current; private Token currentToken; private Token GetCurrentToken() { if (currentToken == null) { while (scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; var commentToken = currentToken as Comment; if (commentToken != null) { pendingEvents.Enqueue(new Events.Comment(commentToken.Value, commentToken.IsInline, commentToken.Start, commentToken.End)); } else { break; } } } return currentToken; } /// <summary> /// Initializes a new instance of the <see cref="Parser"/> class. /// </summary> /// <param name="input">The input where the YAML stream is to be read.</param> public Parser(TextReader input) : this(new Scanner(input)) { } /// <summary> /// Initializes a new instance of the <see cref="Parser"/> class. /// </summary> public Parser(IScanner scanner) { this.scanner = scanner; } /// <summary> /// Gets the current event. /// </summary> public ParsingEvent Current { get { return current; } } private readonly Queue<Events.ParsingEvent> pendingEvents = new Queue<Events.ParsingEvent>(); /// <summary> /// Moves to the next event. /// </summary> /// <returns>Returns true if there are more events available, otherwise returns false.</returns> public bool MoveNext() { // No events after the end of the stream or error. if (state == ParserState.StreamEnd) { current = null; return false; } else if (pendingEvents.Count == 0) { // Generate the next event. pendingEvents.Enqueue(StateMachine()); } current = pendingEvents.Dequeue(); return true; } private ParsingEvent StateMachine() { switch (state) { case ParserState.StreamStart: return ParseStreamStart(); case ParserState.ImplicitDocumentStart: return ParseDocumentStart(true); case ParserState.DocumentStart: return ParseDocumentStart(false); case ParserState.DocumentContent: return ParseDocumentContent(); case ParserState.DocumentEnd: return ParseDocumentEnd(); case ParserState.BlockNode: return ParseNode(true, false); case ParserState.BlockNodeOrIndentlessSequence: return ParseNode(true, true); case ParserState.FlowNode: return ParseNode(false, false); case ParserState.BlockSequenceFirstEntry: return ParseBlockSequenceEntry(true); case ParserState.BlockSequenceEntry: return ParseBlockSequenceEntry(false); case ParserState.IndentlessSequenceEntry: return ParseIndentlessSequenceEntry(); case ParserState.BlockMappingFirstKey: return ParseBlockMappingKey(true); case ParserState.BlockMappingKey: return ParseBlockMappingKey(false); case ParserState.BlockMappingValue: return ParseBlockMappingValue(); case ParserState.FlowSequenceFirstEntry: return ParseFlowSequenceEntry(true); case ParserState.FlowSequenceEntry: return ParseFlowSequenceEntry(false); case ParserState.FlowSequenceEntryMappingKey: return ParseFlowSequenceEntryMappingKey(); case ParserState.FlowSequenceEntryMappingValue: return ParseFlowSequenceEntryMappingValue(); case ParserState.FlowSequenceEntryMappingEnd: return ParseFlowSequenceEntryMappingEnd(); case ParserState.FlowMappingFirstKey: return ParseFlowMappingKey(true); case ParserState.FlowMappingKey: return ParseFlowMappingKey(false); case ParserState.FlowMappingValue: return ParseFlowMappingValue(false); case ParserState.FlowMappingEmptyValue: return ParseFlowMappingValue(true); default: Debug.Assert(false, "Invalid state"); // Invalid state. throw new InvalidOperationException(); } } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } /// <summary> /// Parse the production: /// stream ::= STREAM-START implicit_document? explicit_document* STREAM-END /// ************ /// </summary> private ParsingEvent ParseStreamStart() { StreamStart streamStart = GetCurrentToken() as StreamStart; if (streamStart == null) { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "Did not find expected <stream-start>."); } Skip(); state = ParserState.ImplicitDocumentStart; return new Events.StreamStart(streamStart.Start, streamStart.End); } /// <summary> /// Parse the productions: /// implicit_document ::= block_node DOCUMENT-END* /// * /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// ************************* /// </summary> private ParsingEvent ParseDocumentStart(bool isImplicit) { // Parse extra document end indicators. if (!isImplicit) { while (GetCurrentToken() is DocumentEnd) { Skip(); } } // Parse an isImplicit document. if (isImplicit && !(GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is StreamEnd)) { TagDirectiveCollection directives = new TagDirectiveCollection(); ProcessDirectives(directives); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new Events.DocumentStart(null, directives, true, GetCurrentToken().Start, GetCurrentToken().End); } // Parse an explicit document. else if (!(GetCurrentToken() is StreamEnd)) { Mark start = GetCurrentToken().Start; TagDirectiveCollection directives = new TagDirectiveCollection(); VersionDirective versionDirective = ProcessDirectives(directives); var current = GetCurrentToken(); if (!(current is DocumentStart)) { throw new SemanticErrorException(current.Start, current.End, "Did not find expected <document start>."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; ParsingEvent evt = new Events.DocumentStart(versionDirective, directives, false, start, current.End); Skip(); return evt; } // Parse the stream end. else { state = ParserState.StreamEnd; ParsingEvent evt = new Events.StreamEnd(GetCurrentToken().Start, GetCurrentToken().End); // Do not call skip here because that would throw an exception if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return evt; } } /// <summary> /// Parse directives. /// </summary> private VersionDirective ProcessDirectives(TagDirectiveCollection tags) { VersionDirective version = null; bool hasOwnDirectives = false; while (true) { VersionDirective currentVersion; TagDirective tag; if ((currentVersion = GetCurrentToken() as VersionDirective) != null) { if (version != null) { throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found duplicate %YAML directive."); } if (currentVersion.Version.Major != Constants.MajorVersion || currentVersion.Version.Minor != Constants.MinorVersion) { throw new SemanticErrorException(currentVersion.Start, currentVersion.End, "Found incompatible YAML document."); } version = currentVersion; hasOwnDirectives = true; } else if ((tag = GetCurrentToken() as TagDirective) != null) { if (tags.Contains(tag.Handle)) { throw new SemanticErrorException(tag.Start, tag.End, "Found duplicate %TAG directive."); } tags.Add(tag); hasOwnDirectives = true; } else { break; } Skip(); } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (hasOwnDirectives) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return version; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable<TagDirective> source) { foreach (var directive in source) { if (!directives.Contains(directive)) { directives.Add(directive); } } } /// <summary> /// Parse the productions: /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// *********** /// </summary> private ParsingEvent ParseDocumentContent() { if ( GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is DocumentStart || GetCurrentToken() is DocumentEnd || GetCurrentToken() is StreamEnd ) { state = states.Pop(); return ProcessEmptyScalar(scanner.CurrentPosition); } else { return ParseNode(true, false); } } /// <summary> /// Generate an empty scalar event. /// </summary> private static ParsingEvent ProcessEmptyScalar(Mark position) { return new Events.Scalar(null, null, string.Empty, ScalarStyle.Plain, true, false, position, position); } /// <summary> /// Parse the productions: /// block_node_or_indentless_sequence ::= /// ALIAS /// ***** /// | properties (block_content | indentless_block_sequence)? /// ********** * /// | block_content | indentless_block_sequence /// * /// block_node ::= ALIAS /// ***** /// | properties block_content? /// ********** * /// | block_content /// * /// flow_node ::= ALIAS /// ***** /// | properties flow_content? /// ********** * /// | flow_content /// * /// properties ::= TAG ANCHOR? | ANCHOR TAG? /// ************************* /// block_content ::= block_collection | flow_collection | SCALAR /// ****** /// flow_content ::= flow_collection | SCALAR /// ****** /// </summary> private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { AnchorAlias alias = GetCurrentToken() as AnchorAlias; if (alias != null) { state = states.Pop(); ParsingEvent evt = new Events.AnchorAlias(alias.Value, alias.Start, alias.End); Skip(); return evt; } Mark start = GetCurrentToken().Start; Anchor anchor = null; Tag tag = null; // The anchor and the tag can be in any order. This loop repeats at most twice. while (true) { if (anchor == null && (anchor = GetCurrentToken() as Anchor) != null) { Skip(); } else if (tag == null && (tag = GetCurrentToken() as Tag) != null) { Skip(); } else { break; } } string tagName = null; if (tag != null) { if (string.IsNullOrEmpty(tag.Handle)) { tagName = tag.Suffix; } else if (tagDirectives.Contains(tag.Handle)) { tagName = string.Concat(tagDirectives[tag.Handle].Prefix, tag.Suffix); } else { throw new SemanticErrorException(tag.Start, tag.End, "While parsing a node, find undefined tag handle."); } } if (string.IsNullOrEmpty(tagName)) { tagName = null; } string anchorName = anchor != null ? string.IsNullOrEmpty(anchor.Value) ? null : anchor.Value : null; bool isImplicit = string.IsNullOrEmpty(tagName); if (isIndentlessSequence && GetCurrentToken() is BlockEntry) { state = ParserState.IndentlessSequenceEntry; return new Events.SequenceStart( anchorName, tagName, isImplicit, SequenceStyle.Block, start, GetCurrentToken().End ); } else { Scalar scalar = GetCurrentToken() as Scalar; if (scalar != null) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tagName == null) || tagName == Constants.DefaultHandle) { isPlainImplicit = true; } else if (tagName == null) { isQuotedImplicit = true; } state = states.Pop(); ParsingEvent evt = new Events.Scalar(anchorName, tagName, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start, scalar.End); Skip(); return evt; } FlowSequenceStart flowSequenceStart = GetCurrentToken() as FlowSequenceStart; if (flowSequenceStart != null) { state = ParserState.FlowSequenceFirstEntry; return new Events.SequenceStart(anchorName, tagName, isImplicit, SequenceStyle.Flow, start, flowSequenceStart.End); } FlowMappingStart flowMappingStart = GetCurrentToken() as FlowMappingStart; if (flowMappingStart != null) { state = ParserState.FlowMappingFirstKey; return new Events.MappingStart(anchorName, tagName, isImplicit, MappingStyle.Flow, start, flowMappingStart.End); } if (isBlock) { BlockSequenceStart blockSequenceStart = GetCurrentToken() as BlockSequenceStart; if (blockSequenceStart != null) { state = ParserState.BlockSequenceFirstEntry; return new Events.SequenceStart(anchorName, tagName, isImplicit, SequenceStyle.Block, start, blockSequenceStart.End); } BlockMappingStart blockMappingStart = GetCurrentToken() as BlockMappingStart; if (blockMappingStart != null) { state = ParserState.BlockMappingFirstKey; return new Events.MappingStart(anchorName, tagName, isImplicit, MappingStyle.Block, start, GetCurrentToken().End); } } if (anchorName != null || tag != null) { state = states.Pop(); return new Events.Scalar(anchorName, tagName, string.Empty, ScalarStyle.Plain, isImplicit, false, start, GetCurrentToken().End); } var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a node, did not find expected node content."); } } /// <summary> /// Parse the productions: /// implicit_document ::= block_node DOCUMENT-END* /// ************* /// explicit_document ::= DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// ************* /// </summary> private ParsingEvent ParseDocumentEnd() { bool isImplicit = true; Mark start = GetCurrentToken().Start; Mark end = start; if (GetCurrentToken() is DocumentEnd) { end = GetCurrentToken().End; Skip(); isImplicit = false; } state = ParserState.DocumentStart; return new Events.DocumentEnd(isImplicit, start, end); } /// <summary> /// Parse the productions: /// block_sequence ::= BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END /// ******************** *********** * ********* /// </summary> private ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } if (GetCurrentToken() is BlockEntry) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.BlockSequenceEntry); return ParseNode(true, false); } else { state = ParserState.BlockSequenceEntry; return ProcessEmptyScalar(mark); } } else if (GetCurrentToken() is BlockEnd) { state = states.Pop(); ParsingEvent evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a block collection, did not find expected '-' indicator."); } } /// <summary> /// Parse the productions: /// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ /// *********** * /// </summary> private ParsingEvent ParseIndentlessSequenceEntry() { if (GetCurrentToken() is BlockEntry) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is BlockEntry || GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.IndentlessSequenceEntry); return ParseNode(true, false); } else { state = ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(mark); } } else { state = states.Pop(); return new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); } } /// <summary> /// Parse the productions: /// block_mapping ::= BLOCK-MAPPING_START /// ******************* /// ((KEY block_node_or_indentless_sequence?)? /// *** * /// (VALUE block_node_or_indentless_sequence?)?)* /// /// BLOCK-END /// ********* /// </summary> private ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } if (GetCurrentToken() is Key) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.BlockMappingValue); return ParseNode(true, true); } else { state = ParserState.BlockMappingValue; return ProcessEmptyScalar(mark); } } else if (GetCurrentToken() is BlockEnd) { state = states.Pop(); ParsingEvent evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a block mapping, did not find expected key."); } } /// <summary> /// Parse the productions: /// block_mapping ::= BLOCK-MAPPING_START /// /// ((KEY block_node_or_indentless_sequence?)? /// /// (VALUE block_node_or_indentless_sequence?)?)* /// ***** * /// BLOCK-END /// /// </summary> private ParsingEvent ParseBlockMappingValue() { if (GetCurrentToken() is Value) { Mark mark = GetCurrentToken().End; Skip(); if (!(GetCurrentToken() is Key || GetCurrentToken() is Value || GetCurrentToken() is BlockEnd)) { states.Push(ParserState.BlockMappingKey); return ParseNode(true, true); } else { state = ParserState.BlockMappingKey; return ProcessEmptyScalar(mark); } } else { state = ParserState.BlockMappingKey; return ProcessEmptyScalar(GetCurrentToken().Start); } } /// <summary> /// Parse the productions: /// flow_sequence ::= FLOW-SEQUENCE-START /// ******************* /// (flow_sequence_entry FLOW-ENTRY)* /// * ********** /// flow_sequence_entry? /// * /// FLOW-SEQUENCE-END /// ***************** /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * /// </summary> private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } ParsingEvent evt; if (!(GetCurrentToken() is FlowSequenceEnd)) { if (!isFirst) { if (GetCurrentToken() is FlowEntry) { Skip(); } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a flow sequence, did not find expected ',' or ']'."); } } if (GetCurrentToken() is Key) { state = ParserState.FlowSequenceEntryMappingKey; evt = new Events.MappingStart(null, null, true, MappingStyle.Flow); Skip(); return evt; } else if (!(GetCurrentToken() is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(false, false); } } state = states.Pop(); evt = new Events.SequenceEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } /// <summary> /// Parse the productions: /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// *** * /// </summary> private ParsingEvent ParseFlowSequenceEntryMappingKey() { if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(false, false); } else { Mark mark = GetCurrentToken().End; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(mark); } } /// <summary> /// Parse the productions: /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// ***** * /// </summary> private ParsingEvent ParseFlowSequenceEntryMappingValue() { if (GetCurrentToken() is Value) { Skip(); if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(false, false); } } state = ParserState.FlowSequenceEntryMappingEnd; return ProcessEmptyScalar(GetCurrentToken().Start); } /// <summary> /// Parse the productions: /// flow_sequence_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * /// </summary> private ParsingEvent ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; return new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); } /// <summary> /// Parse the productions: /// flow_mapping ::= FLOW-MAPPING-START /// ****************** /// (flow_mapping_entry FLOW-ENTRY)* /// * ********** /// flow_mapping_entry? /// ****************** /// FLOW-MAPPING-END /// **************** /// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * *** * /// </summary> private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } if (!(GetCurrentToken() is FlowMappingEnd)) { if (!isFirst) { if (GetCurrentToken() is FlowEntry) { Skip(); } else { var current = GetCurrentToken(); throw new SemanticErrorException(current.Start, current.End, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (GetCurrentToken() is Key) { Skip(); if (!(GetCurrentToken() is Value || GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd)) { states.Push(ParserState.FlowMappingValue); return ParseNode(false, false); } else { state = ParserState.FlowMappingValue; return ProcessEmptyScalar(GetCurrentToken().Start); } } else if (!(GetCurrentToken() is FlowMappingEnd)) { states.Push(ParserState.FlowMappingEmptyValue); return ParseNode(false, false); } } state = states.Pop(); ParsingEvent evt = new Events.MappingEnd(GetCurrentToken().Start, GetCurrentToken().End); Skip(); return evt; } /// <summary> /// Parse the productions: /// flow_mapping_entry ::= flow_node | KEY flow_node? (VALUE flow_node?)? /// * ***** * /// </summary> private ParsingEvent ParseFlowMappingValue(bool isEmpty) { if (isEmpty) { state = ParserState.FlowMappingKey; return ProcessEmptyScalar(GetCurrentToken().Start); } if (GetCurrentToken() is Value) { Skip(); if (!(GetCurrentToken() is FlowEntry || GetCurrentToken() is FlowMappingEnd)) { states.Push(ParserState.FlowMappingKey); return ParseNode(false, false); } } state = ParserState.FlowMappingKey; return ProcessEmptyScalar(GetCurrentToken().Start); } } }
//! \file ImagePMS.cs //! \date 2017 Nov 26 //! \brief AliceSoft image format. // // Copyright (C) 2017 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using System.ComponentModel.Composition; using System.IO; using System.Windows; using System.Windows.Media; using System.Windows.Media.Imaging; using GameRes.Utility; namespace GameRes.Formats.AliceSoft { internal class PmsMetaData : ImageMetaData { public uint DataOffset; public uint AlphaOffset; } [Export(typeof(ImageFormat))] public class PmsFormat : ImageFormat { public override string Tag { get { return "PMS"; } } public override string Description { get { return "AliceSoft image format"; } } public override uint Signature { get { return 0x014D50; } } // 'PM' public PmsFormat () { Signatures = new uint[] { 0x014D50, 0x024D50 }; } public override ImageMetaData ReadMetaData (IBinaryStream file) { var header = file.ReadHeader (0x30); var info = new PmsMetaData { BPP = header[6], OffsetX = header.ToInt32 (0x10), OffsetY = header.ToInt32 (0x14), Width = header.ToUInt32 (0x18), Height = header.ToUInt32 (0x1C), DataOffset = header.ToUInt32 (0x20), AlphaOffset = header.ToUInt32 (0x24), }; if ((info.BPP != 16 && info.BPP != 8) || info.DataOffset < 0x30 || info.DataOffset >= file.Length) return null; return info; } public override ImageData Read (IBinaryStream file, ImageMetaData info) { var pms = new PmsReader (file, (PmsMetaData)info); var bitmap = pms.Unpack(); bitmap.Freeze(); return new ImageData (bitmap, info); } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("PmsFormat.Write not implemented"); } } internal class PmsReader { IBinaryStream m_input; PmsMetaData m_info; int m_width; int m_height; public PmsReader (IBinaryStream input, PmsMetaData info) { m_input = input; m_info = info; m_width = (int)m_info.Width; m_height = (int)m_info.Height; } public BitmapSource Unpack () { switch (m_info.BPP) { case 16: return UnpackRgb(); case 8: return UnpackIndexed(); default: throw new InvalidFormatException(); } } BitmapSource UnpackIndexed () { m_input.Position = m_info.AlphaOffset; var palette = ImageFormat.ReadPalette (m_input.AsStream, 0x100, PaletteFormat.Rgb); m_input.Position = m_info.DataOffset; var pixels = Unpack8bpp(); return BitmapSource.Create (m_width, m_height, ImageData.DefaultDpiX, ImageData.DefaultDpiY, PixelFormats.Indexed8, palette, pixels, m_width); } BitmapSource UnpackRgb () { m_input.Position = m_info.DataOffset; var pixels = Unpack16bpp(); var source = BitmapSource.Create (m_width, m_height, ImageData.DefaultDpiX, ImageData.DefaultDpiY, PixelFormats.Bgr565, null, pixels, m_width*2); if (0 == m_info.AlphaOffset) return source; m_input.Position = m_info.AlphaOffset; var alpha = Unpack8bpp(); source = new FormatConvertedBitmap (source, PixelFormats.Bgra32, null, 0); var output = new WriteableBitmap (source); output.Lock(); unsafe { byte* buffer = (byte*)output.BackBuffer; int stride = output.BackBufferStride; int asrc = 0; for (int y = 0; y < m_height; ++y) { for (int x = 3; x < stride; x += 4) { buffer[x] = alpha[asrc++]; } buffer += stride; } } output.AddDirtyRect (new Int32Rect (0, 0, m_width, m_height)); output.Unlock(); return output; } ushort[] Unpack16bpp () { var output = new ushort[m_width * m_height]; int stride = m_width; for (int y = 0; y < m_height; ++y) for (int x = 0; x < m_width; ) { int dst = y * stride + x; int count = 1; byte ctl = m_input.ReadUInt8(); if (ctl < 0xF8) { byte px = m_input.ReadUInt8(); output[dst] = (ushort)(ctl | (px << 8)); } else if (ctl == 0xF8) { output[dst] = m_input.ReadUInt16(); } else if (ctl == 0xF9) { count = m_input.ReadUInt8() + 1; int p0 = m_input.ReadUInt8(); int p1 = m_input.ReadUInt8(); p0 = ((p0 & 0xE0) << 8) | ((p0 & 0x18) << 6) | ((p0 & 7) << 2); p1 = ((p1 & 0xC0) << 5) | ((p1 & 0x3C) << 3) | (p1 & 3); output[dst] = (ushort)(p0 | p1); for (int i = 1; i < count; i++) { p1 = m_input.ReadUInt8(); p1 = ((p1 & 0xC0) << 5) | ((p1 & 0x3C) << 3) | (p1 & 3); output[dst + i] = (ushort)(p0 | p1); } } else if (ctl == 0xFA) { output[dst] = output[dst - stride + 1]; } else if (ctl == 0xFB) { output[dst] = output[dst - stride - 1]; } else if (ctl == 0xFC) { count = (m_input.ReadUInt8() + 2) * 2; ushort px0 = m_input.ReadUInt16(); ushort px1 = m_input.ReadUInt16(); for (int i = 0; i < count; i += 2) { output[dst + i ] = px0; output[dst + i + 1] = px1; } } else if (ctl == 0xFD) { count = m_input.ReadUInt8() + 3; ushort px = m_input.ReadUInt16(); for (int i = 0; i < count; i++) { output[dst + i] = px; } } else if (ctl == 0xFE) { count = m_input.ReadUInt8() + 2; int src = dst - stride * 2; for (int i = 0; i < count; ++i) { output[dst+i] = output[src+i]; } } else // ctl == 0xFF { count = m_input.ReadUInt8() + 2; int src = dst - stride; for (int i = 0; i < count; ++i) { output[dst+i] = output[src+i]; } } x += count; } return output; } byte[] Unpack8bpp () { var output = new byte[m_width * m_height]; int stride = m_width; for (int y = 0; y < m_height; y++) for (int x = 0; x < m_width; ) { int dst = y * stride + x; int count = 1; byte ctl = m_input.ReadUInt8(); if (ctl < 0xF8) { output[dst] = ctl; } else if (ctl == 0xFF) { count = m_input.ReadUInt8() + 3; Binary.CopyOverlapped (output, dst - stride, dst, count); } else if (ctl == 0xFE) { count = m_input.ReadUInt8() + 3; Binary.CopyOverlapped (output, dst - stride * 2, dst, count); } else if (ctl == 0xFD) { count = m_input.ReadUInt8() + 4; byte px = m_input.ReadUInt8(); for (int i = 0; i < count; ++i) { output[dst + i] = px; } } else if (ctl == 0xFC) { count = (m_input.ReadUInt8() + 3) * 2; byte px0 = m_input.ReadUInt8(); byte px1 = m_input.ReadUInt8(); for (int i = 0; i < count; i += 2) { output[dst + i ] = px0; output[dst + i + 1] = px1; } } else // >= 0xF8 < 0xFC { output[dst] = m_input.ReadUInt8(); } x += count; } return output; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Text; using System.Windows.Forms; using DevExpress.XtraEditors; using System.IO; using Be.Windows.Forms; using Trionic5Tools; namespace Trionic5Controls { public partial class HexViewer : DevExpress.XtraEditors.XtraUserControl { public delegate void ViewerClose(object sender, EventArgs e); public event HexViewer.ViewerClose onClose; public delegate void SelectionChanged(object sender, SelectionChangedEventArgs e); public event HexViewer.SelectionChanged onSelectionChanged; private string _fileName = string.Empty; private string _lastFilename = string.Empty; public string LastFilename { get { return _lastFilename; } set { _lastFilename = value; } } private int m_currentfile_size = 0x40000; public string FileName { get { return _fileName; } set { _fileName = value; } } FormFind _formFind = new FormFind(); FormFindCancel _formFindCancel; FormGoTo _formGoto = new FormGoTo(); byte[] _findBuffer = new byte[0]; SymbolCollection m_symbolcollection= new SymbolCollection(); private bool m_issramviewer = false; public bool Issramviewer { get { return m_issramviewer; } set { m_issramviewer = value; } } public HexViewer() { InitializeComponent(); } public void SelectText(string symbolname, int fileoffset, int length) { /* richTextBox1.SelectionStart = fileoffset; richTextBox1.SelectionLength = length; richTextBox1.ScrollToCaret();*/ hexBox1.SelectionStart = fileoffset; hexBox1.SelectionLength = length; hexBox1.ScrollByteIntoView(fileoffset + length + 64); // scroll 4 lines extra for viewing purposes toolStripButton1.Text = symbolname; } public DialogResult CloseFile() { if (hexBox1.ByteProvider == null) return DialogResult.OK; try { if (hexBox1.ByteProvider != null && hexBox1.ByteProvider.HasChanges()) { DialogResult res = MessageBox.Show("Do you want to save changes?", "T5Suite 2.0", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning); if (res == DialogResult.Yes) { SaveFile(); CleanUp(); } else if (res == DialogResult.No) { CleanUp(); } else if (res == DialogResult.Cancel) { return res; } return res; } else { CleanUp(); return DialogResult.OK; } } finally { ManageAbility(); } } /// <summary> /// Saves the current file. /// </summary> void SaveFile() { if (hexBox1.ByteProvider == null) return; try { if (File.Exists(_fileName)) { File.Copy(_fileName, _fileName + "-backup" + DateTime.Now.Ticks.ToString()); FileByteProvider fileByteProvider = hexBox1.ByteProvider as FileByteProvider; DynamicByteProvider dynamicByteProvider = hexBox1.ByteProvider as DynamicByteProvider; DynamicFileByteProvider dynamicFileByteProvider = hexBox1.ByteProvider as DynamicFileByteProvider; if (fileByteProvider != null) { fileByteProvider.ApplyChanges(); } else if (dynamicFileByteProvider != null) { dynamicFileByteProvider.ApplyChanges(); } else if (dynamicByteProvider != null) { byte[] data = dynamicByteProvider.Bytes.ToArray(); using (FileStream stream = File.Open(_fileName, FileMode.Create, FileAccess.Write, FileShare.Read)) { stream.Write(data, 0, data.Length); } dynamicByteProvider.ApplyChanges(); } } } catch (Exception ex1) { MessageBox.Show(ex1.Message, "T5Suite 2.0", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { ManageAbility(); } } void CleanUp() { if (hexBox1.ByteProvider != null) { IDisposable byteProvider = hexBox1.ByteProvider as IDisposable; if (byteProvider != null) byteProvider.Dispose(); hexBox1.ByteProvider = null; } _fileName = null; CastCloseEvent(); //DisplayText(null); } void OpenFile(string fileName) { if (!File.Exists(fileName)) { MessageBox.Show("File does not exist!"); return; } if (hexBox1.ByteProvider != null) { if (CloseFile() == DialogResult.Cancel) return; } try { FileByteProvider fileByteProvider = new FileByteProvider(fileName); fileByteProvider.Changed += new EventHandler(byteProvider_Changed); hexBox1.ByteProvider = fileByteProvider; _fileName = fileName; _lastFilename = _fileName; // DisplayText(fileName); } catch (Exception ex1) { MessageBox.Show(ex1.Message, "HexEditor", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } finally { ManageAbility(); } } void byteProvider_Changed(object sender, EventArgs e) { ManageAbility(); } void ManageAbility() { if (hexBox1.ByteProvider == null) { miClose.Enabled = false; miSave.Enabled = false; miFind.Enabled = false; miFindNext.Enabled = false; } else { miSave.Enabled = hexBox1.ByteProvider.HasChanges(); miClose.Enabled = true; miFind.Enabled = true; miFindNext.Enabled = true; //miGoTo.Enabled = true; } ManageAbilityForCopyAndPaste(); } /// <summary> /// Manages enabling or disabling of menu items and toolbar buttons for copy and paste /// </summary> void ManageAbilityForCopyAndPaste() { miCopy.Enabled = hexBox1.CanCopy(); miCut.Enabled = hexBox1.CanCut(); miPaste.Enabled = hexBox1.CanPaste(); } public void LoadDataFromFile(string filename, SymbolCollection symbols) { _fileName = filename; _lastFilename = _fileName; m_symbolcollection = symbols; FileInfo fi = new FileInfo(filename); m_currentfile_size = (int)fi.Length; OpenFile(filename); // ??? // CloseFile(); /* FileInfo fi = new FileInfo(filename); long numberoflines = fi.Length/16; StringBuilder sb = new StringBuilder(); StringBuilder sbascii = new StringBuilder(); using (BinaryReader br = new BinaryReader(new FileStream(filename, FileMode.Open))) { int current_address = 0; for (int lcount = 0; lcount < numberoflines; lcount++) { byte[] readbytes = br.ReadBytes(16); string line = current_address.ToString("X6") + " "; for (int bcount = 0; bcount < readbytes.Length; bcount++) { byte b = (byte)readbytes.GetValue(bcount); line += b.ToString("X2") + " "; } string line_ascii = string.Empty; for (int bcount = 0; bcount < readbytes.Length; bcount++) { byte b = (byte)readbytes.GetValue(bcount); if (b >= 0x20 && b <= 0x7f) { line_ascii += Convert.ToChar( b); } else { line_ascii += "."; } } sb.AppendLine(line); sbascii.AppendLine(line_ascii); current_address += 16; } } richTextBox1.Text = sb.ToString(); richTextBox2.Text = sbascii.ToString(); //MessageBox.Show(richTextBox1.Find("ox1_filt_coef").ToString());*/ } void Find() { if (_formFind.ShowDialog() == DialogResult.OK) { _findBuffer = _formFind.GetFindBytes(); FindNext(); } } void FindNext() { if (_findBuffer.Length == 0) { Find(); return; } // show cancel dialog _formFindCancel = new FormFindCancel(); _formFindCancel.SetHexBox(hexBox1); _formFindCancel.Closed += new EventHandler(FormFindCancel_Closed); _formFindCancel.Show(); // block activation of main form //Activated += new EventHandler(FocusToFormFindCancel); // start find process long res = hexBox1.Find(_findBuffer, hexBox1.SelectionStart + hexBox1.SelectionLength); _formFindCancel.Dispose(); // unblock activation of main form //Activated -= new EventHandler(FocusToFormFindCancel); if (res == -1) // -1 = no match { MessageBox.Show("Find reached end of file", "T5Suite 2.0", MessageBoxButtons.OK, MessageBoxIcon.Information); } else if (res == -2) // -2 = find was aborted { return; } else // something was found { if (!hexBox1.Focused) hexBox1.Focus(); } ManageAbility(); } void FormFindCancel_Closed(object sender, EventArgs e) { hexBox1.AbortFind(); } private void miFind_Click(object sender, EventArgs e) { Find(); } private void miCut_Click(object sender, EventArgs e) { hexBox1.Cut(); } private void miCopy_Click(object sender, EventArgs e) { hexBox1.Copy(); } private void miPaste_Click(object sender, EventArgs e) { hexBox1.Paste(); } private void printToolStripButton_Click(object sender, EventArgs e) { //print document } private void miSave_Click(object sender, EventArgs e) { SaveFile(); } private void openToolStripButton_Click(object sender, EventArgs e) { } private void miClose_Click(object sender, EventArgs e) { CloseFile(); //CastCloseEvent(); } private void CastCloseEvent() { if (onClose != null) { onClose(this, EventArgs.Empty); } } private string GetSymbolNameOffSetAndLength(long index, out int offset, out int length) { offset = 0; length = 0; string retval = "No symbol"; foreach (SymbolHelper sh in m_symbolcollection) { int address = sh.Flash_start_address; if (m_issramviewer) { address = sh.Start_address; } int internal_length = sh.Length; if (address > 0) { while (address > m_currentfile_size) address -= m_currentfile_size; if (index >= address && index < (address + internal_length) && !sh.Varname.StartsWith("Pressure map")) { retval = sh.Varname; if (m_issramviewer) { offset = sh.Start_address; } else { offset = sh.Flash_start_address; while (offset > m_currentfile_size) offset -= m_currentfile_size; } length = sh.Length; break; } } } return retval; } private string GetSymbolName(long index) { string retval = "No symbol"; foreach (SymbolHelper sh in m_symbolcollection) { int address = sh.Flash_start_address; if (m_issramviewer) { address = sh.Start_address; } int length = sh.Length; if (address > 0) { while (address > m_currentfile_size) address -= m_currentfile_size; if (index >= address && index < (address + length) && !sh.Varname.StartsWith("Pressure map")) { retval = sh.Varname; break; } } } return retval; } private void hexBox1_CurrentPositionInLineChanged(object sender, EventArgs e) { toolStripLabel1.Text = string.Format("Ln {0} Col {1}", hexBox1.CurrentLine, hexBox1.CurrentPositionInLine); toolStripButton1.Text = GetSymbolName((hexBox1.CurrentLine - 1) * 16 + (hexBox1.CurrentPositionInLine - 1)); } private void hexBox1_DragDrop(object sender, DragEventArgs e) { string[] formats = e.Data.GetFormats(); object oFileNames = e.Data.GetData(DataFormats.FileDrop); string[] fileNames = (string[])oFileNames; if (fileNames.Length == 1) { OpenFile(fileNames[0]); } } private void hexBox1_SelectionLengthChanged(object sender, EventArgs e) { ManageAbilityForCopyAndPaste(); } private void hexBox1_SelectionStartChanged(object sender, EventArgs e) { ManageAbilityForCopyAndPaste(); } private void hexBox1_DragEnter(object sender, DragEventArgs e) { e.Effect = DragDropEffects.All; } private void toolStripButton1_Click(object sender, EventArgs e) { if (toolStripButton1.Text != "" && toolStripButton1.Text != "No symbol") { // find in symbol collection foreach (SymbolHelper sh in m_symbolcollection) { if (sh.Varname == toolStripButton1.Text) { int address = sh.Flash_start_address; if (m_issramviewer) { address = sh.Start_address; } int length = sh.Length; while (address > m_currentfile_size) address -= m_currentfile_size; SelectText(sh.Varname, address, length); break; } } } } private void miFindNext_Click(object sender, EventArgs e) { FindNext(); } private void CastSelectionChanged(int offset, int length) { if (onSelectionChanged != null && offset != 0) { onSelectionChanged(this, new SelectionChangedEventArgs(offset, length)); } } private void hexBox1_DoubleClick(object sender, EventArgs e) { int offset = 0; int length = 0; string symbol = GetSymbolNameOffSetAndLength((hexBox1.CurrentLine - 1) * 16 + (hexBox1.CurrentPositionInLine - 1), out offset, out length); CastSelectionChanged(Convert.ToInt32((hexBox1.CurrentLine - 1) * 16 + (hexBox1.CurrentPositionInLine - 1)), length); if (symbol != "No symbol") { SelectText(symbol, offset, length); } } } public class SelectionChangedEventArgs : System.EventArgs { private int _offset; private int _length; public int Length { get { return _length; } set { _length = value; } } public int Offset { get { return _offset; } set { _offset = value; } } public SelectionChangedEventArgs(int offset, int length) { this._offset = offset; this._length = length; } } }
// // System.Diagnostics.TraceListenerCollection.cs // // Authors: // Jonathan Pryor ([email protected]) // // Comments from John R. Hicks <[email protected]> original implementation // can be found at: /mcs/docs/apidocs/xml/en/System.Diagnostics // // (C) 2002 Jonathan Pryor // // // 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.Diagnostics; using System.Globalization; namespace System.Diagnostics { public class TraceListenerCollection : IList, ICollection, IEnumerable { private ArrayList listeners = ArrayList.Synchronized (new ArrayList (1)); internal TraceListenerCollection () : this (true) { } internal TraceListenerCollection (bool addDefault) { // if (addDefault) // Add (new DefaultTraceListener ()); } public int Count{ get {return listeners.Count;} } public TraceListener this [string name] { get { lock (listeners.SyncRoot) { foreach (TraceListener listener in listeners) { if (listener.Name == name) return listener; } } return null; } } public TraceListener this [int index] { get {return (TraceListener) listeners[index];} set { InitializeListener (value); listeners[index] = value; } } object IList.this [int index] { get {return listeners[index];} set { TraceListener l = (TraceListener) value; InitializeListener (l); this[index] = l; } } bool ICollection.IsSynchronized { get {return listeners.IsSynchronized;} } object ICollection.SyncRoot { get {return listeners.SyncRoot;} } bool IList.IsFixedSize { get {return listeners.IsFixedSize;} } bool IList.IsReadOnly { get {return listeners.IsReadOnly;} } public int Add (TraceListener listener) { InitializeListener (listener); return listeners.Add (listener); } #if !MOBILE internal void Add (TraceListener listener, TraceImplSettings settings) { // listener.IndentLevel = settings.IndentLevel; listener.IndentSize = settings.IndentSize; listeners.Add (listener); } #endif private void InitializeListener (TraceListener listener) { listener.IndentLevel = TraceImpl.IndentLevel; listener.IndentSize = TraceImpl.IndentSize; } private void InitializeRange (IList listeners) { int e = listeners.Count; for (int i = 0; i != e; ++i) InitializeListener ( (TraceListener) listeners[i]); } public void AddRange (TraceListener[] value) { InitializeRange (value); listeners.AddRange (value); } public void AddRange (TraceListenerCollection value) { InitializeRange (value); listeners.AddRange (value.listeners); } public void Clear () { listeners.Clear (); } public bool Contains (TraceListener listener) { return listeners.Contains (listener); } public void CopyTo (TraceListener[] listeners, int index) { listeners.CopyTo (listeners, index); } public IEnumerator GetEnumerator () { return listeners.GetEnumerator (); } void ICollection.CopyTo (Array array, int index) { listeners.CopyTo (array, index); } int IList.Add (object value) { if (value is TraceListener) return Add ((TraceListener) value); throw new NotSupportedException ( "You can only add TraceListener objects to the collection"); } bool IList.Contains (object value) { if (value is TraceListener) return listeners.Contains (value); return false; } int IList.IndexOf (object value) { if (value is TraceListener) return listeners.IndexOf (value); return -1; } void IList.Insert (int index, object value) { if (value is TraceListener) { Insert (index, (TraceListener) value); return; } throw new NotSupportedException ( "You can only insert TraceListener objects into the collection"); } void IList.Remove (object value) { if (value is TraceListener) listeners.Remove (value); } public int IndexOf (TraceListener listener) { return listeners.IndexOf (listener); } public void Insert (int index, TraceListener listener) { InitializeListener (listener); listeners.Insert (index, listener); } public void Remove (string name) { TraceListener found = null; lock (listeners.SyncRoot) { foreach (TraceListener listener in listeners) { if (listener.Name == name) { found = listener; break; } } if (found != null) listeners.Remove (found); else throw new ArgumentException ( "TraceListener " + name + " was not in the collection"); } } public void Remove (TraceListener listener) { listeners.Remove (listener); } public void RemoveAt (int index) { listeners.RemoveAt (index); } } }
using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; namespace ACControls { /// <summary> /// Descrizione di riepilogo per ImageFlip. /// </summary> public class ImageFlip : System.Windows.Forms.UserControl { /// <summary> /// Variabile di progettazione necessaria. /// </summary> private System.ComponentModel.Container components = null; private Image m_image = null; private Image m_store = null; private int m_height = 0; private int m_heightflip = 0; private int m_divider = 1; public ImageFlip() { // Chiamata richiesta da Progettazione form Windows.Forms. InitializeComponent(); m_height = base.Height; m_heightflip = (m_height / 2); } /// <summary> /// Pulire le risorse in uso. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Codice generato da Progettazione componenti /// <summary> /// Metodo necessario per il supporto della finestra di progettazione. Non modificare /// il contenuto del metodo con l'editor di codice. /// </summary> private void InitializeComponent() { components = new System.ComponentModel.Container(); } #endregion [Category("Appearance"), Browsable(true), EditorBrowsable, Description("Set the control image")] public Image Image { get { return m_store; } set { m_store = value; this.InitControlImage(); } } public Image FlippedImage { get { return m_image; } } [Category("Appearance"), Browsable(true), EditorBrowsable, Description("Set the height of flipped image, in fraction of original image") ] public int Divider { get { return m_divider; } set { if (value != 0) { m_divider = value; this.InitControlImage(); } } } [Browsable(false)] public override Image BackgroundImage { get { return null; } } [Browsable(false)] public override string Text { get { return string.Empty; } } [Browsable(false)] public override Color BackColor { get { return Color.Transparent; } } /// <summary> /// Flip the image and set control bounds /// </summary> private void InitControlImage() { if (m_store != null) { FlipImage(); base.SetBounds(base.Left, base.Top, m_image.Width, m_image.Height); base.Invalidate(); } } /// <summary> /// Create a gradient image and return a buffer of bytes /// </summary> /// <param name="FlipHeight">Rectangle height</param> /// <returns>Buffer of bytes</returns> private byte[] GradientRectangle(int FlipHeight) { int bytes = m_store.Width * FlipHeight * 4; byte[] m_argbsource = new byte[bytes]; Rectangle m_rectgradient = new Rectangle(0, 0, m_store.Width, FlipHeight); System.Drawing.Drawing2D.LinearGradientBrush m_brushgradient; m_brushgradient = new System.Drawing.Drawing2D.LinearGradientBrush(m_rectgradient, Color.FromArgb(120, Color.White), Color.FromArgb(0, Color.White), 90F); Bitmap m_bmpgradient = new Bitmap(m_store.Width, FlipHeight); using(Graphics g = Graphics.FromImage(m_bmpgradient)) { g.FillRectangle(m_brushgradient, 0, 0, m_store.Width, FlipHeight); } BitmapData m_datasource = m_bmpgradient.LockBits(m_rectgradient, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); IntPtr m_ptrsource = m_datasource.Scan0; System.Runtime.InteropServices.Marshal.Copy(m_ptrsource, m_argbsource, 0, bytes); return m_argbsource; } /// <summary> /// Flip the image and compose to original /// </summary> private void FlipImage() { // Calculate new height m_heightflip = (m_store.Height / m_divider); m_height = (m_store.Height + m_heightflip); // New image is self height plus a piece Bitmap m_double = new Bitmap(m_store.Width, m_height); Rectangle m_rectflip = new Rectangle(0, m_store.Height, m_store.Width, m_heightflip); using(Graphics g = Graphics.FromImage(m_double)) { Image m_img = (Image)m_store.Clone(); // Draw normal image g.DrawImage(m_store, 0, 0, m_store.Width, m_store.Height); // Flip the clone m_img.RotateFlip(RotateFlipType.Rotate180FlipX); // Draw the flipped clone, cropping at flip height g.DrawImage(m_img, 0, m_store.Height, new Rectangle(0, 0, m_store.Width, m_heightflip), GraphicsUnit.Pixel); // Remove this m_img.Dispose(); ////////////////////////////////////////////////////////////////////////// // Apply transparent mask BitmapData m_datadestin = m_double.LockBits(m_rectflip, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); // Init the source and destination buffers int bytes = (m_store.Width * m_heightflip * 4); byte[] m_argbdestin = new byte[bytes]; byte[] m_argbsource = GradientRectangle(m_heightflip); // Point at destination, instead UNSAFE block IntPtr m_ptrdestin = m_datadestin.Scan0; System.Runtime.InteropServices.Marshal.Copy(m_ptrdestin, m_argbdestin, 0, bytes); // Set every transparency value to mask. for (int counter = 3; counter < m_argbsource.Length; counter += 4) { if (m_argbdestin[counter] > 0) m_argbdestin[counter] = m_argbsource[counter]; /* //if (m_argbdestin[counter] > 0) { float d = (float)m_argbsource[counter] / (float)255.0; float bb = (float)m_argbdestin[counter - 3] * d; float gb = (float)m_argbdestin[counter - 2] * d; float rb = (float)m_argbdestin[counter - 1] * d; m_argbdestin[counter - 3] = (byte)bb; m_argbdestin[counter - 2] = (byte)gb; m_argbdestin[counter - 1] = (byte)rb; m_argbdestin[counter] = 255; }*/ } // Copy the ARGB values back to the bitmap System.Runtime.InteropServices.Marshal.Copy(m_argbdestin, 0, m_ptrdestin, bytes); // Unlock the bits. m_double.UnlockBits(m_datadestin); ////////////////////////////////////////////////////////////////////////// } // Reassign modified image to paintable one. m_image = m_double; } // Draw the modified image protected override void OnPaint(PaintEventArgs pevent) { if ( m_image != null ) { pevent.Graphics.DrawImage ( m_image, 0, 0 ); } base.OnPaint(pevent); } // Set background trasparent for control protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; cp.ExStyle |= 0x20; return cp; } } // Avoid drawing back image or color protected override void OnPaintBackground(PaintEventArgs pevent) { // Do nothing, it's trasparent //base.OnPaintBackground (pevent); } } }
/* * Location Intelligence APIs * * Incorporate our extensive geodata into everyday applications, business processes and workflows. * * OpenAPI spec version: 8.5.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace pb.locationIntelligence.Model { /// <summary> /// MatchedAddress /// </summary> [DataContract] public partial class MatchedAddress : IEquatable<MatchedAddress> { /// <summary> /// Initializes a new instance of the <see cref="MatchedAddress" /> class. /// </summary> /// <param name="FormattedAddress">FormattedAddress.</param> /// <param name="MainAddressLine">MainAddressLine.</param> /// <param name="AddressLastLine">AddressLastLine.</param> /// <param name="PlaceName">PlaceName.</param> /// <param name="AreaName1">AreaName1.</param> /// <param name="AreaName2">AreaName2.</param> /// <param name="AreaName3">AreaName3.</param> /// <param name="AreaName4">AreaName4.</param> /// <param name="PostCode">PostCode.</param> /// <param name="PostCodeExt">PostCodeExt.</param> /// <param name="Country">Country.</param> /// <param name="AddressNumber">AddressNumber.</param> /// <param name="StreetName">StreetName.</param> /// <param name="UnitType">UnitType.</param> /// <param name="UnitValue">UnitValue.</param> public MatchedAddress(string FormattedAddress = null, string MainAddressLine = null, string AddressLastLine = null, string PlaceName = null, string AreaName1 = null, string AreaName2 = null, string AreaName3 = null, string AreaName4 = null, string PostCode = null, string PostCodeExt = null, string Country = null, string AddressNumber = null, string StreetName = null, string UnitType = null, string UnitValue = null) { this.FormattedAddress = FormattedAddress; this.MainAddressLine = MainAddressLine; this.AddressLastLine = AddressLastLine; this.PlaceName = PlaceName; this.AreaName1 = AreaName1; this.AreaName2 = AreaName2; this.AreaName3 = AreaName3; this.AreaName4 = AreaName4; this.PostCode = PostCode; this.PostCodeExt = PostCodeExt; this.Country = Country; this.AddressNumber = AddressNumber; this.StreetName = StreetName; this.UnitType = UnitType; this.UnitValue = UnitValue; } /// <summary> /// Gets or Sets FormattedAddress /// </summary> [DataMember(Name="formattedAddress", EmitDefaultValue=false)] public string FormattedAddress { get; set; } /// <summary> /// Gets or Sets MainAddressLine /// </summary> [DataMember(Name="mainAddressLine", EmitDefaultValue=false)] public string MainAddressLine { get; set; } /// <summary> /// Gets or Sets AddressLastLine /// </summary> [DataMember(Name="addressLastLine", EmitDefaultValue=false)] public string AddressLastLine { get; set; } /// <summary> /// Gets or Sets PlaceName /// </summary> [DataMember(Name="placeName", EmitDefaultValue=false)] public string PlaceName { get; set; } /// <summary> /// Gets or Sets AreaName1 /// </summary> [DataMember(Name="areaName1", EmitDefaultValue=false)] public string AreaName1 { get; set; } /// <summary> /// Gets or Sets AreaName2 /// </summary> [DataMember(Name="areaName2", EmitDefaultValue=false)] public string AreaName2 { get; set; } /// <summary> /// Gets or Sets AreaName3 /// </summary> [DataMember(Name="areaName3", EmitDefaultValue=false)] public string AreaName3 { get; set; } /// <summary> /// Gets or Sets AreaName4 /// </summary> [DataMember(Name="areaName4", EmitDefaultValue=false)] public string AreaName4 { get; set; } /// <summary> /// Gets or Sets PostCode /// </summary> [DataMember(Name="postCode", EmitDefaultValue=false)] public string PostCode { get; set; } /// <summary> /// Gets or Sets PostCodeExt /// </summary> [DataMember(Name="postCodeExt", EmitDefaultValue=false)] public string PostCodeExt { get; set; } /// <summary> /// Gets or Sets Country /// </summary> [DataMember(Name="country", EmitDefaultValue=false)] public string Country { get; set; } /// <summary> /// Gets or Sets AddressNumber /// </summary> [DataMember(Name="addressNumber", EmitDefaultValue=false)] public string AddressNumber { get; set; } /// <summary> /// Gets or Sets StreetName /// </summary> [DataMember(Name="streetName", EmitDefaultValue=false)] public string StreetName { get; set; } /// <summary> /// Gets or Sets UnitType /// </summary> [DataMember(Name="unitType", EmitDefaultValue=false)] public string UnitType { get; set; } /// <summary> /// Gets or Sets UnitValue /// </summary> [DataMember(Name="unitValue", EmitDefaultValue=false)] public string UnitValue { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class MatchedAddress {\n"); sb.Append(" FormattedAddress: ").Append(FormattedAddress).Append("\n"); sb.Append(" MainAddressLine: ").Append(MainAddressLine).Append("\n"); sb.Append(" AddressLastLine: ").Append(AddressLastLine).Append("\n"); sb.Append(" PlaceName: ").Append(PlaceName).Append("\n"); sb.Append(" AreaName1: ").Append(AreaName1).Append("\n"); sb.Append(" AreaName2: ").Append(AreaName2).Append("\n"); sb.Append(" AreaName3: ").Append(AreaName3).Append("\n"); sb.Append(" AreaName4: ").Append(AreaName4).Append("\n"); sb.Append(" PostCode: ").Append(PostCode).Append("\n"); sb.Append(" PostCodeExt: ").Append(PostCodeExt).Append("\n"); sb.Append(" Country: ").Append(Country).Append("\n"); sb.Append(" AddressNumber: ").Append(AddressNumber).Append("\n"); sb.Append(" StreetName: ").Append(StreetName).Append("\n"); sb.Append(" UnitType: ").Append(UnitType).Append("\n"); sb.Append(" UnitValue: ").Append(UnitValue).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { // credit: http://stackoverflow.com/a/10454552/677735 return this.Equals(obj as MatchedAddress); } /// <summary> /// Returns true if MatchedAddress instances are equal /// </summary> /// <param name="other">Instance of MatchedAddress to be compared</param> /// <returns>Boolean</returns> public bool Equals(MatchedAddress other) { // credit: http://stackoverflow.com/a/10454552/677735 if (other == null) return false; return ( this.FormattedAddress == other.FormattedAddress || this.FormattedAddress != null && this.FormattedAddress.Equals(other.FormattedAddress) ) && ( this.MainAddressLine == other.MainAddressLine || this.MainAddressLine != null && this.MainAddressLine.Equals(other.MainAddressLine) ) && ( this.AddressLastLine == other.AddressLastLine || this.AddressLastLine != null && this.AddressLastLine.Equals(other.AddressLastLine) ) && ( this.PlaceName == other.PlaceName || this.PlaceName != null && this.PlaceName.Equals(other.PlaceName) ) && ( this.AreaName1 == other.AreaName1 || this.AreaName1 != null && this.AreaName1.Equals(other.AreaName1) ) && ( this.AreaName2 == other.AreaName2 || this.AreaName2 != null && this.AreaName2.Equals(other.AreaName2) ) && ( this.AreaName3 == other.AreaName3 || this.AreaName3 != null && this.AreaName3.Equals(other.AreaName3) ) && ( this.AreaName4 == other.AreaName4 || this.AreaName4 != null && this.AreaName4.Equals(other.AreaName4) ) && ( this.PostCode == other.PostCode || this.PostCode != null && this.PostCode.Equals(other.PostCode) ) && ( this.PostCodeExt == other.PostCodeExt || this.PostCodeExt != null && this.PostCodeExt.Equals(other.PostCodeExt) ) && ( this.Country == other.Country || this.Country != null && this.Country.Equals(other.Country) ) && ( this.AddressNumber == other.AddressNumber || this.AddressNumber != null && this.AddressNumber.Equals(other.AddressNumber) ) && ( this.StreetName == other.StreetName || this.StreetName != null && this.StreetName.Equals(other.StreetName) ) && ( this.UnitType == other.UnitType || this.UnitType != null && this.UnitType.Equals(other.UnitType) ) && ( this.UnitValue == other.UnitValue || this.UnitValue != null && this.UnitValue.Equals(other.UnitValue) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { // credit: http://stackoverflow.com/a/263416/677735 unchecked // Overflow is fine, just wrap { int hash = 41; // Suitable nullity checks etc, of course :) if (this.FormattedAddress != null) hash = hash * 59 + this.FormattedAddress.GetHashCode(); if (this.MainAddressLine != null) hash = hash * 59 + this.MainAddressLine.GetHashCode(); if (this.AddressLastLine != null) hash = hash * 59 + this.AddressLastLine.GetHashCode(); if (this.PlaceName != null) hash = hash * 59 + this.PlaceName.GetHashCode(); if (this.AreaName1 != null) hash = hash * 59 + this.AreaName1.GetHashCode(); if (this.AreaName2 != null) hash = hash * 59 + this.AreaName2.GetHashCode(); if (this.AreaName3 != null) hash = hash * 59 + this.AreaName3.GetHashCode(); if (this.AreaName4 != null) hash = hash * 59 + this.AreaName4.GetHashCode(); if (this.PostCode != null) hash = hash * 59 + this.PostCode.GetHashCode(); if (this.PostCodeExt != null) hash = hash * 59 + this.PostCodeExt.GetHashCode(); if (this.Country != null) hash = hash * 59 + this.Country.GetHashCode(); if (this.AddressNumber != null) hash = hash * 59 + this.AddressNumber.GetHashCode(); if (this.StreetName != null) hash = hash * 59 + this.StreetName.GetHashCode(); if (this.UnitType != null) hash = hash * 59 + this.UnitType.GetHashCode(); if (this.UnitValue != null) hash = hash * 59 + this.UnitValue.GetHashCode(); return hash; } } } }
// 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.Reflection; using System.Text; using System.Collections; using System.Globalization; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Diagnostics; using System.Diagnostics.Contracts; // The code below includes partial support for float/double and // pointer sized enums. // // The type loader does not prohibit such enums, and older versions of // the ECMA spec include them as possible enum types. // // However there are many things broken throughout the stack for // float/double/intptr/uintptr enums. There was a conscious decision // made to not fix the whole stack to work well for them because of // the right behavior is often unclear, and it is hard to test and // very low value because of such enums cannot be expressed in C#. namespace System { [Serializable] [System.Runtime.CompilerServices.TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public abstract class Enum : ValueType, IComparable, IFormattable, IConvertible { #region Private Constants private const char enumSeparatorChar = ','; private const String enumSeparatorString = ", "; #endregion #region Private Static Methods private static TypeValuesAndNames GetCachedValuesAndNames(RuntimeType enumType, bool getNames) { TypeValuesAndNames entry = enumType.GenericCache as TypeValuesAndNames; if (entry == null || (getNames && entry.Names == null)) { ulong[] values = null; String[] names = null; bool isFlags = enumType.IsDefined(typeof(System.FlagsAttribute), false); GetEnumValuesAndNames( enumType.GetTypeHandleInternal(), JitHelpers.GetObjectHandleOnStack(ref values), JitHelpers.GetObjectHandleOnStack(ref names), getNames); entry = new TypeValuesAndNames(isFlags, values, names); enumType.GenericCache = entry; } return entry; } private unsafe String InternalFormattedHexString() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: case CorElementType.U1: return (*(byte*)pValue).ToString("X2", null); case CorElementType.Boolean: // direct cast from bool to byte is not allowed return Convert.ToByte(*(bool*)pValue).ToString("X2", null); case CorElementType.I2: case CorElementType.U2: case CorElementType.Char: return (*(ushort*)pValue).ToString("X4", null); case CorElementType.I4: case CorElementType.U4: return (*(uint*)pValue).ToString("X8", null); case CorElementType.I8: case CorElementType.U8: return (*(ulong*)pValue).ToString("X16", null); default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } } private static String InternalFormattedHexString(object value) { TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.SByte: return ((byte)(sbyte)value).ToString("X2", null); case TypeCode.Byte: return ((byte)value).ToString("X2", null); case TypeCode.Boolean: // direct cast from bool to byte is not allowed return Convert.ToByte((bool)value).ToString("X2", null); case TypeCode.Int16: return ((UInt16)(Int16)value).ToString("X4", null); case TypeCode.UInt16: return ((UInt16)value).ToString("X4", null); case TypeCode.Char: return ((UInt16)(Char)value).ToString("X4", null); case TypeCode.UInt32: return ((UInt32)value).ToString("X8", null); case TypeCode.Int32: return ((UInt32)(Int32)value).ToString("X8", null); case TypeCode.UInt64: return ((UInt64)value).ToString("X16", null); case TypeCode.Int64: return ((UInt64)(Int64)value).ToString("X16", null); // All unsigned types will be directly cast default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } internal static String GetEnumName(RuntimeType eT, ulong ulValue) { Contract.Requires(eT != null); ulong[] ulValues = Enum.InternalGetValues(eT); int index = Array.BinarySearch(ulValues, ulValue); if (index >= 0) { string[] names = Enum.InternalGetNames(eT); return names[index]; } return null; // return null so the caller knows to .ToString() the input } private static String InternalFormat(RuntimeType eT, ulong value) { Contract.Requires(eT != null); // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); if (!entry.IsFlag) // Not marked with Flags attribute { return Enum.GetEnumName(eT, value); } else // These are flags OR'ed together (We treat everything as unsigned types) { return InternalFlagsFormat(eT, entry, value); } } private static String InternalFlagsFormat(RuntimeType eT, ulong result) { // These values are sorted by value. Don't change this TypeValuesAndNames entry = GetCachedValuesAndNames(eT, true); return InternalFlagsFormat(eT, entry, result); } private static String InternalFlagsFormat(RuntimeType eT, TypeValuesAndNames entry, ulong result) { Contract.Requires(eT != null); String[] names = entry.Names; ulong[] values = entry.Values; Debug.Assert(names.Length == values.Length); int index = values.Length - 1; StringBuilder sb = StringBuilderCache.Acquire(); bool firstTime = true; ulong saveResult = result; // We will not optimize this code further to keep it maintainable. There are some boundary checks that can be applied // to minimize the comparsions required. This code works the same for the best/worst case. In general the number of // items in an enum are sufficiently small and not worth the optimization. while (index >= 0) { if ((index == 0) && (values[index] == 0)) break; if ((result & values[index]) == values[index]) { result -= values[index]; if (!firstTime) sb.Insert(0, enumSeparatorString); sb.Insert(0, names[index]); firstTime = false; } index--; } string returnString; if (result != 0) { // We were unable to represent this number as a bitwise or of valid flags returnString = null; // return null so the caller knows to .ToString() the input } else if (saveResult == 0) { // For the cases when we have zero if (values.Length > 0 && values[0] == 0) { returnString = names[0]; // Zero was one of the enum values. } else { returnString = "0"; } } else { returnString = sb.ToString(); // Return the string representation } StringBuilderCache.Release(sb); return returnString; } internal static ulong ToUInt64(Object value) { // Helper function to silently convert the value to UInt64 from the other base types for enum without throwing an exception. // This is need since the Convert functions do overflow checks. TypeCode typeCode = Convert.GetTypeCode(value); ulong result; switch (typeCode) { case TypeCode.SByte: result = (ulong)(sbyte)value; break; case TypeCode.Byte: result = (byte)value; break; case TypeCode.Boolean: // direct cast from bool to byte is not allowed result = Convert.ToByte((bool)value); break; case TypeCode.Int16: result = (ulong)(Int16)value; break; case TypeCode.UInt16: result = (UInt16)value; break; case TypeCode.Char: result = (UInt16)(Char)value; break; case TypeCode.UInt32: result = (UInt32)value; break; case TypeCode.Int32: result = (ulong)(int)value; break; case TypeCode.UInt64: result = (ulong)value; break; case TypeCode.Int64: result = (ulong)(Int64)value; break; // All unsigned types will be directly cast default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } return result; } [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern int InternalCompareTo(Object o1, Object o2); [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern RuntimeType InternalGetUnderlyingType(RuntimeType enumType); [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode)] [System.Security.SuppressUnmanagedCodeSecurity] private static extern void GetEnumValuesAndNames(RuntimeTypeHandle enumType, ObjectHandleOnStack values, ObjectHandleOnStack names, bool getNames); [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern Object InternalBoxEnum(RuntimeType enumType, long value); #endregion #region Public Static Methods private enum ParseFailureKind { None = 0, Argument = 1, ArgumentNull = 2, ArgumentWithParameter = 3, UnhandledException = 4 } // This will store the result of the parsing. private struct EnumResult { internal object parsedEnum; internal bool canThrow; internal ParseFailureKind m_failure; internal string m_failureMessageID; internal string m_failureParameter; internal object m_failureMessageFormatArgument; internal Exception m_innerException; internal void SetFailure(Exception unhandledException) { m_failure = ParseFailureKind.UnhandledException; m_innerException = unhandledException; } internal void SetFailure(ParseFailureKind failure, string failureParameter) { m_failure = failure; m_failureParameter = failureParameter; if (canThrow) throw GetEnumParseException(); } internal void SetFailure(ParseFailureKind failure, string failureMessageID, object failureMessageFormatArgument) { m_failure = failure; m_failureMessageID = failureMessageID; m_failureMessageFormatArgument = failureMessageFormatArgument; if (canThrow) throw GetEnumParseException(); } internal Exception GetEnumParseException() { switch (m_failure) { case ParseFailureKind.Argument: return new ArgumentException(SR.GetResourceString(m_failureMessageID)); case ParseFailureKind.ArgumentNull: return new ArgumentNullException(m_failureParameter); case ParseFailureKind.ArgumentWithParameter: return new ArgumentException(SR.Format(SR.GetResourceString(m_failureMessageID), m_failureMessageFormatArgument)); case ParseFailureKind.UnhandledException: return m_innerException; default: Debug.Assert(false, "Unknown EnumParseFailure: " + m_failure); return new ArgumentException(SR.Arg_EnumValueNotFound); } } } public static bool TryParse(Type enumType, String value, out Object result) { return TryParse(enumType, value, false, out result); } public static bool TryParse(Type enumType, String value, bool ignoreCase, out Object result) { result = null; EnumResult parseResult = new EnumResult(); bool retValue; if (retValue = TryParseEnum(enumType, value, ignoreCase, ref parseResult)) result = parseResult.parsedEnum; return retValue; } public static bool TryParse<TEnum>(String value, out TEnum result) where TEnum : struct { return TryParse(value, false, out result); } public static bool TryParse<TEnum>(String value, bool ignoreCase, out TEnum result) where TEnum : struct { result = default(TEnum); EnumResult parseResult = new EnumResult(); bool retValue; if (retValue = TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) result = (TEnum)parseResult.parsedEnum; return retValue; } public static Object Parse(Type enumType, String value) { return Parse(enumType, value, false); } public static Object Parse(Type enumType, String value, bool ignoreCase) { EnumResult parseResult = new EnumResult() { canThrow = true }; if (TryParseEnum(enumType, value, ignoreCase, ref parseResult)) return parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } public static TEnum Parse<TEnum>(String value) where TEnum : struct { return Parse<TEnum>(value, false); } public static TEnum Parse<TEnum>(String value, bool ignoreCase) where TEnum : struct { EnumResult parseResult = new EnumResult() { canThrow = true }; if (TryParseEnum(typeof(TEnum), value, ignoreCase, ref parseResult)) return (TEnum)parseResult.parsedEnum; else throw parseResult.GetEnumParseException(); } private static bool TryParseEnum(Type enumType, String value, bool ignoreCase, ref EnumResult parseResult) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (value == null) { parseResult.SetFailure(ParseFailureKind.ArgumentNull, nameof(value)); return false; } int firstNonWhitespaceIndex = -1; for (int i = 0; i < value.Length; i++) { if (!Char.IsWhiteSpace(value[i])) { firstNonWhitespaceIndex = i; break; } } if (firstNonWhitespaceIndex == -1) { parseResult.SetFailure(ParseFailureKind.Argument, nameof(SR.Arg_MustContainEnumInfo), null); return false; } // We have 2 code paths here. One if they are values else if they are Strings. // values will have the first character as as number or a sign. ulong result = 0; char firstNonWhitespaceChar = value[firstNonWhitespaceIndex]; if (Char.IsDigit(firstNonWhitespaceChar) || firstNonWhitespaceChar == '-' || firstNonWhitespaceChar == '+') { Type underlyingType = GetUnderlyingType(enumType); Object temp; try { value = value.Trim(); temp = Convert.ChangeType(value, underlyingType, CultureInfo.InvariantCulture); parseResult.parsedEnum = ToObject(enumType, temp); return true; } catch (FormatException) { // We need to Parse this as a String instead. There are cases // when you tlbimp enums that can have values of the form "3D". // Don't fix this code. } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } // Find the field. Let's assume that these are always static classes // because the class is an enum. TypeValuesAndNames entry = GetCachedValuesAndNames(rtType, true); String[] enumNames = entry.Names; ulong[] enumValues = entry.Values; StringComparison comparison = ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; int valueIndex = firstNonWhitespaceIndex; while (valueIndex <= value.Length) // '=' is to handle invalid case of an ending comma { // Find the next separator, if there is one, otherwise the end of the string. int endIndex = value.IndexOf(enumSeparatorChar, valueIndex); if (endIndex == -1) { endIndex = value.Length; } // Shift the starting and ending indices to eliminate whitespace int endIndexNoWhitespace = endIndex; while (valueIndex < endIndex && Char.IsWhiteSpace(value[valueIndex])) valueIndex++; while (endIndexNoWhitespace > valueIndex && Char.IsWhiteSpace(value[endIndexNoWhitespace - 1])) endIndexNoWhitespace--; int valueSubstringLength = endIndexNoWhitespace - valueIndex; // Try to match this substring against each enum name bool success = false; for (int i = 0; i < enumNames.Length; i++) { if (enumNames[i].Length == valueSubstringLength && string.Compare(enumNames[i], 0, value, valueIndex, valueSubstringLength, comparison) == 0) { result |= enumValues[i]; success = true; break; } } // If we couldn't find a match, throw an argument exception. if (!success) { // Not found, throw an argument exception. parseResult.SetFailure(ParseFailureKind.ArgumentWithParameter, nameof(SR.Arg_EnumValueNotFound), value); return false; } // Move our pointer to the ending index to go again. valueIndex = endIndex + 1; } try { parseResult.parsedEnum = ToObject(enumType, result); return true; } catch (Exception ex) { if (parseResult.canThrow) throw; else { parseResult.SetFailure(ex); return false; } } } public static Type GetUnderlyingType(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Contract.Ensures(Contract.Result<Type>() != null); Contract.EndContractBlock(); return enumType.GetEnumUnderlyingType(); } public static Array GetValues(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Contract.Ensures(Contract.Result<Array>() != null); Contract.EndContractBlock(); return enumType.GetEnumValues(); } internal static ulong[] InternalGetValues(RuntimeType enumType) { // Get all of the values return GetCachedValuesAndNames(enumType, false).Values; } public static String GetName(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Contract.EndContractBlock(); return enumType.GetEnumName(value); } public static String[] GetNames(Type enumType) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Contract.Ensures(Contract.Result<String[]>() != null); Contract.EndContractBlock(); return enumType.GetEnumNames(); } internal static String[] InternalGetNames(RuntimeType enumType) { // Get all of the names return GetCachedValuesAndNames(enumType, true).Names; } public static Object ToObject(Type enumType, Object value) { if (value == null) throw new ArgumentNullException(nameof(value)); Contract.EndContractBlock(); // Delegate rest of error checking to the other functions TypeCode typeCode = Convert.GetTypeCode(value); switch (typeCode) { case TypeCode.Int32: return ToObject(enumType, (int)value); case TypeCode.SByte: return ToObject(enumType, (sbyte)value); case TypeCode.Int16: return ToObject(enumType, (short)value); case TypeCode.Int64: return ToObject(enumType, (long)value); case TypeCode.UInt32: return ToObject(enumType, (uint)value); case TypeCode.Byte: return ToObject(enumType, (byte)value); case TypeCode.UInt16: return ToObject(enumType, (ushort)value); case TypeCode.UInt64: return ToObject(enumType, (ulong)value); case TypeCode.Char: return ToObject(enumType, (char)value); case TypeCode.Boolean: return ToObject(enumType, (bool)value); default: // All unsigned types will be directly cast throw new ArgumentException(SR.Arg_MustBeEnumBaseTypeOrEnum, nameof(value)); } } [Pure] public static bool IsDefined(Type enumType, Object value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); Contract.EndContractBlock(); return enumType.IsEnumDefined(value); } public static String Format(Type enumType, Object value, String format) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); if (value == null) throw new ArgumentNullException(nameof(value)); if (format == null) throw new ArgumentNullException(nameof(format)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); // Check if both of them are of the same type Type valueType = value.GetType(); Type underlyingType = GetUnderlyingType(enumType); // If the value is an Enum then we need to extract the underlying value from it if (valueType.IsEnum) { if (!valueType.IsEquivalentTo(enumType)) throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, valueType.ToString(), enumType.ToString())); if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } return ((Enum)value).ToString(format); } // The value must be of the same type as the Underlying type of the Enum else if (valueType != underlyingType) { throw new ArgumentException(SR.Format(SR.Arg_EnumFormatUnderlyingTypeAndObjectMustBeSameType, valueType.ToString(), underlyingType.ToString())); } if (format.Length != 1) { // all acceptable format string are of length 1 throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } char formatCh = format[0]; if (formatCh == 'G' || formatCh == 'g') return GetEnumName(rtType, ToUInt64(value)) ?? value.ToString(); if (formatCh == 'D' || formatCh == 'd') return value.ToString(); if (formatCh == 'X' || formatCh == 'x') return InternalFormattedHexString(value); if (formatCh == 'F' || formatCh == 'f') return Enum.InternalFlagsFormat(rtType, ToUInt64(value)) ?? value.ToString(); throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } #endregion #region Definitions private class TypeValuesAndNames { // Each entry contains a list of sorted pair of enum field names and values, sorted by values public TypeValuesAndNames(bool isFlag, ulong[] values, String[] names) { this.IsFlag = isFlag; this.Values = values; this.Names = names; } public bool IsFlag; public ulong[] Values; public String[] Names; } #endregion #region Private Methods internal unsafe Object GetValue() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return *(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return *(bool*)pValue; case CorElementType.I2: return *(short*)pValue; case CorElementType.U2: return *(ushort*)pValue; case CorElementType.Char: return *(char*)pValue; case CorElementType.I4: return *(int*)pValue; case CorElementType.U4: return *(uint*)pValue; case CorElementType.R4: return *(float*)pValue; case CorElementType.I8: return *(long*)pValue; case CorElementType.U8: return *(ulong*)pValue; case CorElementType.R8: return *(double*)pValue; case CorElementType.I: return *(IntPtr*)pValue; case CorElementType.U: return *(UIntPtr*)pValue; default: Debug.Assert(false, "Invalid primitive type"); return null; } } } private unsafe ulong ToUInt64() { fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (ulong)*(sbyte*)pValue; case CorElementType.U1: return *(byte*)pValue; case CorElementType.Boolean: return Convert.ToUInt64(*(bool*)pValue, CultureInfo.InvariantCulture); case CorElementType.I2: return (ulong)*(short*)pValue; case CorElementType.U2: case CorElementType.Char: return *(ushort*)pValue; case CorElementType.I4: return (ulong)*(int*)pValue; case CorElementType.U4: case CorElementType.R4: return *(uint*)pValue; case CorElementType.I8: return (ulong)*(long*)pValue; case CorElementType.U8: case CorElementType.R8: return *(ulong*)pValue; case CorElementType.I: if (IntPtr.Size == 8) { return *(ulong*)pValue; } else { return (ulong)*(int*)pValue; } case CorElementType.U: if (IntPtr.Size == 8) { return *(ulong*)pValue; } else { return *(uint*)pValue; } default: Debug.Assert(false, "Invalid primitive type"); return 0; } } } [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern bool InternalHasFlag(Enum flags); [MethodImplAttribute(MethodImplOptions.InternalCall)] private extern CorElementType InternalGetCorElementType(); #endregion #region Object Overrides [MethodImplAttribute(MethodImplOptions.InternalCall)] public extern override bool Equals(Object obj); public override unsafe int GetHashCode() { // CONTRACT with the runtime: GetHashCode of enum types is implemented as GetHashCode of the underlying type. // The runtime can bypass calls to Enum::GetHashCode and call the underlying type's GetHashCode directly // to avoid boxing the enum. fixed (void* pValue = &JitHelpers.GetPinningHelper(this).m_data) { switch (InternalGetCorElementType()) { case CorElementType.I1: return (*(sbyte*)pValue).GetHashCode(); case CorElementType.U1: return (*(byte*)pValue).GetHashCode(); case CorElementType.Boolean: return (*(bool*)pValue).GetHashCode(); case CorElementType.I2: return (*(short*)pValue).GetHashCode(); case CorElementType.U2: return (*(ushort*)pValue).GetHashCode(); case CorElementType.Char: return (*(char*)pValue).GetHashCode(); case CorElementType.I4: return (*(int*)pValue).GetHashCode(); case CorElementType.U4: return (*(uint*)pValue).GetHashCode(); case CorElementType.R4: return (*(float*)pValue).GetHashCode(); case CorElementType.I8: return (*(long*)pValue).GetHashCode(); case CorElementType.U8: return (*(ulong*)pValue).GetHashCode(); case CorElementType.R8: return (*(double*)pValue).GetHashCode(); case CorElementType.I: return (*(IntPtr*)pValue).GetHashCode(); case CorElementType.U: return (*(UIntPtr*)pValue).GetHashCode(); default: Debug.Assert(false, "Invalid primitive type"); return 0; } } } public override String ToString() { // Returns the value in a human readable format. For PASCAL style enums who's value maps directly the name of the field is returned. // For PASCAL style enums who's values do not map directly the decimal value of the field is returned. // For BitFlags (indicated by the Flags custom attribute): If for each bit that is set in the value there is a corresponding constant //(a pure power of 2), then the OR string (ie "Red | Yellow") is returned. Otherwise, if the value is zero or if you can't create a string that consists of // pure powers of 2 OR-ed together, you return a hex value // Try to see if its one of the enum values, then we return a String back else the value return Enum.InternalFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString(); } #endregion #region IFormattable [Obsolete("The provider argument is not used. Please use ToString(String).")] public String ToString(String format, IFormatProvider provider) { return ToString(format); } #endregion #region IComparable public int CompareTo(Object target) { const int retIncompatibleMethodTables = 2; // indicates that the method tables did not match const int retInvalidEnumType = 3; // indicates that the enum was of an unknown/unsupported underlying type if (this == null) throw new NullReferenceException(); Contract.EndContractBlock(); int ret = InternalCompareTo(this, target); if (ret < retIncompatibleMethodTables) { // -1, 0 and 1 are the normal return codes return ret; } else if (ret == retIncompatibleMethodTables) { Type thisType = this.GetType(); Type targetType = target.GetType(); throw new ArgumentException(SR.Format(SR.Arg_EnumAndObjectMustBeSameType, targetType.ToString(), thisType.ToString())); } else { // assert valid return code (3) Debug.Assert(ret == retInvalidEnumType, "Enum.InternalCompareTo return code was invalid"); throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } #endregion #region Public Methods public String ToString(String format) { char formatCh; if (format == null || format.Length == 0) formatCh = 'G'; else if (format.Length != 1) throw new FormatException(SR.Format_InvalidEnumFormatSpecification); else formatCh = format[0]; if (formatCh == 'G' || formatCh == 'g') return ToString(); if (formatCh == 'D' || formatCh == 'd') return GetValue().ToString(); if (formatCh == 'X' || formatCh == 'x') return InternalFormattedHexString(); if (formatCh == 'F' || formatCh == 'f') return InternalFlagsFormat((RuntimeType)GetType(), ToUInt64()) ?? GetValue().ToString(); throw new FormatException(SR.Format_InvalidEnumFormatSpecification); } [Obsolete("The provider argument is not used. Please use ToString().")] public String ToString(IFormatProvider provider) { return ToString(); } [Intrinsic] public Boolean HasFlag(Enum flag) { if (flag == null) throw new ArgumentNullException(nameof(flag)); Contract.EndContractBlock(); if (!this.GetType().IsEquivalentTo(flag.GetType())) { throw new ArgumentException(SR.Format(SR.Argument_EnumTypeDoesNotMatch, flag.GetType(), this.GetType())); } return InternalHasFlag(flag); } #endregion #region IConvertable public TypeCode GetTypeCode() { switch (InternalGetCorElementType()) { case CorElementType.I1: return TypeCode.SByte; case CorElementType.U1: return TypeCode.Byte; case CorElementType.Boolean: return TypeCode.Boolean; case CorElementType.I2: return TypeCode.Int16; case CorElementType.U2: return TypeCode.UInt16; case CorElementType.Char: return TypeCode.Char; case CorElementType.I4: return TypeCode.Int32; case CorElementType.U4: return TypeCode.UInt32; case CorElementType.I8: return TypeCode.Int64; case CorElementType.U8: return TypeCode.UInt64; default: throw new InvalidOperationException(SR.InvalidOperation_UnknownEnumType); } } bool IConvertible.ToBoolean(IFormatProvider provider) { return Convert.ToBoolean(GetValue(), CultureInfo.CurrentCulture); } char IConvertible.ToChar(IFormatProvider provider) { return Convert.ToChar(GetValue(), CultureInfo.CurrentCulture); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(GetValue(), CultureInfo.CurrentCulture); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(GetValue(), CultureInfo.CurrentCulture); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(GetValue(), CultureInfo.CurrentCulture); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(GetValue(), CultureInfo.CurrentCulture); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(GetValue(), CultureInfo.CurrentCulture); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(GetValue(), CultureInfo.CurrentCulture); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(GetValue(), CultureInfo.CurrentCulture); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(GetValue(), CultureInfo.CurrentCulture); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(GetValue(), CultureInfo.CurrentCulture); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(GetValue(), CultureInfo.CurrentCulture); } Decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(GetValue(), CultureInfo.CurrentCulture); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Enum", "DateTime")); } Object IConvertible.ToType(Type type, IFormatProvider provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #endregion #region ToObject [CLSCompliant(false)] public static Object ToObject(Type enumType, sbyte value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } public static Object ToObject(Type enumType, short value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } public static Object ToObject(Type enumType, int value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } public static Object ToObject(Type enumType, byte value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } [CLSCompliant(false)] public static Object ToObject(Type enumType, ushort value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } [CLSCompliant(false)] public static Object ToObject(Type enumType, uint value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } public static Object ToObject(Type enumType, long value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } [CLSCompliant(false)] public static Object ToObject(Type enumType, ulong value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, unchecked((long)value)); } private static Object ToObject(Type enumType, char value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value); } private static Object ToObject(Type enumType, bool value) { if (enumType == null) throw new ArgumentNullException(nameof(enumType)); if (!enumType.IsEnum) throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); Contract.EndContractBlock(); RuntimeType rtType = enumType as RuntimeType; if (rtType == null) throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); return InternalBoxEnum(rtType, value ? 1 : 0); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Security.Permissions; using System.Security.Policy; namespace System.Runtime.InteropServices { [GuidAttribute("BEBB2505-8B54-3443-AEAD-142A16DD9CC7")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.AssemblyBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _AssemblyBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("ED3E4384-D7E2-3FA7-8FFD-8940D330519A")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ConstructorBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _ConstructorBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("BE9ACCE8-AAFF-3B91-81AE-8211663F5CAD")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.CustomAttributeBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _CustomAttributeBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("C7BD73DE-9F85-3290-88EE-090B8BDFE2DF")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EnumBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _EnumBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("AADABA99-895D-3D65-9760-B1F12621FAE8")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.EventBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _EventBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("CE1A3BF5-975E-30CC-97C9-1EF70F8F3993")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.FieldBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _FieldBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("A4924B27-6E3B-37F7-9B83-A4501955E6A7")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ILGenerator))] [System.Runtime.InteropServices.ComVisible(true)] public interface _ILGenerator { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("4E6350D1-A08B-3DEC-9A3E-C465F9AEEC0C")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.LocalBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _LocalBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("007D8A14-FDF3-363E-9A0B-FEC0618260A2")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } #if FEATURE_METHOD_RENTAL [GuidAttribute("C2323C25-F57F-3880-8A4D-12EBEA7A5852")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.MethodRental))] [System.Runtime.InteropServices.ComVisible(true)] public interface _MethodRental { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } #endif [GuidAttribute("D05FFA9A-04AF-3519-8EE1-8D93AD73430B")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ModuleBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _ModuleBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("36329EBA-F97A-3565-BC07-0ED5C6EF19FC")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.ParameterBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _ParameterBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("15F9A479-9397-3A63-ACBD-F51977FB0F02")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.PropertyBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _PropertyBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("7D13DD37-5A04-393C-BBCA-A5FEA802893D")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.SignatureHelper))] [System.Runtime.InteropServices.ComVisible(true)] public interface _SignatureHelper { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } [GuidAttribute("7E5678EE-48B3-3F83-B076-C58543498A58")] [InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown)] [CLSCompliant(false)] [TypeLibImportClassAttribute(typeof(System.Reflection.Emit.TypeBuilder))] [System.Runtime.InteropServices.ComVisible(true)] public interface _TypeBuilder { #if !FEATURE_CORECLR void GetTypeInfoCount(out uint pcTInfo); void GetTypeInfo(uint iTInfo, uint lcid, IntPtr ppTInfo); void GetIDsOfNames([In] ref Guid riid, IntPtr rgszNames, uint cNames, uint lcid, IntPtr rgDispId); void Invoke(uint dispIdMember, [In] ref Guid riid, uint lcid, short wFlags, IntPtr pDispParams, IntPtr pVarResult, IntPtr pExcepInfo, IntPtr puArgErr); #endif } }
// Copyright 2004-2008 Castle Project - http://www.castleproject.org/ // // 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; namespace BoC.Logging { /// <summary> /// Supporting Logger levels. /// </summary> public enum LoggerLevel { /// <summary> /// Logging will be off /// </summary> Off = 0, /// <summary> /// Fatal logging level /// </summary> Fatal = 1, /// <summary> /// Error logging level /// </summary> Error = 2, /// <summary> /// Warn logging level /// </summary> Warn = 3, /// <summary> /// Info logging level /// </summary> Info = 4, /// <summary> /// Debug logging level /// </summary> Debug = 5, } /// <summary> /// Manages logging. /// </summary> /// <remarks> /// This is a facade for the different logging subsystems. /// It offers a simplified interface that follows IOC patterns /// and a simplified priority/level/severity abstraction. /// </remarks> public interface ILogger { IDisposable Stack(string name); #region Debug /// <summary> /// Logs a debug message. /// </summary> /// <param name="message">The message to log</param> void Debug(String message); /// <summary> /// Logs a debug message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="message">The message to log</param> void Debug(String message, Exception exception); /// <summary> /// Logs a debug message. /// </summary> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void DebugFormat(String format, params Object[] args); /// <summary> /// Logs a debug message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void DebugFormat(Exception exception, String format, params Object[] args); /// <summary> /// Logs a debug message. /// </summary> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void DebugFormat(IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Logs a debug message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void DebugFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Determines if messages of priority "debug" will be logged. /// </summary> /// <value>True if "debug" messages will be logged.</value> bool IsDebugEnabled { get; } #endregion #region Info /// <summary> /// Logs an info message. /// </summary> /// <param name="message">The message to log</param> void Info(String message); /// <summary> /// Logs an info message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="message">The message to log</param> void Info(String message, Exception exception); /// <summary> /// Logs an info message. /// </summary> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void InfoFormat(String format, params Object[] args); /// <summary> /// Logs an info message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void InfoFormat(Exception exception, String format, params Object[] args); /// <summary> /// Logs an info message. /// </summary> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void InfoFormat(IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Logs an info message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void InfoFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Determines if messages of priority "info" will be logged. /// </summary> /// <value>True if "info" messages will be logged.</value> bool IsInfoEnabled { get; } #endregion #region Warn /// <summary> /// Logs a warn message. /// </summary> /// <param name="message">The message to log</param> void Warn(String message); /// <summary> /// Logs a warn message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="message">The message to log</param> void Warn(String message, Exception exception); /// <summary> /// Logs a warn message. /// </summary> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void WarnFormat(String format, params Object[] args); /// <summary> /// Logs a warn message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void WarnFormat(Exception exception, String format, params Object[] args); /// <summary> /// Logs a warn message. /// </summary> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void WarnFormat(IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Determines if messages of priority "warn" will be logged. /// </summary> /// <value>True if "warn" messages will be logged.</value> bool IsWarnEnabled { get; } #endregion #region Error /// <summary> /// Logs an error message. /// </summary> /// <param name="message">The message to log</param> void Error(String message); /// <summary> /// Logs an error message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="message">The message to log</param> void Error(String message, Exception exception); /// <summary> /// Logs an error message. /// </summary> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void ErrorFormat(String format, params Object[] args); /// <summary> /// Logs an error message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void ErrorFormat(Exception exception, String format, params Object[] args); /// <summary> /// Logs an error message. /// </summary> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void ErrorFormat(IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Logs an error message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void ErrorFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Determines if messages of priority "error" will be logged. /// </summary> /// <value>True if "error" messages will be logged.</value> bool IsErrorEnabled { get; } #endregion #region Fatal /// <summary> /// Logs a fatal message. /// </summary> /// <param name="message">The message to log</param> void Fatal(String message); /// <summary> /// Logs a fatal message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="message">The message to log</param> void Fatal(String message, Exception exception); /// <summary> /// Logs a fatal message. /// </summary> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void FatalFormat(String format, params Object[] args); /// <summary> /// Logs a fatal message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void FatalFormat(Exception exception, String format, params Object[] args); /// <summary> /// Logs a fatal message. /// </summary> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void FatalFormat(IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Logs a fatal message. /// </summary> /// <param name="exception">The exception to log</param> /// <param name="formatProvider">The format provider to use</param> /// <param name="format">Format string for the message to log</param> /// <param name="args">Format arguments for the message to log</param> void FatalFormat(Exception exception, IFormatProvider formatProvider, String format, params Object[] args); /// <summary> /// Determines if messages of priority "fatal" will be logged. /// </summary> /// <value>True if "fatal" messages will be logged.</value> bool IsFatalEnabled { get; } #endregion } }
using UnityEngine; using System.Collections; public class InstantGuiElement : MonoBehaviour { class TextParams { bool enabled; //Color color = new Color(1,1,1,1); float size; Vector2 offset; } //element position public InstantGuiElementPos parentpos = new InstantGuiElementPos(0,Screen.width,0,Screen.height); public InstantGuiElementPos relative = new InstantGuiElementPos(50,50,50,50); public InstantGuiElementPos offset = new InstantGuiElementPos(-20,20,-20,20); public InstantGuiElementPos absolute = new InstantGuiElementPos(-20,20,-20,20); public float layerOffset = 1; public bool lockPosition = false; private InstantGuiElementPos oldParentpos = new InstantGuiElementPos(0,0,0,0); private InstantGuiElementPos oldRelative = new InstantGuiElementPos(0,0,0,0); private InstantGuiElementPos oldOffset = new InstantGuiElementPos(0,0,0,0); //active element params public bool dynamic = true; //only dynamic elements could be on hover (ie selected in game AND in editor) public bool editable = true; //could be selected in editor public bool pointed; public bool pointedOnBackground; public float pointedTime; //how much time this element is under cursor. Increment on pointed, resets when element becomes not pointed public float unpointedTime; //how much time this element is not under cursor public bool disabled; public bool activated = false; //user pressed button and released the mouse on it. Activates for 1 frame only. Could be activated in editor public bool pressed = false; //user is holding mouse pressed above button public bool check = false; public bool instant = true; //activated right after pressing. Otherwise activated on mouse up public bool password = false; //text is displayed in dots private bool holdingPressed = false; //for pressing only protected float pointedBlend = 0; //text params public string text = ""; public GUITexture mainGuiTexture; //accessable with style public GUITexture blendGuiTexture; public GUIText[] guiTexts; public Material textMaterial; public Material textEffectMaterial; public InstantGuiStyleSet styleSet; public bool customStyle; public string styleName = ""; //to find style in styleset after scene loading public InstantGuiStyle style; private SubStyle currentSubStyle; public Font currentFont; public bool forceAlign = false; public System.Collections.Generic.List<InstantGuiElement> childElements = new System.Collections.Generic.List<InstantGuiElement>(); public System.Collections.Generic.List<Transform> childTfms = new System.Collections.Generic.List<Transform>(); public System.Collections.Generic.List<bool> childTfmsActive = new System.Collections.Generic.List<bool>(); public bool deleteChildren; public bool guiLinkText = true; public bool guiEditor; public bool guiStyle = true; public bool guiPosition; public bool guiAttributes; public bool guiElementProps; public enum InstantGuiElementType { none, button, text, toggle, slider, list, enumPopup, gauge, window }; public InstantGuiElementType guiType; public bool useStylePlacement; static public InstantGuiElement Create ( string name , System.Type type , InstantGuiElement parent ){ return Create(name, name, type, parent); } static public InstantGuiElement Create ( string name , string style , System.Type type , InstantGuiElement parent ){ //finding gui parent if (InstantGui.instance==null) InstantGui.instance = (InstantGui)FindObjectOfType(typeof(InstantGui)); if (InstantGui.instance==null) { InstantGui.CreateRoot(); parent = InstantGui.instance.element; } GameObject obj = new GameObject (name); //the object component will be assigned to //adding component InstantGuiElement element = (InstantGuiElement)obj.AddComponent(type); //parenting and setting styleset if (parent!=null) { element.transform.parent = parent.transform; element.styleSet = parent.styleSet; //do not assign parent to element! It will get it automaticly } //resetting transform if (obj.transform.parent!=null) obj.transform.localPosition = new Vector3(0,0,obj.transform.parent.localPosition.z + 1); else obj.transform.localPosition = new Vector3(0,0,0); obj.transform.localScale = new Vector3(0,0,1); //setting style element.styleName = style; if (element.styleSet!=null) for (int i=0; i<element.styleSet.styles.Length; i++) if (element.styleSet.styles[i].name == element.styleName) element.style = element.styleSet.styles[i]; //setting default size if (element.style!=null) { element.relative.Set(element.style.relative); element.offset.Set(element.style.offset); element.layerOffset = element.style.layerOffset; } //pureGui.Update(); return element; } public void CheckChildren () { //init root gui if (!InstantGui.instance) InstantGui.instance = (InstantGui)GameObject.FindObjectOfType(typeof(InstantGui)); if (!InstantGui.instance.element) InstantGui.instance.element = InstantGui.instance.GetComponent<InstantGuiElement>(); //checking children if (childTfms.Count != transform.childCount || childTfmsActive.Count != transform.childCount) { InstantGui.instance.element.GetChildren(); return; } for (int i=0; i<transform.childCount; i++) { Transform childTfm = transform.GetChild(i); if (childTfm.gameObject.activeInHierarchy != childTfmsActive[i]) { InstantGui.instance.element.GetChildren(); return; } if (childTfm != childTfms[i]) { InstantGui.instance.element.GetChildren(); return; } } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].CheckChildren(); } public void GetChildren () { childElements.Clear(); childTfms.Clear(); childTfmsActive.Clear(); InstantGuiElement childElement; for (int i=0; i<transform.childCount; i++) { Transform childTfm = transform.GetChild(i); childTfmsActive.Add(childTfm.gameObject.activeInHierarchy); childTfms.Add(childTfm); if (!childTfm.gameObject.activeInHierarchy) continue; childElement = childTfm.GetComponent<InstantGuiElement>(); if (childElement!=null) childElements.Add(childElement); } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].GetChildren(); } public virtual void Align () { if (!this) return; //element could be deleted to this time! //assigning vars if they do not exist if (guiTexts == null) guiTexts = new GUIText[0]; //using style position if (styleSet!=null && useStylePlacement) { //if (style==null) style = styleSet.FindStyle(styleName, styleNum); if (style!=null) { relative.Set(style.relative); offset.Set(style.offset); } } else { if (relative.isStyle) relative = new InstantGuiElementPos(relative); if (offset.isStyle) offset = new InstantGuiElementPos(offset); } //setting layer Transform parentTfm= transform.parent; if (parentTfm != null) { Vector3 localPos = parentTfm.localPosition; localPos.z += layerOffset; transform.localPosition = localPos;} //refreshing parent absolute pos InstantGuiElement parentElement = null; if (parentTfm!=null) parentElement = parentTfm.GetComponent<InstantGuiElement>(); if (parentElement!=null) parentpos = parentElement.absolute; else //parentpos = InstantGuiElementPos(0,Screen.width,0,Screen.height); { if (InstantGui.instance == null) InstantGui.instance = (InstantGui)FindObjectOfType(typeof(InstantGui)); parentpos = new InstantGuiElementPos(0,InstantGui.width,0,InstantGui.height); } //checking if there is a need to re-allign if (!InstantGuiElementPos.Equals(parentpos, oldParentpos) || !InstantGuiElementPos.Equals(relative, oldRelative) || !InstantGuiElementPos.Equals(offset, oldOffset) || InstantGui.oldScreenWidth != Screen.width || InstantGui.oldScreenHeight != Screen.height || true) { //transforming relative pos to absolute //if (!absolute || !parentpos || !relative || !offset) return; absolute.GetAbsolute(parentpos, relative, offset); //setting fixed size (if on) if (style!=null) { if (style.fixedWidth) absolute.right = absolute.left+style.fixedWidthSize; if (style.fixedHeight) absolute.bottom = absolute.top+style.fixedHeightSize; } //preventing negative size int minWidth = 10; int minHeight = 10; if (style!=null) { minWidth = style.borders.left + style.borders.right; minHeight = style.borders.bottom + style.borders.top; } if (absolute.right < absolute.left+minWidth) absolute.right = absolute.left+minWidth; if (absolute.bottom < absolute.top+minHeight) absolute.bottom = absolute.top+minHeight; //writing compare-data oldParentpos = new InstantGuiElementPos(parentpos); oldRelative = new InstantGuiElementPos(relative); oldOffset = new InstantGuiElementPos(offset); } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].Align(); } public void PreventZeroSize ( bool noReturn ) //called from frame only { int minWidth = 10; int minHeight = 10; if (style!=null) { minWidth = style.borders.left + style.borders.right; minHeight = style.borders.bottom + style.borders.top; } if (noReturn) { if (absolute.right - absolute.left < minWidth && absolute.bottom - absolute.top < minHeight) offset.GetOffset(parentpos, relative, new InstantGuiElementPos(absolute.left, absolute.left + minWidth, absolute.top, absolute.top + minHeight)); else if (absolute.right - absolute.left < minWidth) offset.GetOffset(parentpos, relative, new InstantGuiElementPos(absolute.left, absolute.left + minWidth, absolute.top, absolute.bottom)); else if (absolute.bottom - absolute.top < minHeight) offset.GetOffset(parentpos, relative, new InstantGuiElementPos(absolute.left, absolute.right, absolute.top, absolute.top + minHeight)); } else { if (absolute.right - absolute.left < minWidth) absolute.right = absolute.left + minWidth; if (absolute.bottom - absolute.top < minHeight) absolute.bottom = absolute.top + minHeight; } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].PreventZeroSize(false); } //void Point (){ Point (Input.mousePosition); } public void Point (){ Point (false); } public void Point ( bool isEditor ) //special point variant with custom mouseposition for editor. { //getting mouse pos Vector2 mousePos; if (isEditor) { mousePos = Event.current.mousePosition; mousePos.y = InstantGui.Invert(mousePos.y); } else mousePos = Input.mousePosition; pointed = false; //resetting isPointed to all elements pointedOnBackground = false; //getting point offset int leftPointOffset=0; int rightPointOffset=0; int topPointOffset=0; int bottomPointOffset=0; if (style!=null) { leftPointOffset = style.pointOffset.left; rightPointOffset = style.pointOffset.right; topPointOffset = style.pointOffset.top; bottomPointOffset = style.pointOffset.bottom; } if (dynamic && (editable || !isEditor) && mousePos.x >= absolute.left - leftPointOffset && mousePos.x <= absolute.right - rightPointOffset && InstantGui.Invert(mousePos.y) >= absolute.top - topPointOffset && InstantGui.Invert(mousePos.y) <= absolute.bottom - bottomPointOffset) { pointedOnBackground = true; if (!InstantGui.pointed || transform.localPosition.z > InstantGui.pointed.transform.localPosition.z) { if (InstantGui.pointed!=null) InstantGui.pointed.pointed = false; //resetting isHover to old hover element previously assigned this frame pointed = true; //assignin new hover element if (InstantGui.pointed != this) InstantGui.pointed = this; } } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].Point(isEditor); } public virtual void Action () { //resetting activation state - element could be activated for one frame only activated = false; //mouse pressed action if (!disabled) { //pressing mouse if (pointed && Input.GetMouseButtonDown(0)) { pressed = true; holdingPressed = true; if (instant) activated = true; } //holding mouse //if (Input.GetMouseButton(0) && holdingPressed) pressed = pointed; //releasing mouse if (Input.GetMouseButtonUp(0) && holdingPressed) { pressed = false; holdingPressed = false; if (pointed && !instant) activated = true; } //alt-pressing in editor #if UNITY_EDITOR if (pointed && !UnityEditor.EditorApplication.isPlayingOrWillChangePlaymode && Event.current != null && Event.current.isMouse && Event.current.button == 0 && Event.current.alt && Event.current.type == EventType.MouseDown) activated = true; #endif } //calculating pointed and unpointed times if (pointed) { pointedTime += Time.deltaTime; unpointedTime = 0; } else { unpointedTime += Time.deltaTime; pointedTime = 0; } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].Action(); } public virtual void ApplyStyle () //re-written { //trying to load style if styleSet assigned (usually after scene loading) if (!customStyle && styleSet!=null) { style = styleSet.FindStyle(styleName); } //clearing if no style assigned if (style==null) InstantGuiStyle.Clear(this); else { //calculating style SubStyle subStyle= style.main; if (style.disabled.enabled && disabled) subStyle = style.disabled; if (style.active.enabled && (check || pressed)) subStyle = style.active; //calculating pointed blend if (style.pointed.enabled && !disabled && !pressed && !check) { if (pointed) pointedBlend = Mathf.Min(pointedBlend + Time.deltaTime*style.blendSpeed, 1); else pointedBlend = Mathf.Max(pointedBlend - Time.deltaTime*style.blendSpeed, 0); //setting pointed time and blend to zero if in editor #if UNITY_EDITOR if (!UnityEditor.EditorApplication.isPlaying) { pointedTime = 0; unpointedTime = 0; pointedBlend = 0; } #endif } //apply style if (pointedBlend < 0.001f || disabled || pressed || check) { style.Unblend(this); style.Apply(subStyle, this); } else if (pointedBlend > 0.999f) { style.Unblend(this); style.Apply(style.pointed, this); } else //blended { style.Apply(subStyle, this); style.Blend(style.pointed, this, pointedBlend); } } //recursive for (int i=0; i<childElements.Count; i++) childElements[i].ApplyStyle(); } public IEnumerator YieldAndDestroy () { #if UNITY_EDITOR UnityEditor.Selection.activeGameObject = null; #endif yield return null; DestroyImmediate(gameObject); } }
using UnityEngine; using UnityEditor; using System.Collections; using System.Collections.Generic; namespace Igor { public class ListWindow<ManagerType, ListType> : EditorWindow where ManagerType : ManagerList<ListType> where ListType : XMLSerializable, new() { static ListWindow() { EditorTypeUtils.RegisterEditorTypes(); } protected Vector2 ItemScrollPosition = new Vector2(0.0f, 0.0f); protected List<ListItem<ListType>> ListItems = new List<ListItem<ListType>>(); protected bool bWindowHasFocus = false; protected bool bHasRunFirstRebuild = false; protected int RepaintDelay = 20; public virtual ManagerType GetManager() { return null; } public virtual void Initialize() { RebuildList(); } protected virtual void Update() { if(EditorApplication.isCompiling) { bHasRunFirstRebuild = false; } ConditionalRepaint(); } protected virtual void ConditionalRepaint() { if(--RepaintDelay == 0) { // RebuildList(); Repaint(); RepaintDelay = 20; } } protected virtual string GetAddButtonText() { return "Add item"; } protected virtual string GetRemoveButtonText() { if(GetSelectionCount() > 1) { return "Remove items"; } else { return "Remove item"; } } protected virtual ListItem<ListType> CreateNewItem(int IndexToWatch) { return null; } protected virtual void AddNewItem() { ListItems.Add(CreateNewItem(-1)); } protected virtual void OnGUI() { if(EditorApplication.isCompiling) { EditorGUILayout.LabelField("Igor is waiting for Unity to finish recompiling!"); } else { try { InputState.Update(this, Vector2.zero); DrawItems(); // This needs to happen second so clicking on the button doesn't invalidate the selection. CheckForMouseEvents(); CheckForKeyboardEvents(); } catch(System.Exception e) { Debug.Log("ListWindow threw an exception in OnGUI() - " + e.ToString()); } } } protected virtual void OnFocus() { bWindowHasFocus = true; } protected virtual void OnLostFocus() { bWindowHasFocus = false; } public virtual bool HasFocus() { return bWindowHasFocus; } public virtual void UpdateSingleSelect(ListItem<ListType> ItemToUpdate, bool bIsSelected) { for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { if(ListItems[CurrentItem] != ItemToUpdate) { ListItems[CurrentItem].ManagerSetSelected(false); } } ItemToUpdate.ManagerSetSelected(bIsSelected); } public virtual void UpdateMultiSelect(ListItem<ListType> ItemToUpdate, bool bIsSelected) { ItemToUpdate.ManagerSetSelected(bIsSelected); } public virtual void ClearSelection() { for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { ListItems[CurrentItem].ManagerSetSelected(false); } Selection.activeObject = null; } public virtual void SetAllToViewMode() { for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { ListItems[CurrentItem].SetIsInEditMode(false); } } public virtual void CheckForMouseEvents() { if(!bWindowHasFocus) { return; } Vector2 ClickPosition = InputState.GetLocalMousePosition(this, new Vector2(0.0f, 40.0f)); bool bHandleClick = false; InputState.MouseButton ButtonType = InputState.MouseButton.Mouse_Left; if(Event.current.type == EventType.MouseDrag) { for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { if(ListItems[CurrentItem].IsWithinBounds(ClickPosition) && !ListItems[CurrentItem].IsInEditMode()) { DragAndDrop.PrepareStartDrag(); List<string> Paths = new List<string>(); Paths.Add(ListItems[CurrentItem].GetDragAndDropText()); DragAndDrop.paths = Paths.ToArray(); DragAndDrop.StartDrag(ListItems[CurrentItem].GetDisplayText()); Event.current.Use(); } } } else if(!InputState.IsMouseButtonDown(InputState.MouseButton.Mouse_Left) && !InputState.WasLastMouseUpHandled(this, InputState.MouseButton.Mouse_Left)) { bHandleClick = true; ButtonType = InputState.MouseButton.Mouse_Left; } else if(!InputState.IsMouseButtonDown(InputState.MouseButton.Mouse_Right) && !InputState.WasLastMouseUpHandled(this, InputState.MouseButton.Mouse_Right)) { bHandleClick = true; ButtonType = InputState.MouseButton.Mouse_Right; } if(bHandleClick) { bool bCtrl = InputState.IsModifierDown(InputState.ModifierKeys.Key_Control); bool bShift = InputState.IsModifierDown(InputState.ModifierKeys.Key_Shift); bool bDoubleClick = InputState.WasLastClickDoubleClick(ButtonType); bool bClickHandled = false; for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { if(ListItems[CurrentItem].IsWithinBounds(ClickPosition)) { bClickHandled = true; if(ListItems[CurrentItem].HandleMouseClick(ClickPosition, ButtonType, bCtrl, bShift, bDoubleClick)) { GUIUtility.keyboardControl = 0; InputState.HandledMouseUp(ButtonType); if(bDoubleClick) { InputState.HandledDoubleClick(ButtonType); } break; } } } if(!bClickHandled) { if(ButtonType == InputState.MouseButton.Mouse_Left) { ClearSelection(); SetAllToViewMode(); } else if(ButtonType == InputState.MouseButton.Mouse_Right) { ShowNoSelectionContextMenu(); } } } } public virtual void CheckForKeyboardEvents() { if(!bWindowHasFocus) { return; } KeyCode RenameKeycode = KeyCode.Return; #if UNITY_EDITOR_WIN RenameKeycode = KeyCode.F2; #endif // UNITY_EDITOR_WIN if(InputState.IsKeyDown(RenameKeycode)) { ListItem<ListType> SingleSelection = null; foreach(ListItem<ListType> CurrentItem in ListItems) { if(CurrentItem.IsSelected()) { if(SingleSelection == null) { SingleSelection = CurrentItem; } else { SingleSelection = null; break; } } } if(SingleSelection != null && !SingleSelection.IsInEditMode()) { SingleSelection.SetIsInEditMode(true); InputState.HandleKeyDown(RenameKeycode); } } } public virtual void ShowItemContextMenu() { // These are messing with the selection code so I'm turning them off for now. /* GenericMenu GenericContextMenu = new GenericMenu(); GenericContextMenu.AddItem(new GUIContent(GetAddButtonText()), false, AddNewItem); GenericContextMenu.AddItem(new GUIContent(GetRemoveButtonText()), false, RemoveSelectedItems); GenericContextMenu.ShowAsContext();*/ } public virtual void ShowNoSelectionContextMenu() { // These are messing with the selection code so I'm turning them off for now. /* GenericMenu GenericContextMenu = new GenericMenu(); GenericContextMenu.AddItem(new GUIContent(GetAddButtonText()), false, AddNewItem); GenericContextMenu.ShowAsContext();*/ } protected virtual int GetSelectionCount() { int NumSelectedItems = 0; for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { if(ListItems[CurrentItem].IsSelected()) { ++NumSelectedItems; } } return NumSelectedItems; } protected virtual void RemoveSelectedItems() { for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { if(ListItems[CurrentItem].IsSelected()) { RemoveItemWithCompareString(ListItems[CurrentItem].GetCompareString()); ListItems.RemoveAt(CurrentItem); --CurrentItem; } } RebuildList(); } protected virtual void RemoveItemWithCompareString(string CompareString) { } protected virtual void DrawHeader() { EditorGUILayout.BeginHorizontal(); if(GUILayout.Button(GetAddButtonText())) { AddNewItem(); } if(GUILayout.Button(GetRemoveButtonText())) { RemoveSelectedItems(); } EditorGUILayout.EndHorizontal(); } protected virtual void DrawItems() { DrawHeader(); ItemScrollPosition = EditorGUILayout.BeginScrollView(ItemScrollPosition); if(!bHasRunFirstRebuild) { RebuildList(); } if(GetManager() != null) { bool bEven = true; for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { ListItems[CurrentItem].UpdateLastBounds(EditorGUILayout.BeginHorizontal(ListItems[CurrentItem].GetBackgroundGUIStyle(bEven))); DrawItem(CurrentItem); EditorGUILayout.EndHorizontal(); bEven = !bEven; } } EditorGUILayout.EndScrollView(); } protected virtual void DrawItem(int Index) { if(ListItems[Index].IsInEditMode()) { ListItems[Index].HandleNewDisplayName(GUILayout.TextField(ListItems[Index].GetDisplayText(), ListItems[Index].GetTextGUIStyle())); if(Event.current.keyCode == KeyCode.Return) { ListItems[Index].SetIsInEditMode(false); } } else { GUILayout.Label(ListItems[Index].GetDisplayText(), ListItems[Index].GetTextGUIStyle()); } } public virtual void RebuildList() { if(GetManager() != null) { bHasRunFirstRebuild = true; List<ListItem<ListType>> NewList = new List<ListItem<ListType>>(); List<int> ItemsToSkip = new List<int>(); for(int CurrentItem = 0; CurrentItem < ListItems.Count; ++CurrentItem) { if(ListItems[CurrentItem].bIsReal()) { string CurrentEditorCompareString = ListItems[CurrentItem].GetCompareString(); int ExistingIndex = GetManager().EditorHasCompareString(CurrentEditorCompareString); if(ExistingIndex > -1) { ItemsToSkip.Add(ExistingIndex); NewList.Add(ListItems[CurrentItem]); } } else { NewList.Add(ListItems[CurrentItem]); } } for(int CurrentItem = 0; CurrentItem < GetManager().EditorGetListCount(); ++CurrentItem) { if(!ItemsToSkip.Contains(CurrentItem)) { NewList.Add(CreateNewItem(CurrentItem)); } } ListItems = NewList; } ConditionalRepaint(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; using System.ComponentModel; using System.Runtime.Serialization; using System.Security.Permissions; namespace System.Management { /// <summary> /// <para>Describes the possible text formats that can be used with <see cref='System.Management.ManagementBaseObject.GetText'/>.</para> /// </summary> public enum TextFormat { /// <summary> /// Managed Object Format /// </summary> Mof = 0, /// <summary> /// XML DTD that corresponds to CIM DTD version 2.0 /// </summary> CimDtd20 = 1, /// <summary> /// XML WMI DTD that corresponds to CIM DTD version 2.0. /// Using this value enables a few WMI-specific extensions, like embedded objects. /// </summary> WmiDtd20 = 2 }; /// <summary> /// <para>Describes the possible CIM types for properties, qualifiers, or method parameters.</para> /// </summary> public enum CimType { /// <summary> /// <para>Invalid Type</para> /// </summary> None = 0, /// <summary> /// <para>A signed 8-bit integer.</para> /// </summary> SInt8 = 16, /// <summary> /// <para>An unsigned 8-bit integer.</para> /// </summary> UInt8 = 17, /// <summary> /// <para>A signed 16-bit integer.</para> /// </summary> SInt16 = 2, /// <summary> /// <para>An unsigned 16-bit integer.</para> /// </summary> UInt16 = 18, /// <summary> /// <para>A signed 32-bit integer.</para> /// </summary> SInt32 = 3, /// <summary> /// <para>An unsigned 32-bit integer.</para> /// </summary> UInt32 = 19, /// <summary> /// <para>A signed 64-bit integer.</para> /// </summary> SInt64 = 20, /// <summary> /// <para>An unsigned 64-bit integer.</para> /// </summary> UInt64 = 21, /// <summary> /// <para>A floating-point 32-bit number.</para> /// </summary> Real32 = 4, /// <summary> /// <para>A floating point 64-bit number.</para> /// </summary> Real64 = 5, /// <summary> /// <para> A boolean.</para> /// </summary> Boolean = 11, /// <summary> /// <para>A string.</para> /// </summary> String = 8, /// <summary> /// <para> A date or time value, represented in a string in DMTF /// date/time format: yyyymmddHHMMSS.mmmmmmsUUU</para> /// <para>where:</para> /// <para>yyyymmdd - is the date in year/month/day</para> /// <para>HHMMSS - is the time in hours/minutes/seconds</para> /// <para>mmmmmm - is the number of microseconds in 6 digits</para> /// <para>sUUU - is a sign (+ or -) and a 3-digit UTC offset</para> /// </summary> DateTime = 101, /// <summary> /// <para>A reference to another object. This is represented by a /// string containing the path to the referenced object</para> /// </summary> Reference = 102, /// <summary> /// <para> A 16-bit character.</para> /// </summary> Char16 = 103, /// <summary> /// <para>An embedded object.</para> /// <para>Note that embedded objects differ from references in that the embedded object /// doesn't have a path and its lifetime is identical to the lifetime of the /// containing object.</para> /// </summary> Object = 13, }; /// <summary> /// <para>Describes the object comparison modes that can be used with <see cref='System.Management.ManagementBaseObject.CompareTo'/>. /// Note that these values may be combined.</para> /// </summary> [Flags] public enum ComparisonSettings { /// <summary> /// <para>A mode that compares all elements of the compared objects.</para> /// </summary> IncludeAll = 0, /// <summary> /// <para>A mode that compares the objects, ignoring qualifiers.</para> /// </summary> IgnoreQualifiers = 0x1, /// <summary> /// <para> A mode that ignores the source of the objects, namely the server /// and the namespace they came from, in comparison to other objects.</para> /// </summary> IgnoreObjectSource = 0x2, /// <summary> /// <para> A mode that ignores the default values of properties. /// This value is only meaningful when comparing classes.</para> /// </summary> IgnoreDefaultValues = 0x4, /// <summary> /// <para>A mode that assumes that the objects being compared are instances of /// the same class. Consequently, this value causes comparison /// of instance-related information only. Use this flag to optimize /// performance. If the objects are not of the same class, the results are undefined.</para> /// </summary> IgnoreClass = 0x8, /// <summary> /// <para> A mode that compares string values in a case-insensitive /// manner. This applies to strings and to qualifier values. Property and qualifier /// names are always compared in a case-insensitive manner whether this flag is /// specified or not.</para> /// </summary> IgnoreCase = 0x10, /// <summary> /// <para>A mode that ignores qualifier flavors. This flag still takes /// qualifier values into account, but ignores flavor distinctions such as /// propagation rules and override restrictions.</para> /// </summary> IgnoreFlavor = 0x20 }; internal enum QualifierType { ObjectQualifier, PropertyQualifier, MethodQualifier } //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// /// <summary> /// <para> Contains the basic elements of a management /// object. It serves as a base class to more specific management object classes.</para> /// </summary> //CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC// [ToolboxItem(false)] public class ManagementBaseObject : Component, ICloneable, ISerializable { // This field holds onto a WbemContext for the lifetime of the appdomain. This should // prevent Fastprox.dll from unloading prematurely. // Since this is fixed in WinXP, we only hold onto a WbemContext if we are NOT running XP or later. #pragma warning disable 0414 // Kept for possible reflection, comment above for history private static WbemContext lockOnFastProx = null; // RemovedDuringPort System.Management.Instrumentation.WMICapabilities.IsWindowsXPOrHigher()?null:new WbemContext(); #pragma warning restore 0414 // // The wbemObject is changed from a field to a property. This is to avoid major code churn and simplify the solution to // the problem where the Initialize call actually binds to the object. This occured even in cases like Get() whereby we // ended up getting the object twice. Any direct usage of this property will cause a call to Initialize ( true ) to be made // (if not already done) indicating that we wish to bind to the underlying WMI object. // // See changes to Initialize // internal IWbemClassObjectFreeThreaded wbemObject { get { if (_wbemObject == null) { Initialize(true); } return _wbemObject; } set { _wbemObject = value; } } internal IWbemClassObjectFreeThreaded _wbemObject ; private PropertyDataCollection properties; private PropertyDataCollection systemProperties; private QualifierDataCollection qualifiers; /// <summary> /// <para>Initializes a new instance of the <see cref='System.Management.ManagementBaseObject'/> class that is serializable.</para> /// </summary> /// <param name='info'>The <see cref='System.Runtime.Serialization.SerializationInfo'/> to populate with data.</param> /// <param name='context'>The destination (see <see cref='System.Runtime.Serialization.StreamingContext'/> ) for this serialization.</param> protected ManagementBaseObject(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } public new void Dispose() { if (_wbemObject != null) { _wbemObject.Dispose(); _wbemObject = null; } base.Dispose(); GC.SuppressFinalize(this); } /// <summary> /// <para>Provides the internal WMI object represented by a ManagementObject.</para> /// <para>See remarks with regard to usage.</para> /// </summary> /// <param name='managementObject'>The <see cref='System.Management.ManagementBaseObject'/> that references the requested WMI object. </param> /// <returns> /// <para>An <see cref='System.IntPtr'/> representing the internal WMI object.</para> /// </returns> /// <remarks> /// <para>This operator is used internally by instrumentation code. It is not intended /// for direct use by regular client or instrumented applications.</para> /// </remarks> public static explicit operator IntPtr(ManagementBaseObject managementObject) { if(null == managementObject) return IntPtr.Zero; return (IntPtr)managementObject.wbemObject; } void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } protected virtual void GetObjectData(SerializationInfo info, StreamingContext context) { throw new PlatformNotSupportedException(); } // Factory /// <summary> /// Factory for various types of base object /// </summary> /// <param name="wbemObject"> IWbemClassObject </param> /// <param name="scope"> The scope</param> internal static ManagementBaseObject GetBaseObject( IWbemClassObjectFreeThreaded wbemObject, ManagementScope scope) { ManagementBaseObject newObject = null; if (_IsClass(wbemObject)) newObject = ManagementClass.GetManagementClass(wbemObject, scope); else newObject = ManagementObject.GetManagementObject(wbemObject, scope); return newObject; } //Constructor internal ManagementBaseObject(IWbemClassObjectFreeThreaded wbemObject) { this.wbemObject = wbemObject; properties = null; systemProperties = null; qualifiers = null; } /// <summary> /// <para>Returns a copy of the object.</para> /// </summary> /// <returns> /// <para>The new cloned object.</para> /// </returns> public virtual Object Clone() { IWbemClassObjectFreeThreaded theClone = null; int status = wbemObject.Clone_(out theClone); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return new ManagementBaseObject(theClone); } internal virtual void Initialize ( bool getObject ) {} // //Properties // /// <summary> /// <para>Gets or sets a collection of <see cref='System.Management.PropertyData'/> objects describing the properties of the /// management object.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.PropertyDataCollection'/> that represents the /// properties of the management object.</para> /// </value> /// <seealso cref='System.Management.PropertyData'/> public virtual PropertyDataCollection Properties { get { Initialize ( true ) ; if (properties == null) properties = new PropertyDataCollection(this, false); return properties; } } /// <summary> /// <para>Gets or sets the collection of WMI system properties of the management object (for example, the /// class name, server, and namespace). WMI system property names begin with /// "__".</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.PropertyDataCollection'/> that represents the system properties of the management object.</para> /// </value> /// <seealso cref='System.Management.PropertyData'/> public virtual PropertyDataCollection SystemProperties { get { Initialize ( false ) ; if (systemProperties == null) systemProperties = new PropertyDataCollection(this, true); return systemProperties; } } /// <summary> /// <para>Gets or sets the collection of <see cref='System.Management.QualifierData'/> objects defined on the management object. /// Each element in the collection holds information such as the qualifier name, /// value, and flavor.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.QualifierDataCollection'/> that represents the qualifiers /// defined on the management object.</para> /// </value> /// <seealso cref='System.Management.QualifierData'/> public virtual QualifierDataCollection Qualifiers { get { Initialize ( true ) ; if (qualifiers == null) qualifiers = new QualifierDataCollection(this); return qualifiers; } } /// <summary> /// <para>Gets or sets the path to the management object's class.</para> /// </summary> /// <value> /// <para>A <see cref='System.Management.ManagementPath'/> that represents the path to the management object's class.</para> /// </value> /// <example> /// <para>For example, for the \\MyBox\root\cimv2:Win32_LogicalDisk= /// 'C:' object, the class path is \\MyBox\root\cimv2:Win32_LogicalDisk /// .</para> /// </example> public virtual ManagementPath ClassPath { get { Object serverName = null; Object scopeName = null; Object className = null; int propertyType = 0; int propertyFlavor = 0; int status = (int)ManagementStatus.NoError; status = wbemObject.Get_("__SERVER", 0, ref serverName, ref propertyType, ref propertyFlavor); if (status == (int)ManagementStatus.NoError) { status = wbemObject.Get_("__NAMESPACE", 0, ref scopeName, ref propertyType, ref propertyFlavor); if (status == (int)ManagementStatus.NoError) status = wbemObject.Get_("__CLASS", 0, ref className, ref propertyType, ref propertyFlavor); } if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } ManagementPath classPath = new ManagementPath(); // initialize in case of throw classPath.Server = String.Empty; classPath.NamespacePath = String.Empty; classPath.ClassName = String.Empty; // Some of these may throw if they are NULL try { classPath.Server = (string)(serverName is System.DBNull ? "" : serverName); classPath.NamespacePath = (string)(scopeName is System.DBNull ? "" : scopeName); classPath.ClassName = (string)(className is System.DBNull ? "" : className); } catch { } return classPath; } } // //Methods // //****************************************************** //[] operator by property name //****************************************************** /// <summary> /// <para> Gets access to property values through [] notation.</para> /// </summary> /// <param name='propertyName'>The name of the property of interest. </param> /// <value> /// An <see cref='System.Object'/> containing the /// value of the requested property. /// </value> public Object this[string propertyName] { get { return GetPropertyValue(propertyName); } set { Initialize ( true ) ; try { SetPropertyValue (propertyName, value); } catch (COMException e) { ManagementException.ThrowWithExtendedInfo(e); } } } //****************************************************** //GetPropertyValue //****************************************************** /// <summary> /// <para>Gets an equivalent accessor to a property's value.</para> /// </summary> /// <param name='propertyName'>The name of the property of interest. </param> /// <returns> /// <para>The value of the specified property.</para> /// </returns> public Object GetPropertyValue(string propertyName) { if (null == propertyName) throw new ArgumentNullException ("propertyName"); // Check for system properties if (propertyName.StartsWith ("__", StringComparison.Ordinal)) return SystemProperties[propertyName].Value; else return Properties[propertyName].Value; } //****************************************************** //GetQualifierValue //****************************************************** /// <summary> /// <para>Gets the value of the specified qualifier.</para> /// </summary> /// <param name='qualifierName'>The name of the qualifier of interest. </param> /// <returns> /// <para>The value of the specified qualifier.</para> /// </returns> public Object GetQualifierValue(string qualifierName) { return Qualifiers [qualifierName].Value; } //****************************************************** //SetQualifierValue //****************************************************** /// <summary> /// <para>Sets the value of the named qualifier.</para> /// </summary> /// <param name='qualifierName'>The name of the qualifier to set. This parameter cannot be null.</param> /// <param name='qualifierValue'>The value to set.</param> public void SetQualifierValue(string qualifierName, object qualifierValue) { Qualifiers [qualifierName].Value = qualifierValue; } //****************************************************** //GetPropertyQualifierValue //****************************************************** /// <summary> /// <para>Returns the value of the specified property qualifier.</para> /// </summary> /// <param name='propertyName'>The name of the property to which the qualifier belongs. </param> /// <param name='qualifierName'>The name of the property qualifier of interest. </param> /// <returns> /// <para>The value of the specified qualifier.</para> /// </returns> public Object GetPropertyQualifierValue(string propertyName, string qualifierName) { return Properties[propertyName].Qualifiers[qualifierName].Value; } //****************************************************** //SetPropertyQualifierValue //****************************************************** /// <summary> /// <para>Sets the value of the specified property qualifier.</para> /// </summary> /// <param name='propertyName'>The name of the property to which the qualifier belongs.</param> /// <param name='qualifierName'>The name of the property qualifier of interest.</param> /// <param name='qualifierValue'>The new value for the qualifier.</param> public void SetPropertyQualifierValue(string propertyName, string qualifierName, object qualifierValue) { Properties[propertyName].Qualifiers[qualifierName].Value = qualifierValue; } //****************************************************** //GetText //****************************************************** /// <summary> /// <para>Returns a textual representation of the object in the specified format.</para> /// </summary> /// <param name='format'>The requested textual format. </param> /// <returns> /// <para>The textual representation of the /// object in the specified format.</para> /// </returns> public string GetText(TextFormat format) { string objText = null; int status = (int)ManagementStatus.NoError; // // Removed Initialize call since wbemObject is a property that will call Initialize ( true ) on // its getter. // switch(format) { case TextFormat.Mof : status = wbemObject.GetObjectText_(0, out objText); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return objText; case TextFormat.CimDtd20 : case TextFormat.WmiDtd20 : //This may throw on non-XP platforms... - should we catch ? IWbemObjectTextSrc wbemTextSrc = (IWbemObjectTextSrc)new WbemObjectTextSrc(); IWbemContext ctx = (IWbemContext)new WbemContext(); object v = (bool)true; ctx.SetValue_("IncludeQualifiers", 0, ref v); ctx.SetValue_("IncludeClassOrigin", 0, ref v); if (wbemTextSrc != null) { status = wbemTextSrc.GetText_(0, (IWbemClassObject_DoNotMarshal)(Marshal.GetObjectForIUnknown(wbemObject)), (uint)format, //note: this assumes the format enum has the same values as the underlying WMI enum !! ctx, out objText); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } } return objText; default : return null; } } /// <summary> /// <para>Compares two management objects.</para> /// </summary> /// <param name='obj'>An object to compare with this instance.</param> /// <returns> /// <see langword='true'/> if /// <paramref name="obj"/> is an instance of <see cref='System.Management.ManagementBaseObject'/> and represents /// the same object as this instance; otherwise, <see langword='false'/>. /// </returns> public override bool Equals(object obj) { bool result = false; try { if (obj is ManagementBaseObject) { result = CompareTo ((ManagementBaseObject)obj, ComparisonSettings.IncludeAll); } else { return false; } } catch (ManagementException exc) { if (exc.ErrorCode == ManagementStatus.NotFound) { //we could wind up here if Initialize() throws (either here or inside CompareTo()) //Since we cannot throw from Equals() imprelemtation and it is invalid to assume //that two objects are different because they fail to initialize //so, we can just compare these invalid paths "by value" if (this is ManagementObject && obj is ManagementObject) { int compareRes = String.Compare(((ManagementObject)this).Path.Path, ((ManagementObject)obj).Path.Path, StringComparison.OrdinalIgnoreCase); return (compareRes == 0); } } return false; } catch { return false; } return result; } /// <summary> /// <para>Serves as a hash function for a particular type, suitable for use in hashing algorithms and data structures like a hash table.</para> /// <para>The hash code for ManagementBaseObjects is based on the MOF for the WbemObject that this instance is based on. Two different ManagementBaseObject instances pointing to the same WbemObject in WMI will have the same mof and thus the same hash code. Changing a property value of an object will change the hash code. </para> /// </summary> /// <returns> /// <para>A hash code for the current object. </para> /// </returns> public override int GetHashCode() { //This implementation has to match the Equals() implementation. In Equals(), we use //the WMI CompareTo() which compares values of properties, qualifiers etc. //Probably the closest we can get is to take the MOF representation of the object and get it's hash code. int localHash = 0; try { // GetText may throw if it cannot get a string for the mof for various reasons // This should be a very rare event localHash = this.GetText(TextFormat.Mof).GetHashCode(); } catch (ManagementException) { // use the hash code of an empty string on failure to get the mof localHash = string.Empty.GetHashCode(); } catch (System.Runtime.InteropServices.COMException) { // use the hash code of an empty string on failure to get the mof localHash = string.Empty.GetHashCode(); } return localHash; } //****************************************************** //CompareTo //****************************************************** /// <summary> /// <para>Compares this object to another, based on specified options.</para> /// </summary> /// <param name='otherObject'>The object to which to compare this object. </param> /// <param name='settings'>Options on how to compare the objects. </param> /// <returns> /// <para><see langword='true'/> if the objects compared are equal /// according to the given options; otherwise, <see langword='false'/> /// .</para> /// </returns> public bool CompareTo(ManagementBaseObject otherObject, ComparisonSettings settings) { if (null == otherObject) throw new ArgumentNullException ("otherObject"); bool result = false; if (null != wbemObject) { int status = (int) ManagementStatus.NoError; status = wbemObject.CompareTo_((int) settings, otherObject.wbemObject); if ((int)ManagementStatus.Different == status) result = false; else if ((int)ManagementStatus.NoError == status) result = true; else if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else if (status < 0) Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return result; } internal string ClassName { get { object val = null; int dummy1 = 0, dummy2 = 0; int status = (int)ManagementStatus.NoError; status = wbemObject.Get_ ("__CLASS", 0, ref val, ref dummy1, ref dummy2); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } if (val is System.DBNull) return String.Empty; else return ((string) val); } } private static bool _IsClass(IWbemClassObjectFreeThreaded wbemObject) { object val = null; int dummy1 = 0, dummy2 = 0; int status = wbemObject.Get_("__GENUS", 0, ref val, ref dummy1, ref dummy2); if (status < 0) { if ((status & 0xfffff000) == 0x80041000) ManagementException.ThrowWithExtendedInfo((ManagementStatus)status); else Marshal.ThrowExceptionForHR(status, WmiNetUtilsHelper.GetErrorInfo_f()); } return ((int)val == (int)tag_WBEM_GENUS_TYPE.WBEM_GENUS_CLASS); } internal bool IsClass { get { return _IsClass(wbemObject); } } /// <summary> /// <para>Sets the value of the named property.</para> /// </summary> /// <param name='propertyName'>The name of the property to be changed.</param> /// <param name='propertyValue'>The new value for this property.</param> public void SetPropertyValue ( string propertyName, object propertyValue) { if (null == propertyName) throw new ArgumentNullException ("propertyName"); // Check for system properties if (propertyName.StartsWith ("__", StringComparison.Ordinal)) SystemProperties[propertyName].Value = propertyValue; else Properties[propertyName].Value = propertyValue; } }//ManagementBaseObject }
namespace nHydrate.DslPackage.Forms { partial class ImportDatabaseForm { /// <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(ImportDatabaseForm)); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.wizard1 = new nHydrate.Wizard.Wizard(); this.pageConnection = new nHydrate.Wizard.WizardPage(); this.grpConnectionStringPostgres = new System.Windows.Forms.GroupBox(); this.lblConnectionString = new System.Windows.Forms.Label(); this.txtConnectionStringPostgres = new nHydrate.Generator.Common.Forms.CueTextBox(); this.panel1 = new System.Windows.Forms.Panel(); this.optDatabaseTypePostgres = new System.Windows.Forms.RadioButton(); this.optDatabaseTypeSQL = new System.Windows.Forms.RadioButton(); this.cmdTestConnection = new System.Windows.Forms.Button(); this.DatabaseConnectionControl1 = new nHydrate.DslPackage.Forms.DatabaseConnectionControl(); this.pageSummary = new nHydrate.Wizard.WizardPage(); this.txtSummary = new FastColoredTextBoxNS.FastColoredTextBox(); this.pageEntities = new nHydrate.Wizard.WizardPage(); this.panel2 = new System.Windows.Forms.Panel(); this.chkIgnoreRelations = new System.Windows.Forms.CheckBox(); this.chkInheritance = new System.Windows.Forms.CheckBox(); this.chkSettingPK = new System.Windows.Forms.CheckBox(); this.pnlMain = new System.Windows.Forms.Panel(); this.cmdViewDiff = new System.Windows.Forms.Button(); this.tabControl1 = new System.Windows.Forms.TabControl(); this.tabPage1 = new System.Windows.Forms.TabPage(); this.tvwAdd = new System.Windows.Forms.TreeView(); this.tabPage2 = new System.Windows.Forms.TabPage(); this.tvwRefresh = new System.Windows.Forms.TreeView(); this.tabPage3 = new System.Windows.Forms.TabPage(); this.tvwDelete = new System.Windows.Forms.TreeView(); this.wizard1.SuspendLayout(); this.pageConnection.SuspendLayout(); this.grpConnectionStringPostgres.SuspendLayout(); this.panel1.SuspendLayout(); this.pageSummary.SuspendLayout(); this.pageEntities.SuspendLayout(); this.panel2.SuspendLayout(); this.pnlMain.SuspendLayout(); this.tabControl1.SuspendLayout(); this.tabPage1.SuspendLayout(); this.tabPage2.SuspendLayout(); this.tabPage3.SuspendLayout(); this.SuspendLayout(); // // imageList1 // this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream"))); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; this.imageList1.Images.SetKeyName(0, "import_table_header.png"); this.imageList1.Images.SetKeyName(1, "import_view_header.png"); this.imageList1.Images.SetKeyName(2, "import_storedprocedure_header.png"); this.imageList1.Images.SetKeyName(3, "import_table.png"); this.imageList1.Images.SetKeyName(4, "import_view.png"); this.imageList1.Images.SetKeyName(5, "import_storedprocedure.png"); // // wizard1 // this.wizard1.ButtonFlatStyle = System.Windows.Forms.FlatStyle.Standard; this.wizard1.Controls.Add(this.pageEntities); this.wizard1.Controls.Add(this.pageConnection); this.wizard1.Controls.Add(this.pageSummary); this.wizard1.HeaderImage = ((System.Drawing.Image)(resources.GetObject("wizard1.HeaderImage"))); this.wizard1.Location = new System.Drawing.Point(0, 0); this.wizard1.Name = "wizard1"; this.wizard1.Size = new System.Drawing.Size(653, 543); this.wizard1.TabIndex = 74; this.wizard1.WizardPages.AddRange(new nHydrate.Wizard.WizardPage[] { this.pageConnection, this.pageEntities, this.pageSummary}); // // pageConnection // this.pageConnection.Controls.Add(this.grpConnectionStringPostgres); this.pageConnection.Controls.Add(this.panel1); this.pageConnection.Controls.Add(this.cmdTestConnection); this.pageConnection.Controls.Add(this.DatabaseConnectionControl1); this.pageConnection.Description = "Specify your database connection information."; this.pageConnection.Location = new System.Drawing.Point(0, 0); this.pageConnection.Name = "pageConnection"; this.pageConnection.Size = new System.Drawing.Size(653, 495); this.pageConnection.TabIndex = 7; this.pageConnection.Title = "Database Connection"; // // grpConnectionStringPostgres // this.grpConnectionStringPostgres.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.grpConnectionStringPostgres.Controls.Add(this.lblConnectionString); this.grpConnectionStringPostgres.Controls.Add(this.txtConnectionStringPostgres); this.grpConnectionStringPostgres.Location = new System.Drawing.Point(12, 396); this.grpConnectionStringPostgres.Name = "grpConnectionStringPostgres"; this.grpConnectionStringPostgres.Size = new System.Drawing.Size(619, 57); this.grpConnectionStringPostgres.TabIndex = 82; this.grpConnectionStringPostgres.TabStop = false; this.grpConnectionStringPostgres.Visible = false; // // lblConnectionString // this.lblConnectionString.AutoSize = true; this.lblConnectionString.Location = new System.Drawing.Point(19, 27); this.lblConnectionString.Name = "lblConnectionString"; this.lblConnectionString.Size = new System.Drawing.Size(112, 13); this.lblConnectionString.TabIndex = 5; this.lblConnectionString.Text = "Database connection:"; // // txtConnectionStringPostgres // this.txtConnectionStringPostgres.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtConnectionStringPostgres.Cue = "<Enter Connectionstring>"; this.txtConnectionStringPostgres.Location = new System.Drawing.Point(136, 24); this.txtConnectionStringPostgres.Name = "txtConnectionStringPostgres"; this.txtConnectionStringPostgres.Size = new System.Drawing.Size(469, 20); this.txtConnectionStringPostgres.TabIndex = 8; // // panel1 // this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.panel1.Controls.Add(this.optDatabaseTypePostgres); this.panel1.Controls.Add(this.optDatabaseTypeSQL); this.panel1.Location = new System.Drawing.Point(12, 67); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(619, 52); this.panel1.TabIndex = 81; // // optDatabaseTypePostgres // this.optDatabaseTypePostgres.AutoSize = true; this.optDatabaseTypePostgres.Location = new System.Drawing.Point(157, 13); this.optDatabaseTypePostgres.Name = "optDatabaseTypePostgres"; this.optDatabaseTypePostgres.Size = new System.Drawing.Size(66, 17); this.optDatabaseTypePostgres.TabIndex = 0; this.optDatabaseTypePostgres.Text = "Postgres"; this.optDatabaseTypePostgres.UseVisualStyleBackColor = true; // // optDatabaseTypeSQL // this.optDatabaseTypeSQL.AutoSize = true; this.optDatabaseTypeSQL.Checked = true; this.optDatabaseTypeSQL.Location = new System.Drawing.Point(17, 13); this.optDatabaseTypeSQL.Name = "optDatabaseTypeSQL"; this.optDatabaseTypeSQL.Size = new System.Drawing.Size(80, 17); this.optDatabaseTypeSQL.TabIndex = 0; this.optDatabaseTypeSQL.TabStop = true; this.optDatabaseTypeSQL.Text = "SQL Server"; this.optDatabaseTypeSQL.UseVisualStyleBackColor = true; // // cmdTestConnection // this.cmdTestConnection.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.cmdTestConnection.Location = new System.Drawing.Point(501, 459); this.cmdTestConnection.Name = "cmdTestConnection"; this.cmdTestConnection.Size = new System.Drawing.Size(130, 23); this.cmdTestConnection.TabIndex = 80; this.cmdTestConnection.Text = "Test Connection"; this.cmdTestConnection.UseVisualStyleBackColor = true; // // DatabaseConnectionControl1 // this.DatabaseConnectionControl1.AutoSize = true; this.DatabaseConnectionControl1.FileName = ""; this.DatabaseConnectionControl1.Location = new System.Drawing.Point(12, 125); this.DatabaseConnectionControl1.Name = "DatabaseConnectionControl1"; this.DatabaseConnectionControl1.Size = new System.Drawing.Size(619, 269); this.DatabaseConnectionControl1.TabIndex = 76; // // pageSummary // this.pageSummary.Controls.Add(this.txtSummary); this.pageSummary.Description = "This is a summary of the import. Please verify this information and press \'Finish" + "\' to import the new objects."; this.pageSummary.Location = new System.Drawing.Point(0, 0); this.pageSummary.Name = "pageSummary"; this.pageSummary.Size = new System.Drawing.Size(653, 495); this.pageSummary.TabIndex = 9; this.pageSummary.Title = "Summary"; // // txtSummary // this.txtSummary.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.txtSummary.AutoScrollMinSize = new System.Drawing.Size(2, 14); this.txtSummary.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.txtSummary.CommentPrefix = "--"; this.txtSummary.Cursor = System.Windows.Forms.Cursors.IBeam; this.txtSummary.Font = new System.Drawing.Font("Courier New", 9.75F); this.txtSummary.LeftBracket = '('; this.txtSummary.Location = new System.Drawing.Point(12, 76); this.txtSummary.Name = "txtSummary"; this.txtSummary.ReadOnly = true; this.txtSummary.RightBracket = ')'; this.txtSummary.ShowLineNumbers = false; this.txtSummary.Size = new System.Drawing.Size(629, 404); this.txtSummary.TabIndex = 2; // // pageEntities // this.pageEntities.Controls.Add(this.panel2); this.pageEntities.Controls.Add(this.pnlMain); this.pageEntities.Description = "Choose the objects to import."; this.pageEntities.Location = new System.Drawing.Point(0, 0); this.pageEntities.Name = "pageEntities"; this.pageEntities.Size = new System.Drawing.Size(653, 495); this.pageEntities.TabIndex = 8; this.pageEntities.Title = "Choose Objects"; // // panel2 // this.panel2.Controls.Add(this.chkIgnoreRelations); this.panel2.Controls.Add(this.chkInheritance); this.panel2.Controls.Add(this.chkSettingPK); this.panel2.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel2.Location = new System.Drawing.Point(0, 441); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(653, 54); this.panel2.TabIndex = 75; // // chkIgnoreRelations // this.chkIgnoreRelations.AutoSize = true; this.chkIgnoreRelations.Location = new System.Drawing.Point(151, 31); this.chkIgnoreRelations.Name = "chkIgnoreRelations"; this.chkIgnoreRelations.Size = new System.Drawing.Size(103, 17); this.chkIgnoreRelations.TabIndex = 73; this.chkIgnoreRelations.Text = "Ignore Relations"; this.chkIgnoreRelations.UseVisualStyleBackColor = true; // // chkInheritance // this.chkInheritance.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.chkInheritance.AutoSize = true; this.chkInheritance.Location = new System.Drawing.Point(151, 8); this.chkInheritance.Name = "chkInheritance"; this.chkInheritance.Size = new System.Drawing.Size(119, 17); this.chkInheritance.TabIndex = 72; this.chkInheritance.Text = "Assume Inheritance"; this.chkInheritance.UseVisualStyleBackColor = true; // // chkSettingPK // this.chkSettingPK.AutoSize = true; this.chkSettingPK.Checked = true; this.chkSettingPK.CheckState = System.Windows.Forms.CheckState.Checked; this.chkSettingPK.Location = new System.Drawing.Point(8, 8); this.chkSettingPK.Name = "chkSettingPK"; this.chkSettingPK.Size = new System.Drawing.Size(124, 17); this.chkSettingPK.TabIndex = 70; this.chkSettingPK.Text = "Override Primary Key"; this.chkSettingPK.UseVisualStyleBackColor = true; // // pnlMain // this.pnlMain.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.pnlMain.Controls.Add(this.cmdViewDiff); this.pnlMain.Controls.Add(this.tabControl1); this.pnlMain.Location = new System.Drawing.Point(0, 78); this.pnlMain.Margin = new System.Windows.Forms.Padding(0); this.pnlMain.Name = "pnlMain"; this.pnlMain.Padding = new System.Windows.Forms.Padding(10); this.pnlMain.Size = new System.Drawing.Size(653, 363); this.pnlMain.TabIndex = 73; // // cmdViewDiff // this.cmdViewDiff.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.cmdViewDiff.Enabled = false; this.cmdViewDiff.Location = new System.Drawing.Point(500, 345); this.cmdViewDiff.Name = "cmdViewDiff"; this.cmdViewDiff.Size = new System.Drawing.Size(140, 23); this.cmdViewDiff.TabIndex = 73; this.cmdViewDiff.Text = "View Differences"; this.cmdViewDiff.UseVisualStyleBackColor = true; this.cmdViewDiff.Click += new System.EventHandler(this.cmdViewDiff_Click); // // tabControl1 // this.tabControl1.Controls.Add(this.tabPage1); this.tabControl1.Controls.Add(this.tabPage2); this.tabControl1.Controls.Add(this.tabPage3); this.tabControl1.Dock = System.Windows.Forms.DockStyle.Top; this.tabControl1.Location = new System.Drawing.Point(10, 10); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; this.tabControl1.Size = new System.Drawing.Size(633, 329); this.tabControl1.TabIndex = 70; this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged); // // tabPage1 // this.tabPage1.Controls.Add(this.tvwAdd); this.tabPage1.Location = new System.Drawing.Point(4, 22); this.tabPage1.Name = "tabPage1"; this.tabPage1.Padding = new System.Windows.Forms.Padding(3); this.tabPage1.Size = new System.Drawing.Size(625, 303); this.tabPage1.TabIndex = 0; this.tabPage1.Text = "Add"; this.tabPage1.UseVisualStyleBackColor = true; // // tvwAdd // this.tvwAdd.CheckBoxes = true; this.tvwAdd.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwAdd.HideSelection = false; this.tvwAdd.Location = new System.Drawing.Point(3, 3); this.tvwAdd.Name = "tvwAdd"; this.tvwAdd.Size = new System.Drawing.Size(619, 297); this.tvwAdd.TabIndex = 68; // // tabPage2 // this.tabPage2.Controls.Add(this.tvwRefresh); this.tabPage2.Location = new System.Drawing.Point(4, 22); this.tabPage2.Name = "tabPage2"; this.tabPage2.Padding = new System.Windows.Forms.Padding(3); this.tabPage2.Size = new System.Drawing.Size(625, 303); this.tabPage2.TabIndex = 1; this.tabPage2.Text = "Refresh"; this.tabPage2.UseVisualStyleBackColor = true; // // tvwRefresh // this.tvwRefresh.CheckBoxes = true; this.tvwRefresh.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwRefresh.HideSelection = false; this.tvwRefresh.Location = new System.Drawing.Point(3, 3); this.tvwRefresh.Name = "tvwRefresh"; this.tvwRefresh.Size = new System.Drawing.Size(619, 297); this.tvwRefresh.TabIndex = 69; // // tabPage3 // this.tabPage3.Controls.Add(this.tvwDelete); this.tabPage3.Location = new System.Drawing.Point(4, 22); this.tabPage3.Name = "tabPage3"; this.tabPage3.Padding = new System.Windows.Forms.Padding(3); this.tabPage3.Size = new System.Drawing.Size(625, 303); this.tabPage3.TabIndex = 2; this.tabPage3.Text = "Delete"; this.tabPage3.UseVisualStyleBackColor = true; // // tvwDelete // this.tvwDelete.CheckBoxes = true; this.tvwDelete.Dock = System.Windows.Forms.DockStyle.Fill; this.tvwDelete.HideSelection = false; this.tvwDelete.Location = new System.Drawing.Point(3, 3); this.tvwDelete.Name = "tvwDelete"; this.tvwDelete.Size = new System.Drawing.Size(619, 297); this.tvwDelete.TabIndex = 69; // // ImportDatabaseForm // this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.None; this.ClientSize = new System.Drawing.Size(653, 543); this.Controls.Add(this.wizard1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(659, 582); this.Name = "ImportDatabaseForm"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Import Model Wizard"; this.wizard1.ResumeLayout(false); this.wizard1.PerformLayout(); this.pageConnection.ResumeLayout(false); this.pageConnection.PerformLayout(); this.grpConnectionStringPostgres.ResumeLayout(false); this.grpConnectionStringPostgres.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.pageSummary.ResumeLayout(false); this.pageEntities.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.pnlMain.ResumeLayout(false); this.tabControl1.ResumeLayout(false); this.tabPage1.ResumeLayout(false); this.tabPage2.ResumeLayout(false); this.tabPage3.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ImageList imageList1; private nHydrate.Wizard.Wizard wizard1; private nHydrate.Wizard.WizardPage pageConnection; private nHydrate.Wizard.WizardPage pageEntities; private System.Windows.Forms.Panel pnlMain; private System.Windows.Forms.TabControl tabControl1; private System.Windows.Forms.TabPage tabPage1; private System.Windows.Forms.TreeView tvwAdd; private System.Windows.Forms.TabPage tabPage2; private System.Windows.Forms.TreeView tvwRefresh; private System.Windows.Forms.TabPage tabPage3; private System.Windows.Forms.TreeView tvwDelete; private System.Windows.Forms.Panel panel2; private System.Windows.Forms.CheckBox chkSettingPK; private nHydrate.DslPackage.Forms.DatabaseConnectionControl DatabaseConnectionControl1; private System.Windows.Forms.Button cmdTestConnection; private System.Windows.Forms.CheckBox chkInheritance; private System.Windows.Forms.CheckBox chkIgnoreRelations; private System.Windows.Forms.Button cmdViewDiff; private Wizard.WizardPage pageSummary; private FastColoredTextBoxNS.FastColoredTextBox txtSummary; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.RadioButton optDatabaseTypePostgres; private System.Windows.Forms.RadioButton optDatabaseTypeSQL; private System.Windows.Forms.GroupBox grpConnectionStringPostgres; private System.Windows.Forms.Label lblConnectionString; private Generator.Common.Forms.CueTextBox txtConnectionStringPostgres; } }
using System; using System.Collections; using System.IO; using System.Text; using Microsoft.SPOT; using PervasiveDigital.Net; using PervasiveDigital.Utilities; using PervasiveDigital.Security.ManagedProviders; namespace PervasiveDigital.Net.Azure.Storage { public class BlobClient { private readonly CloudStorageAccount _account; private readonly INetworkAdapter _adapter; private readonly HttpClient _client; public BlobClient(INetworkAdapter adapter, CloudStorageAccount account) { _adapter = adapter; _account = account; _client = new HttpClient(adapter); } //public bool PutBlockBlob(string containerName, string blobName, string fileNamePath) //{ // try // { // string deploymentPath = // StringUtilities.Format("{0}/{1}/{2}", _account.UriEndpoints["Blob"], containerName, // blobName); // int contentLength; // HttpVerb = "PUT"; // byte[] ms = GetPackageFileBytesAndLength(fileNamePath, out contentLength); // string canResource = StringUtilities.Format("/{0}/{1}/{2}", _account.AccountName, containerName, blobName); // string authHeader = CreateAuthorizationHeader(canResource, "\nx-ms-blob-type:BlockBlob", contentLength); // try // { // var blobTypeHeaders = new Hashtable(); // blobTypeHeaders.Add("x-ms-blob-type", "BlockBlob"); // var response = AzureStorageHttpHelper.SendWebRequest(_client, deploymentPath, authHeader, GetDateHeader(), VersionHeader, ms, contentLength, HttpVerb, true, blobTypeHeaders); // if (response.StatusCode != HttpStatusCode.Created) // { // Debug.Print("Deployment Path was " + deploymentPath); // Debug.Print("Auth Header was " + authHeader); // Debug.Print("Ms was " + ms.Length); // Debug.Print("Length was " + contentLength); // } // else // { // Debug.Print("Success"); // Debug.Print("Auth Header was " + authHeader); // } // return response.StatusCode == HttpStatusCode.Created; // } // catch (WebException wex) // { // Debug.Print(wex.ToString()); // return false; // } // } // catch (IOException ex) // { // Debug.Print(ex.ToString()); // return false; // } // catch (Exception ex) // { // Debug.Print(ex.ToString()); // return false; // } //} public bool PutBlockBlob(string containerName, string blobName, Byte[] ms) { try { string deploymentPath = StringUtilities.Format("{0}/{1}/{2}", _account.UriEndpoints["Blob"], containerName, blobName); int contentLength = ms.Length; HttpVerb = "PUT"; string canResource = StringUtilities.Format("/{0}/{1}/{2}", _account.AccountName, containerName, blobName); var timestamp = GetDateHeader(); string authHeader = CreateAuthorizationHeader(canResource, timestamp, "\nx-ms-blob-type:BlockBlob", contentLength); try { var blobTypeHeaders = new Hashtable(); blobTypeHeaders.Add("x-ms-blob-type", "BlockBlob"); var response = AzureStorageHttpHelper.SendWebRequest(_client, deploymentPath, authHeader, timestamp, VersionHeader, ms, contentLength, HttpVerb, true, blobTypeHeaders); if (response.StatusCode != HttpStatusCode.Created) { Debug.Print("Deployment Path was " + deploymentPath); Debug.Print("Auth Header was " + authHeader); Debug.Print("Ms was " + ms.Length); Debug.Print("Length was " + contentLength); } else { Debug.Print("Success"); Debug.Print("Auth Header was " + authHeader); } return response.StatusCode == HttpStatusCode.Created; } catch (WebException wex) { Debug.Print(wex.ToString()); return false; } } catch (IOException ex) { Debug.Print(ex.ToString()); return false; } catch (Exception ex) { Debug.Print(ex.ToString()); return false; } } public bool DeleteBlob(string containerName, string blobName) { try { string deploymentPath = StringUtilities.Format("{0}/{1}/{2}", _account.UriEndpoints["Blob"], containerName, blobName); HttpVerb = "DELETE"; string canResource = StringUtilities.Format("/{0}/{1}/{2}", _account.AccountName, containerName, blobName); var timestamp = GetDateHeader(); string authHeader = CreateAuthorizationHeader(canResource, timestamp); try { var response = AzureStorageHttpHelper.SendWebRequest(_client, deploymentPath, authHeader, timestamp, VersionHeader, null, 0, HttpVerb, true); if (response.StatusCode != HttpStatusCode.Accepted) { Debug.Print("Deployment Path was " + deploymentPath); Debug.Print("Auth Header was " + authHeader); Debug.Print("Error Status Code: " + response.StatusCode); } else { Debug.Print("Success"); Debug.Print("Auth Header was " + authHeader); } return response.StatusCode == HttpStatusCode.Accepted; } catch (WebException wex) { Debug.Print(wex.ToString()); return false; } } catch (IOException ex) { Debug.Print(ex.ToString()); return false; } catch (Exception ex) { Debug.Print(ex.ToString()); return false; } } public bool CreateContainer(string containerName) { try { string deploymentPath = StringUtilities.Format("{0}/{1}?{2}", _account.UriEndpoints["Blob"], containerName, ContainerString); HttpVerb = "PUT"; string canResource = StringUtilities.Format("/{0}/{1}\nrestype:container", _account.AccountName, containerName); var timestamp = GetDateHeader(); string authHeader = CreateAuthorizationHeader(canResource, timestamp); try { var response = AzureStorageHttpHelper.SendWebRequest(_client, deploymentPath, authHeader, timestamp, VersionHeader, null, 0, HttpVerb, true); if (response.StatusCode != HttpStatusCode.Created) { Debug.Print("Deployment Path was " + deploymentPath); Debug.Print("Auth Header was " + authHeader); Debug.Print("Error Status Code: " + response.StatusCode); } else { Debug.Print("Success"); Debug.Print("Auth Header was " + authHeader); } return response.StatusCode == HttpStatusCode.Created; } catch (WebException wex) { Debug.Print(wex.ToString()); return false; } } catch (IOException ex) { Debug.Print(ex.ToString()); return false; } catch (Exception ex) { Debug.Print(ex.ToString()); return false; } } public bool DeleteContainer(string containerName) { try { string deploymentPath = StringUtilities.Format("{0}/{1}?{2}", _account.UriEndpoints["Blob"], containerName, ContainerString); HttpVerb = "DELETE"; string canResource = StringUtilities.Format("/{0}/{1}\nrestype:container", _account.AccountName, containerName); var timestamp = GetDateHeader(); string authHeader = CreateAuthorizationHeader(canResource, timestamp); try { var response = AzureStorageHttpHelper.SendWebRequest(_client, deploymentPath, authHeader, timestamp, VersionHeader, null, 0, HttpVerb, true); if (response.StatusCode != HttpStatusCode.Accepted) { Debug.Print("Deployment Path was " + deploymentPath); Debug.Print("Auth Header was " + authHeader); Debug.Print("Error Status Code: " + response.StatusCode); } else { Debug.Print("Success"); Debug.Print("Auth Header was " + authHeader); } return response.StatusCode == HttpStatusCode.Accepted; } catch (WebException wex) { Debug.Print(wex.ToString()); return false; } } catch (IOException ex) { Debug.Print(ex.ToString()); return false; } catch (Exception ex) { Debug.Print(ex.ToString()); return false; } } //protected byte[] GetPackageFileBytesAndLength(string fileName, out int contentLength) //{ // byte[] ms = null; // contentLength = 0; // if (fileName != null) // { // using (StreamReader sr = new StreamReader(File.Open(fileName, FileMode.Open))) // { // string data = sr.ReadToEnd(); // ms = Encoding.UTF8.GetBytes(data); // contentLength = ms.Length; // } // } // return ms; //} protected string CreateAuthorizationHeader(string canResource, string timestamp, string options = "", int contentLength = 0) { string toSign = StringUtilities.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n{5}\nx-ms-date:{2}\nx-ms-version:{3}\n{4}", HttpVerb, contentLength, timestamp, VersionHeader, canResource, options); var hmac = new HMACSHA256(Convert.FromBase64String(_account.AccountKey)); var hmacBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(toSign)); string signature = Convert.ToBase64String(hmacBytes).Replace("!", "+").Replace("*", "/"); ; return "SharedKey " + _account.AccountName + ":" + signature; } internal const string VersionHeader = "2011-08-18"; private const string ContainerString = "restype=container"; protected string GetDateHeader() { return DateTime.UtcNow.ToString("R"); } public string HttpVerb { get; set; } } }
using XPT.Games.Generic.Constants; using XPT.Games.Generic.Maps; using XPT.Games.Twinion.Entities; namespace XPT.Games.Twinion.Maps { class TwMap25 : TwMap { public override int MapIndex => 25; public override int MapID => 0x0A03; protected override int RandomEncounterChance => 15; protected override int RandomEncounterExtraCount => 2; private const int PANSTAR = 1; private const int PORT = 2; protected override void FnEvent01(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 159, Direction.South); } protected override void FnEvent02(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 11, 1, 175, Direction.North); RemoveItem(player, type, doMsgs, HOPESFURY); RemoveItem(player, type, doMsgs, FLASKOFSHADOWFALL); RemoveItem(player, type, doMsgs, NIMBUSOFTHEFATES); RemoveItem(player, type, doMsgs, REALITYSRAMPART); } protected override void FnEvent03(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 46, Direction.North); } protected override void FnEvent04(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 176, Direction.South); } protected override void FnEvent05(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 11, 3, 16, Direction.North); RemoveItem(player, type, doMsgs, ICEFLAME); RemoveItem(player, type, doMsgs, HOPESFURY); RemoveItem(player, type, doMsgs, FLASKOFSHADOWFALL); RemoveItem(player, type, doMsgs, NIMBUSOFTHEFATES); } protected override void FnEvent06(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 172, Direction.North); } protected override void FnEvent07(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 11, 1, 241, Direction.North); RemoveItem(player, type, doMsgs, ICEFLAME); RemoveItem(player, type, doMsgs, HOPESFURY); RemoveItem(player, type, doMsgs, NIMBUSOFTHEFATES); RemoveItem(player, type, doMsgs, REALITYSRAMPART); } protected override void FnEvent08(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 110, Direction.West); } protected override void FnEvent09(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 11, 1, 40, Direction.South); RemoveItem(player, type, doMsgs, ICEFLAME); RemoveItem(player, type, doMsgs, FLASKOFSHADOWFALL); RemoveItem(player, type, doMsgs, NIMBUSOFTHEFATES); RemoveItem(player, type, doMsgs, REALITYSRAMPART); } protected override void FnEvent0A(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 11, 3, 240, Direction.East); RemoveItem(player, type, doMsgs, FLASKOFSHADOWFALL); RemoveItem(player, type, doMsgs, ICEFLAME); RemoveItem(player, type, doMsgs, HOPESFURY); RemoveItem(player, type, doMsgs, REALITYSRAMPART); } protected override void FnEvent0B(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "You quickly jump out of the way of a falling boulder."); TeleportParty(player, type, doMsgs, 10, 3, 233, Direction.North); } protected override void FnEvent0C(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 19, Direction.East); } protected override void FnEvent0D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0) { if (GetFlag(player, type, doMsgs, FlagTypeParty, PANSTAR) == 1) { TeleportParty(player, type, doMsgs, 10, 3, 35, Direction.West); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } } protected override void FnEvent0E(TwPlayerServer player, MapEventType type, bool doMsgs) { TeleportParty(player, type, doMsgs, 10, 3, 83, Direction.South); } protected override void FnEvent0F(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANHEAL) == 1) { ShowText(player, type, doMsgs, "The alcove is empty."); } else { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANHEAL, 1); GiveItem(player, type, doMsgs, HEALAMPHORA); GiveItem(player, type, doMsgs, HEALAMPHORA); GiveItem(player, type, doMsgs, SCORCHEDSCROLL); ShowText(player, type, doMsgs, "Next to the obvious remains of a long time dead adventurer you are surprised to find some items intact."); } } protected override void FnEvent10(TwPlayerServer player, MapEventType type, bool doMsgs) { ModifyMana(player, type, doMsgs, - 200); ShowText(player, type, doMsgs, "Your constant running into invisible walls has taken a toll on your mana."); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } protected override void FnEvent11(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } protected override void FnEvent12(TwPlayerServer player, MapEventType type, bool doMsgs) { DisableSkills(player, type, doMsgs); DisableSpells(player, type, doMsgs); } protected override void FnEvent13(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANSCROLL) == 1) { ShowText(player, type, doMsgs, "You see nothing of interest here."); } else { ShowPortrait(player, type, doMsgs, DWARFWIZARD); SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANSCROLL, 1); GiveItem(player, type, doMsgs, ZEUSSCROLL); GiveItem(player, type, doMsgs, PUMMELSCROLL); GiveItem(player, type, doMsgs, SHIELDINGSCROLL); ModifyGold(player, type, doMsgs, - 10000); ShowText(player, type, doMsgs, "You encounter a wizard selling scrolls."); ShowText(player, type, doMsgs, "'I see that you will be in need of magic as you travel through this area. I accept your payment for these scrolls. May they aid you in your journey.'"); } } protected override void FnEvent14(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { ShowText(player, type, doMsgs, "The water drains your energy as you wade through it."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } protected override void FnEvent16(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { if (GetGuild(player, type, doMsgs) == RANGER || GetGuild(player, type, doMsgs) == CLERIC || GetGuild(player, type, doMsgs) == WIZARD) { ShowText(player, type, doMsgs, "A water monster attacks you, but you manage to get away with minimal damage."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } } protected override void FnEvent18(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "You fall into a bottomless pit."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); } protected override void FnEvent1A(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANMANA) == 1) { ShowText(player, type, doMsgs, "The water flows briskly around you."); } else { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANMANA, 1); GiveItem(player, type, doMsgs, MANAAMPHORA); ShowText(player, type, doMsgs, "You see something bobbing in the water and grab it."); } } protected override void FnEvent1B(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { if (GetGuild(player, type, doMsgs) == THIEF || GetGuild(player, type, doMsgs) == BARBARIAN || GetGuild(player, type, doMsgs) == KNIGHT) { ShowText(player, type, doMsgs, "A water monster attacks you, but you manage to get away with minimal damage."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } } protected override void FnEvent1D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); } } protected override void FnEvent1E(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { ShowText(player, type, doMsgs, "The heat of the surrounding lava makes you weak."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } protected override void FnEvent1F(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANMONEY) == 1) { ShowText(player, type, doMsgs, "You find nothing."); } else { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANMONEY, 1); GiveItem(player, type, doMsgs, THIEFSSTILETTO); GiveItem(player, type, doMsgs, DRAGONSSTONE); GiveItem(player, type, doMsgs, PLATINUMBAR); GiveItem(player, type, doMsgs, RINGOFTHIEVES); ShowText(player, type, doMsgs, "Protruding from the hardened lava you find a bag. You free it and pocket the contents."); } } protected override void FnEvent20(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } } protected override void FnEvent21(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "You see a sign on the door. 'Adventurers! Proceed through this door individually if you possess the magical Starburst.'"); if (GetPartyCount(player, type, doMsgs) == 1) { if (HasItem(player, type, doMsgs, STARBURST)) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "You must find the magical Starburst to gain entry."); } } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent22(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { if (GetGuild(player, type, doMsgs) == THIEF || GetGuild(player, type, doMsgs) == BARBARIAN || GetGuild(player, type, doMsgs) == KNIGHT) { ShowText(player, type, doMsgs, "Your heavy step causes a crack in the hardened lava and the still molten lava below splashes up and injures you."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } } protected override void FnEvent23(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { if (GetGuild(player, type, doMsgs) == RANGER || GetGuild(player, type, doMsgs) == CLERIC || GetGuild(player, type, doMsgs) == WIZARD) { ShowText(player, type, doMsgs, "Your heavy step causes a crack in the hardened lava and the still molten lava below splashes up and injures you."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 4); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } } protected override void FnEvent24(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "The swirling waters of Bedlam Whirlpool heal your wounds."); ModifyHealth(player, type, doMsgs, GetHealthMax(player, type, doMsgs)); } protected override void FnEvent25(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); } else { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); } } protected override void FnEvent26(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { ShowText(player, type, doMsgs, "The crusted lava allows for easy passage."); } else { ShowPortrait(player, type, doMsgs, ELFCLERIC); ShowText(player, type, doMsgs, "You help a Cleric free his trapped foot from a crack in the lava. 'Thank you for helping me. Please accept this talisman with my gratitude. May it aid you in your travels."); ShowText(player, type, doMsgs, "It has gotten me out of a few rocky situations.'"); GiveItem(player, type, doMsgs, STARBURST); } } protected override void FnEvent29(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); DisableHealing(player, type, doMsgs); if ((GetFlag(player, type, doMsgs, FlagTypeTile, PORT) == 0)) { ShowText(player, type, doMsgs, "You cut yourself on the jagged rock wall."); DoDamage(player, type, doMsgs, GetHealthMax(player, type, doMsgs) / 3); SetFlag(player, type, doMsgs, FlagTypeTile, PORT, 1); } } protected override void FnEvent2A(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANLIFE) == 1) { ShowText(player, type, doMsgs, "You see a hole in the wall."); } else { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANLIFE, 1); ShowText(player, type, doMsgs, "You see forgotten items resting on a ledge in the wall."); GiveItem(player, type, doMsgs, SYMBOLOFDEATH); GiveItem(player, type, doMsgs, SPIKEDSHIELD); GiveItem(player, type, doMsgs, LIFEGIVER); GiveItem(player, type, doMsgs, CUREALLPOTION); } } protected override void FnEvent2B(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); ShowText(player, type, doMsgs, "The Lava Pool of Confusion restores your mana."); ModifyMana(player, type, doMsgs, 10000); } protected override void FnEvent2C(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "You find that a boulder has blocked your path."); if ((UsedItem(player, type, ref doMsgs, STARBURST, STARBURST)) && (GetGuild(player, type, doMsgs) == GNOME || GetGuild(player, type, doMsgs) == ELF)) { SetFlag(player, type, doMsgs, FlagTypeParty, PANSTAR, 1); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "The magical Starburst shatters the boulder."); } else { ShowText(player, type, doMsgs, "You cannot budge the boulder."); } } else { ShowText(player, type, doMsgs, "The ground shows signs of damage from heavy boulders falling."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent2D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "You find that a boulder has blocked your path."); if ((UsedItem(player, type, ref doMsgs, STARBURST, STARBURST)) && (GetGuild(player, type, doMsgs) == ORC || GetGuild(player, type, doMsgs) == GREMLIN)) { SetFlag(player, type, doMsgs, FlagTypeParty, PANSTAR, 1); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "The magical Starburst shatters the boulder."); } else { ShowText(player, type, doMsgs, "You cannot budge the boulder."); } } else { ShowText(player, type, doMsgs, "The ground shows signs of damage from heavy boulders falling."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent2E(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "You find that a boulder has blocked your path."); if ((UsedItem(player, type, ref doMsgs, STARBURST, STARBURST)) && (GetGuild(player, type, doMsgs) == DWARF || GetGuild(player, type, doMsgs) == TROLL)) { SetFlag(player, type, doMsgs, FlagTypeParty, PANSTAR, 1); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "The magical Starburst shatters the boulder."); } else { ShowText(player, type, doMsgs, "You cannot budge the boulder."); } } else { ShowText(player, type, doMsgs, "The ground shows signs of damage from heavy boulders falling."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent2F(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "You find that a boulder has blocked your path."); if ((UsedItem(player, type, ref doMsgs, STARBURST, STARBURST)) && (GetGuild(player, type, doMsgs) == HALFLING || GetGuild(player, type, doMsgs) == HUMAN)) { SetFlag(player, type, doMsgs, FlagTypeParty, PANSTAR, 1); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); ShowText(player, type, doMsgs, "The magical Starburst shatters the boulder."); } else { ShowText(player, type, doMsgs, "You cannot budge the boulder."); } } else { ShowText(player, type, doMsgs, "The ground shows signs of damage from heavy boulders falling."); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), GetFacing(player, type, doMsgs)); } } protected override void FnEvent30(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); if (GetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANBUCKS) == 1) { ShowText(player, type, doMsgs, "There is nothing but rubble on the ground."); } else { SetFlag(player, type, doMsgs, FlagTypeDungeon, TwIndexes.PANBUCKS, 1); ShowText(player, type, doMsgs, "Upon searching the alcove you move a rock and discover treasure."); GiveItem(player, type, doMsgs, TEMPEREDADAMANTINE); GiveItem(player, type, doMsgs, PLATINUMBAR); GiveItem(player, type, doMsgs, PRIESTSAMULET); GiveItem(player, type, doMsgs, CRYSTALBALL); } } protected override void FnEvent31(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, GNOMEWIZARD); ShowText(player, type, doMsgs, "You encounter a Gnome Wizard who stops you in your path. "); ShowText(player, type, doMsgs, "'This place is pandemonium. My skills and spells are useless in places.'"); } protected override void FnEvent32(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, STORMGIANT); ShowText(player, type, doMsgs, "'You have come to the area where you must decide which path to follow in your search for each of the Dralkarians. Guard well your magical Starburst for it will grant you passage to the portals.'"); ShowText(player, type, doMsgs, "'May your choices be wise and your journeys successful.'"); } protected override void FnEvent33(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, GREMLINTHIEF); ShowText(player, type, doMsgs, "A thief pulls you aside. 'Pssst....I found a way to walk over the lava. Just be sure it's crusted over. Shhhhh, don't tell a soul.'"); } protected override void FnEvent34(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); ShowText(player, type, doMsgs, "You see a hand written note on the back of a scroll. It warns that what may harm one, may not harm another."); } protected override void FnEvent35(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowPortrait(player, type, doMsgs, COMMONNIGHTELF); ShowText(player, type, doMsgs, "'The time has come for you to begin your journey to meet the Dralkarians. You must travel through Pandemonium in order to seek the portals to the final paths. Of the 5 portals you shall make your choice.'"); } protected override void FnEvent37(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 1); AddEncounter(player, type, doMsgs, 05, 2); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 1); AddEncounter(player, type, doMsgs, 02, 2); AddEncounter(player, type, doMsgs, 05, 3); AddEncounter(player, type, doMsgs, 06, 3); } else { AddEncounter(player, type, doMsgs, 01, 1); AddEncounter(player, type, doMsgs, 02, 1); AddEncounter(player, type, doMsgs, 03, 2); AddEncounter(player, type, doMsgs, 04, 2); AddEncounter(player, type, doMsgs, 05, 3); } } protected override void FnEvent38(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 32); AddEncounter(player, type, doMsgs, 02, 33); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 31); AddEncounter(player, type, doMsgs, 02, 31); AddEncounter(player, type, doMsgs, 03, 32); AddEncounter(player, type, doMsgs, 04, 33); } else { AddEncounter(player, type, doMsgs, 01, 31); AddEncounter(player, type, doMsgs, 02, 31); AddEncounter(player, type, doMsgs, 03, 33); AddEncounter(player, type, doMsgs, 04, 33); AddEncounter(player, type, doMsgs, 06, 34); } } protected override void FnEvent39(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 17); AddEncounter(player, type, doMsgs, 02, 19); AddEncounter(player, type, doMsgs, 06, 30); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 19); AddEncounter(player, type, doMsgs, 02, 20); AddEncounter(player, type, doMsgs, 05, 30); AddEncounter(player, type, doMsgs, 06, 28); } else { AddEncounter(player, type, doMsgs, 01, 17); AddEncounter(player, type, doMsgs, 02, 17); AddEncounter(player, type, doMsgs, 04, 30); AddEncounter(player, type, doMsgs, 05, 28); AddEncounter(player, type, doMsgs, 06, 29); } } protected override void FnEvent3A(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 26); AddEncounter(player, type, doMsgs, 05, 38); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 26); AddEncounter(player, type, doMsgs, 02, 27); AddEncounter(player, type, doMsgs, 03, 28); AddEncounter(player, type, doMsgs, 04, 38); } else { AddEncounter(player, type, doMsgs, 01, 26); AddEncounter(player, type, doMsgs, 02, 26); AddEncounter(player, type, doMsgs, 04, 27); AddEncounter(player, type, doMsgs, 05, 37); AddEncounter(player, type, doMsgs, 06, 38); } } protected override void FnEvent3B(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 39); AddEncounter(player, type, doMsgs, 05, 40); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 39); AddEncounter(player, type, doMsgs, 02, 39); AddEncounter(player, type, doMsgs, 03, 40); AddEncounter(player, type, doMsgs, 06, 25); } else { AddEncounter(player, type, doMsgs, 01, 40); AddEncounter(player, type, doMsgs, 02, 40); AddEncounter(player, type, doMsgs, 03, 39); AddEncounter(player, type, doMsgs, 05, 25); AddEncounter(player, type, doMsgs, 06, 25); } } protected override void FnEvent3C(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 1); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 1); AddEncounter(player, type, doMsgs, 02, 3); } else { AddEncounter(player, type, doMsgs, 01, 1); AddEncounter(player, type, doMsgs, 02, 4); AddEncounter(player, type, doMsgs, 05, 33); AddEncounter(player, type, doMsgs, 06, 33); } } protected override void FnEvent3D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { AddEncounter(player, type, doMsgs, 01, 13); } else if (GetPartyCount(player, type, doMsgs) == 2) { AddEncounter(player, type, doMsgs, 01, 12); AddEncounter(player, type, doMsgs, 02, 13); AddEncounter(player, type, doMsgs, 03, 36); AddEncounter(player, type, doMsgs, 04, 36); } else { AddEncounter(player, type, doMsgs, 01, 12); AddEncounter(player, type, doMsgs, 02, 12); AddEncounter(player, type, doMsgs, 03, 13); AddEncounter(player, type, doMsgs, 04, 13); AddEncounter(player, type, doMsgs, 05, 36); } } protected override void FnEvent3E(TwPlayerServer player, MapEventType type, bool doMsgs) { if (GetPartyCount(player, type, doMsgs) == 1) { ShowText(player, type, doMsgs, "Now you may proceed to pick the path of your choice."); } else { TeleportParty(player, type, doMsgs, 10, 3, 34, Direction.East); } } protected override void FnEvent3F(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); } protected override void FnEvent40(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); } protected override void FnEvent41(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent42(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } protected override void FnEvent43(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent44(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent45(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent46(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } protected override void FnEvent47(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } protected override void FnEvent48(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); } protected override void FnEvent49(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); } protected override void FnEvent4A(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent4B(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent4C(TwPlayerServer player, MapEventType type, bool doMsgs) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } protected override void FnEvent4D(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } else { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } } protected override void FnEvent4E(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } } protected override void FnEvent4F(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } else { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.West); } } protected override void FnEvent50(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } else { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } } protected override void FnEvent51(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } else { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.East); SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } } protected override void FnEvent52(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } else { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.South); } } protected override void FnEvent53(TwPlayerServer player, MapEventType type, bool doMsgs) { if (HasItem(player, type, doMsgs, STARBURST)) { SetWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); } else { ClearWallBlock(player, type, doMsgs, GetTile(player, type, doMsgs), Direction.North); } } protected override void FnEvent54(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Proceed through this door and accept the challenge of the elements in order to gain access to Malos, the Dralkarian who controls the elements. Be aware that all Quest items gained from other paths will be taken from you."); } protected override void FnEvent55(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Step through this door to overcome physical obstacles on your path to Corpeus, the Dralkarian who guards the gate. Be aware that all Quest items gained from other paths will be taken from you."); } protected override void FnEvent56(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "This door will lead you to the path through Enakkar in your search for the Dralkarian Juvalad. Be aware that all Quest items from other paths will be taken from you."); } protected override void FnEvent57(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Through this door is Ashakkar. Succeed in your quest and you will find the Dralkarian Pluthros. Be aware that all Quest items from other paths will be taken from you."); } protected override void FnEvent58(TwPlayerServer player, MapEventType type, bool doMsgs) { ShowText(player, type, doMsgs, "Inside, a portal will teleport you to the astral path in order to find the Dralkarian guard Astelligus. Be aware that all Quest items from other paths will be taken from you."); } } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id$")] namespace Elmah.Assertions { #region Imports using System; using System.ComponentModel; using System.Configuration; using System.Reflection; using System.Text.RegularExpressions; using System.Web; using System.Xml; using System.Collections.Generic; #endregion /// <summary> /// Represents the method that will be responsible for creating an /// assertion object and initializing it from an XML configuration /// element. /// </summary> public delegate IAssertion AssertionFactoryHandler(XmlElement config); /// <summary> /// Holds factory methods for creating configured assertion objects. /// </summary> public static class AssertionFactory { public static IAssertion assert_is_null(IContextExpression binding) { return new IsNullAssertion(binding); } public static IAssertion assert_is_not_null(IContextExpression binding) { return new UnaryNotAssertion(assert_is_null(binding)); } public static IAssertion assert_equal(IContextExpression binding, TypeCode type, string value) { return new ComparisonAssertion(ComparisonResults.Equal, binding, type, value); } public static IAssertion assert_not_equal(IContextExpression binding, TypeCode type, string value) { return new UnaryNotAssertion(assert_equal(binding, type, value)); } public static IAssertion assert_lesser(IContextExpression binding, TypeCode type, string value) { return new ComparisonAssertion(ComparisonResults.Lesser, binding, type, value); } public static IAssertion assert_lesser_or_equal(IContextExpression binding, TypeCode type, string value) { return new ComparisonAssertion(ComparisonResults.LesserOrEqual, binding, type, value); } public static IAssertion assert_greater(IContextExpression binding, TypeCode type, string value) { return new ComparisonAssertion(ComparisonResults.Greater, binding, type, value); } public static IAssertion assert_greater_or_equal(IContextExpression binding, TypeCode type, string value) { return new ComparisonAssertion(ComparisonResults.GreaterOrEqual, binding, type, value); } public static IAssertion assert_and(XmlElement config) { return LogicalAssertion.LogicalAnd(Create(config.ChildNodes)); } public static IAssertion assert_or(XmlElement config) { return LogicalAssertion.LogicalOr(Create(config.ChildNodes)); } public static IAssertion assert_not(XmlElement config) { return LogicalAssertion.LogicalNot(Create(config.ChildNodes)); } public static IAssertion assert_is_type(IContextExpression binding, Type type) { return new TypeAssertion(binding, type, /* byCompatibility */ false); } public static IAssertion assert_is_type_compatible(IContextExpression binding, Type type) { return new TypeAssertion(binding, type, /* byCompatibility */ true); } public static IAssertion assert_regex(IContextExpression binding, string pattern, bool caseSensitive, bool dontCompile) { if ((pattern ?? string.Empty).Length == 0) return StaticAssertion.False; // // NOTE: There is an assumption here that most uses of this // assertion will be for culture-insensitive matches. Since // it is difficult to imagine all the implications of involving // a culture at this point, it seems safer to just err with the // invariant culture settings. // var options = RegexOptions.CultureInvariant; if (!caseSensitive) options |= RegexOptions.IgnoreCase; if (!dontCompile) options |= RegexOptions.Compiled; return new RegexMatchAssertion(binding, new Regex(pattern, options)); } public static IAssertion assert_jscript(XmlElement config) { if (config == null) throw new ArgumentNullException("config"); // // The expression can be specified via an attribute or a // a child element named "expression". The element form takes // precedence. // // TODO More rigorous validation // For example, expression should not appear as an attribute and // a child node. Also multiple child expressions should result in // an error. string expression = null; var expressionElement = config["expression"]; if (expressionElement != null) expression = expressionElement.InnerText; if (expression == null) expression = config.GetAttribute("expression"); return new JScriptAssertion( expression, DeserializeStringArray(config, "assemblies", "assembly", "name"), DeserializeStringArray(config, "imports", "import", "namespace")); } public static IAssertion Create(XmlElement config) { if (config == null) throw new ArgumentNullException("config"); try { return CreateImpl(config); } catch (ConfigurationException) { throw; } catch (Exception e) { throw new ConfigurationException(e.Message, e); } } public static IAssertion[] Create(XmlNodeList nodes) { if (nodes == null) throw new ArgumentNullException("nodes"); // // First count the number of elements, which will be used to // allocate the array at its correct and final size. // var elementCount = 0; foreach (XmlNode child in nodes) { var nodeType = child.NodeType; // // Skip comments and whitespaces. // if (nodeType == XmlNodeType.Comment || nodeType == XmlNodeType.Whitespace) continue; // // Otherwise all elements only. // if (nodeType != XmlNodeType.Element) { throw new ConfigurationException( string.Format("Unexpected type of node ({0}).", nodeType.ToString()), child); } elementCount++; } // // In the second pass, create and configure the assertions // from each element. // var assertions = new IAssertion[elementCount]; elementCount = 0; foreach (XmlNode node in nodes) { if (node.NodeType == XmlNodeType.Element) assertions[elementCount++] = Create((XmlElement) node); } return assertions; } private static IAssertion CreateImpl(XmlElement config) { Debug.Assert(config != null); var name = "assert_" + config.LocalName; if (name.IndexOf('-') > 0) name = name.Replace("-", "_"); Type factoryType; var xmlns = config.NamespaceURI ?? string.Empty; if (xmlns.Length > 0) { string assemblyName, ns; if (!DecodeClrTypeNamespaceFromXmlNamespace(xmlns, out ns, out assemblyName) || ns.Length == 0 || assemblyName.Length == 0) { throw new ConfigurationException(string.Format( "Error decoding CLR type namespace and assembly from the XML namespace '{0}'.", xmlns)); } var assembly = Assembly.Load(assemblyName); factoryType = assembly.GetType(ns + ".AssertionFactory", /* throwOnError */ true); } else { factoryType = typeof(AssertionFactory); } var method = factoryType.GetMethod(name, BindingFlags.Public | BindingFlags.Static); if (method == null) { throw new MissingMemberException(string.Format( "{0} does not have a method named {1}. " + "Ensure that the method is named correctly and that it is public and static.", factoryType, name)); } var parameters = method.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(XmlElement) && method.ReturnType == typeof(IAssertion)) { var handler = (AssertionFactoryHandler) Delegate.CreateDelegate(typeof(AssertionFactoryHandler), factoryType, name); return handler(config); // TODO Check if Delegate.CreateDelegate could return null } return (IAssertion) method.Invoke(null, ParseArguments(method, config)); } private static object[] ParseArguments(MethodInfo method, XmlElement config) { Debug.Assert(method != null); Debug.Assert(config != null); var parameters = method.GetParameters(); var args = new object[parameters.Length]; foreach (var parameter in parameters) args[parameter.Position] = ParseArgument(parameter, config); return args; } private static readonly string[] _truths = new[] { "true", "yes", "on", "1" }; // TODO Remove duplication with SecurityConfiguration private static object ParseArgument(ParameterInfo parameter, XmlElement config) { Debug.Assert(parameter != null); Debug.Assert(config != null); var name = parameter.Name; var type = parameter.ParameterType; string text; var attribute = config.GetAttributeNode(name); if (attribute != null) { text = attribute.Value; } else { var element = config[name]; if (element == null) return null; text = element.InnerText; } if (type == typeof(IContextExpression)) return new WebDataBindingExpression(text); if (type == typeof(Type)) return Type.GetType(text, /* throwOnError */ true, /* ignoreCase */ false); if (type == typeof(bool)) { text = text.Trim().ToLowerInvariant(); return Boolean.TrueString.Equals(StringTranslation.Translate(Boolean.TrueString, text, _truths)); } var converter = TypeDescriptor.GetConverter(type); return converter.ConvertFromInvariantString(text); } /// <remarks> /// Ideally, we would be able to use SoapServices.DecodeXmlNamespaceForClrTypeNamespace /// but that requires a link demand permission that will fail in partially trusted /// environments such as ASP.NET medium trust. /// </remarks> private static bool DecodeClrTypeNamespaceFromXmlNamespace(string xmlns, out string typeNamespace, out string assemblyName) { Debug.Assert(xmlns != null); assemblyName = string.Empty; typeNamespace = string.Empty; const string assemblyNS = "http://schemas.microsoft.com/clr/assem/"; const string namespaceNS = "http://schemas.microsoft.com/clr/ns/"; const string fullNS = "http://schemas.microsoft.com/clr/nsassem/"; if (OrdinalStringStartsWith(xmlns, assemblyNS)) { assemblyName = HttpUtility.UrlDecode(xmlns.Substring(assemblyNS.Length)); return assemblyName.Length > 0; } if (OrdinalStringStartsWith(xmlns, namespaceNS)) { typeNamespace = xmlns.Substring(namespaceNS.Length); return typeNamespace.Length > 0; } if (OrdinalStringStartsWith(xmlns, fullNS)) { var index = xmlns.IndexOf("/", fullNS.Length); typeNamespace = xmlns.Substring(fullNS.Length, index - fullNS.Length); assemblyName = HttpUtility.UrlDecode(xmlns.Substring(index + 1)); return assemblyName.Length > 0 && typeNamespace.Length > 0; } return false; } private static bool OrdinalStringStartsWith(string s, string prefix) { Debug.Assert(s != null); Debug.Assert(prefix != null); return s.Length >= prefix.Length && string.CompareOrdinal(s.Substring(0, prefix.Length), prefix) == 0; } private static string[] DeserializeStringArray(XmlElement config, string containerName, string elementName, string valueName) { Debug.Assert(config != null); Debug.AssertStringNotEmpty(containerName); Debug.AssertStringNotEmpty(elementName); Debug.AssertStringNotEmpty(valueName); var list = new List<string>(4); var xpath = containerName + "/" + elementName + "/@" + valueName; foreach (XmlAttribute attribute in config.SelectNodes(xpath)) { var value = attribute.Value ?? string.Empty; if (value.Length > 0) list.Add(attribute.Value); } return list.ToArray(); } } }
//------------------------------------------------------------------------------ // <copyright file="visualStyleRenderer.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA905:SystemAndMicrosoftNamespacesRequireApproval", Scope="namespace", Target="System.Windows.Forms.VisualStyles")] namespace System.Windows.Forms.VisualStyles { using System; using System.Drawing; using System.Windows.Forms.Internal; using System.Text; using System.Windows.Forms; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Runtime.InteropServices; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.Win32; using System.Security; using System.Security.Permissions; /// <include file='doc\visualStyleRenderer.uex' path='docs/doc[@for="visualStyleRenderer"]/*' /> /// <devdoc> /// <para> /// This class provides full feature parity with UxTheme API. /// </para> /// </devdoc> public sealed class VisualStyleRenderer { private const TextFormatFlags AllGraphicsProperties = TextFormatFlags.PreserveGraphicsClipping | TextFormatFlags.PreserveGraphicsTranslateTransform; internal const int EdgeAdjust = 0x2000; //used with Edges in VisualStyleRenderer.DrawThemeEdge private string _class; private int part; private int state; private int lastHResult = 0; private static int numberOfPossibleClasses = VisualStyleElement.Count; //used as size for themeHandles [ThreadStatic] private static Hashtable themeHandles = null; //per-thread cache of ThemeHandle objects. [ThreadStatic] private static long threadCacheVersion = 0; private static long globalCacheVersion = 0; static VisualStyleRenderer() { SystemEvents.UserPreferenceChanging += new UserPreferenceChangingEventHandler(OnUserPreferenceChanging); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.IsSupported"]/*' /> /// <devdoc> /// <para> /// Returns true if visual styles are 1) supported by the OS 2) enabled in the client area /// and 3) currently applied to this application. Otherwise, it returns false. Note that /// if it returns false, attempting to instantiate/use objects of this class /// will result in exceptions being thrown. /// </para> /// </devdoc> public static bool IsSupported { get { bool supported = (VisualStyleInformation.IsEnabledByUser && (Application.VisualStyleState == VisualStyleState.ClientAreaEnabled || Application.VisualStyleState == VisualStyleState.ClientAndNonClientAreasEnabled)); if (supported) { // VSWhidbey #171915: In some cases, this check isn't enough, since the theme handle creation // could fail for some other reason. Try creating a theme handle here - if successful, return true, // else return false. IntPtr hTheme = GetHandle("BUTTON", false); //Button is an arbitrary choice. supported = (hTheme != IntPtr.Zero); } return supported; } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.IsCombinationDefined"]/*' /> /// <devdoc> /// <para> /// Returns true if the element is defined by the current visual style, else false. /// Note: /// 1) Throws an exception if IsSupported is false, since it is illegal to call it in that case. /// 2) The underlying API does not validate states. So if you pass in invalid state values, /// we might still return true. When you use an invalid state to render, you get the default /// state instead. /// </para> /// </devdoc> public static bool IsElementDefined(VisualStyleElement element) { if (element == null) { throw new ArgumentNullException("element"); } return IsCombinationDefined(element.ClassName, element.Part); } private static bool IsCombinationDefined(string className, int part) { bool returnVal = false; if (!IsSupported) { if (!VisualStyleInformation.IsEnabledByUser) { throw new InvalidOperationException(SR.GetString(SR.VisualStyleNotActive)); } else { throw new InvalidOperationException(SR.GetString(SR.VisualStylesDisabledInClientArea)); } } if (className == null) { throw new ArgumentNullException("className"); } IntPtr hTheme = GetHandle(className, false); if (hTheme != IntPtr.Zero) { // IsThemePartDefined doesn't work for part = 0, although there are valid parts numbered 0. We // allow these explicitly here. if (part == 0) { returnVal = true; } else { returnVal = SafeNativeMethods.IsThemePartDefined(new HandleRef(null, hTheme), part, 0); } } //if the combo isn't defined, check the validity of our theme handle cache if (!returnVal) { using (ThemeHandle tHandle = ThemeHandle.Create(className, false)) { if (tHandle != null) { returnVal = SafeNativeMethods.IsThemePartDefined(new HandleRef(null, tHandle.NativeHandle), part, 0); } //if we did, in fact get a new correct theme handle, our cache is out of date -- update it now. if (returnVal) { RefreshCache(); } } } return returnVal; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.VisualStyleRenderer"]/*' /> /// <devdoc> /// <para> /// Constructor takes a VisualStyleElement. /// </para> /// </devdoc> public VisualStyleRenderer(VisualStyleElement element) : this(element.ClassName, element.Part, element.State) { } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.VisualStyleRenderer1"]/*' /> /// <devdoc> /// <para> /// Constructor takes weakly typed parameters - left for extensibility (using classes, parts or states /// not defined in the VisualStyleElement class.) /// </para> /// </devdoc> public VisualStyleRenderer(string className, int part, int state) { if (!IsCombinationDefined(className, part)) { //internally this call takes care of IsSupported. throw new ArgumentException(SR.GetString(SR.VisualStylesInvalidCombination)); } this._class = className; this.part = part; this.state = state; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.Class"]/*' /> /// <devdoc> /// <para> /// Returns the current _class. Use SetParameters to set. /// </para> /// </devdoc> public string Class { get { return _class; } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.Part"]/*' /> /// <devdoc> /// <para> /// Returns the current part. Use SetParameters to set. /// </para> /// </devdoc> public int Part { get { return part; } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.State"]/*' /> /// <devdoc> /// <para> /// Returns the current state. Use SetParameters to set. /// </para> /// </devdoc> public int State { get { return state; } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.Handle"]/*' /> /// <devdoc> /// <para> /// Returns the underlying HTheme handle. /// NOTE: The handle gets invalidated when the theme changes or the user disables theming. When that /// happens, the user should requery this property to get the correct handle. To know when the /// theme changed, hook on to SystemEvents.UserPreferenceChanged and look for ThemeChanged /// category. /// </para> /// </devdoc> public IntPtr Handle { get { if (!IsSupported) { if (!VisualStyleInformation.IsEnabledByUser) { throw new InvalidOperationException(SR.GetString(SR.VisualStyleNotActive)); } else { throw new InvalidOperationException(SR.GetString(SR.VisualStylesDisabledInClientArea)); } } return GetHandle(_class); } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.SetParameters"]/*' /> /// <devdoc> /// <para> /// Used to set a new VisualStyleElement on this VisualStyleRenderer instance. /// </para> /// </devdoc> public void SetParameters(VisualStyleElement element) { if (element == null) { throw new ArgumentNullException("element"); } SetParameters(element.ClassName, element.Part, element.State); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.SetParameters"]/*' /> /// <devdoc> /// <para> /// Used to set the _class, part and state that the VisualStyleRenderer object references. /// These parameters cannot be set individually. /// This method is present for extensibility. /// </para> /// </devdoc> public void SetParameters(string className, int part, int state) { if (!IsCombinationDefined(className, part)) { //internally this call takes care of IsSupported. throw new ArgumentException(SR.GetString(SR.VisualStylesInvalidCombination)); } this._class = className; this.part = part; this.state = state; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawBackground"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public void DrawBackground(IDeviceContext dc, Rectangle bounds) { if (dc == null) { throw new ArgumentNullException("dc"); } if (bounds.Width < 0 || bounds.Height < 0) { return; } using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ){ HandleRef hdc = new HandleRef(wgr, wgr.WindowsGraphics.DeviceContext.Hdc); lastHResult = SafeNativeMethods.DrawThemeBackground( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), null ); } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawBackground1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public void DrawBackground(IDeviceContext dc, Rectangle bounds, Rectangle clipRectangle) { if( dc == null ){ throw new ArgumentNullException("dc"); } if (bounds.Width < 0 || bounds.Height < 0) { return; } if (clipRectangle.Width < 0 || clipRectangle.Height < 0) { return; } using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.DrawThemeBackground( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), new NativeMethods.COMRECT( clipRectangle ) ); } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawEdge"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Rectangle DrawEdge(IDeviceContext dc, Rectangle bounds, Edges edges, EdgeStyle style, EdgeEffects effects) { if (dc == null) { throw new ArgumentNullException("dc"); } if (!ClientUtils.IsEnumValid_Masked(edges, (int)edges,(UInt32)(Edges.Left | Edges.Top | Edges.Right | Edges.Bottom | Edges.Diagonal))) { throw new InvalidEnumArgumentException("edges", (int)edges, typeof(Edges)); } if (!ClientUtils.IsEnumValid_NotSequential(style, (int)style, (int)EdgeStyle.Raised,(int)EdgeStyle.Sunken,(int)EdgeStyle.Etched,(int)EdgeStyle.Bump )) { throw new InvalidEnumArgumentException("style", (int)style, typeof(EdgeStyle)); } if (!ClientUtils.IsEnumValid_Masked(effects, (int)effects, (UInt32)(EdgeEffects.FillInterior | EdgeEffects.Flat | EdgeEffects.Soft | EdgeEffects.Mono))) { throw new InvalidEnumArgumentException("effects", (int)effects, typeof(EdgeEffects)); } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.DrawThemeEdge( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), (int) style, (int) edges | (int) effects | EdgeAdjust, rect ); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawImage"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// This method uses Graphics.DrawImage as a backup if themed drawing does not work. /// </para> /// </devdoc> public void DrawImage(Graphics g, Rectangle bounds, Image image) { if (g == null) { throw new ArgumentNullException("g"); } if (image == null) { throw new ArgumentNullException("image"); } if (bounds.Width < 0 || bounds.Height < 0) { return; } g.DrawImage(image, bounds); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawImage1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// This method uses Graphics.DrawImage as a backup if themed drawing does not work. /// </para> /// </devdoc> public void DrawImage(Graphics g, Rectangle bounds, ImageList imageList, int imageIndex) { if (g == null) { throw new ArgumentNullException("g"); } if (imageList == null) { throw new ArgumentNullException("imageList"); } if (imageIndex < 0 || imageIndex >= imageList.Images.Count) { throw new ArgumentOutOfRangeException("imageIndex", SR.GetString(SR.InvalidArgument, "imageIndex", imageIndex.ToString(CultureInfo.CurrentCulture))); } if (bounds.Width < 0 || bounds.Height < 0) { return; } // VSWhidbey #282742: DrawThemeIcon currently seems to do nothing, but still return S_OK. As a workaround, // we call DrawImage on the graphics object itself for now. A bug has been opened in Windows OS Bugs on this. //int returnVal = NativeMethods.S_FALSE; //using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { // HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); // returnVal = SafeNativeMethods.DrawThemeIcon( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), new HandleRef( this, imageList.Handle ), imageIndex ); //} //if (returnVal != NativeMethods.S_OK) { g.DrawImage(imageList.Images[imageIndex], bounds); //} } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawParentBackground"]/*' /> /// <devdoc> /// <para> /// Given a graphics object and bounds to draw in, this method effectively asks the passed in /// control's parent to draw itself in there (it sends WM_ERASEBKGND & WM_PRINTCLIENT messages /// to the parent). /// </para> /// </devdoc> public void DrawParentBackground(IDeviceContext dc, Rectangle bounds, Control childControl) { if (dc == null) { throw new ArgumentNullException("dc"); } if (childControl == null) { throw new ArgumentNullException("childControl"); } if (bounds.Width < 0 || bounds.Height < 0) { return; } if (childControl.Handle != IntPtr.Zero) { using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.DrawThemeParentBackground( new HandleRef( this, childControl.Handle ), hdc, new NativeMethods.COMRECT( bounds ) ); } } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawText"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw) { DrawText(dc, bounds, textToDraw, false); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawText1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, bool drawDisabled) { DrawText(dc, bounds, textToDraw, drawDisabled, TextFormatFlags.HorizontalCenter); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.DrawText2"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public void DrawText(IDeviceContext dc, Rectangle bounds, string textToDraw, bool drawDisabled, TextFormatFlags flags) { if( dc == null ){ throw new ArgumentNullException("dc"); } if (bounds.Width < 0 || bounds.Height < 0) { return; } int disableFlag = drawDisabled?0x1:0; if (!String.IsNullOrEmpty(textToDraw)) { using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.DrawThemeText( new HandleRef( this, Handle ), hdc, part, state, textToDraw, textToDraw.Length, (int) flags, disableFlag, new NativeMethods.COMRECT( bounds ) ); } } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetBackgroundContentRectangle"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Rectangle GetBackgroundContentRectangle(IDeviceContext dc, Rectangle bounds) { if( dc == null ){ throw new ArgumentNullException("dc"); } if (bounds.Width < 0 || bounds.Height < 0) { return Rectangle.Empty; } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeBackgroundContentRect( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), rect ); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetBackgroundExtent"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Rectangle GetBackgroundExtent(IDeviceContext dc, Rectangle contentBounds) { if( dc == null ){ throw new ArgumentNullException("dc"); } if (contentBounds.Width < 0 || contentBounds.Height < 0) { return Rectangle.Empty; } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeBackgroundExtent( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( contentBounds ), rect ); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetBackgroundRegion"]/*' /> /// <devdoc> /// <para> /// Computes the region for a regular or partially transparent background that is bounded by a specified /// rectangle. Return null if the region cannot be created. /// [See win32 equivalent.] /// </para> /// </devdoc> [SuppressUnmanagedCodeSecurity, SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage")] public Region GetBackgroundRegion(IDeviceContext dc, Rectangle bounds) { if (dc == null) { throw new ArgumentNullException("dc"); } if (bounds.Width < 0 || bounds.Height < 0) { return null; } IntPtr hRegion = IntPtr.Zero; using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeBackgroundRegion( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), ref hRegion ); } // GetThemeBackgroundRegion returns a null hRegion if it fails to create one, it could be because the bounding // box is too big. For more info see code in %xpsrc%\shell\themes\uxtheme\imagefile.cpp if you have an enlistment to it. if (hRegion == IntPtr.Zero) { return null; } // From the GDI+ sources it doesn't appear as if they take ownership of the hRegion, so this is safe to do. // We need to DeleteObject in order to not leak. DevDiv Bugs 169791 Region region = Region.FromHrgn(hRegion); SafeNativeMethods.ExternalDeleteObject(new HandleRef(null, hRegion)); return region; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetBoolean"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public bool GetBoolean(BooleanProperty prop) { if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)BooleanProperty.Transparent, (int)BooleanProperty.SourceShrink)){ throw new InvalidEnumArgumentException("prop", (int)prop, typeof(BooleanProperty)); } bool val = false; lastHResult = SafeNativeMethods.GetThemeBool(new HandleRef(this, Handle), part, state, (int)prop, ref val); return val; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetColor"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Color GetColor(ColorProperty prop) { //valid values are 0xed9 to 0xeef if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)ColorProperty.BorderColor, (int)ColorProperty.AccentColorHint)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(ColorProperty)); } int color = 0; lastHResult = SafeNativeMethods.GetThemeColor(new HandleRef(this, Handle), part, state, (int)prop, ref color); return ColorTranslator.FromWin32(color); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetEnumValue"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public int GetEnumValue(EnumProperty prop) { //valid values are 0xfa1 to 0xfaf if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)EnumProperty.BackgroundType, (int)EnumProperty.TrueSizeScalingType)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(EnumProperty)); } int val = 0; lastHResult = SafeNativeMethods.GetThemeEnumValue(new HandleRef(this, Handle), part, state, (int)prop, ref val); return val; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetFilename"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public string GetFilename(FilenameProperty prop) { //valid values are 0xbb9 to 0xbc0 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)FilenameProperty.ImageFile, (int)FilenameProperty.GlyphImageFile)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(FilenameProperty)); } StringBuilder filename = new StringBuilder(512); lastHResult = SafeNativeMethods.GetThemeFilename(new HandleRef(this, Handle), part, state, (int)prop, filename, filename.Capacity); return filename.ToString(); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetFont"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// Returns null if the returned font was not true type, since GDI+ does not support it. /// </para> /// </devdoc> [SuppressMessage("Microsoft.Security", "CA2102:CatchNonClsCompliantExceptionsInGeneralHandlers")] public Font GetFont(IDeviceContext dc, FontProperty prop) { if( dc == null ){ throw new ArgumentNullException("dc"); } //valid values are 0xa29 to 0xa29 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)FontProperty.GlyphFont, (int)FontProperty.GlyphFont)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(FontProperty)); } NativeMethods.LOGFONT logfont = new NativeMethods.LOGFONT(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeFont( new HandleRef( this, Handle ), hdc, part, state, (int) prop, logfont ); } Font font = null; //check for a failed HR. if (NativeMethods.Succeeded(lastHResult)) { // SECREVIEW: Safe to assert here, since the logfont comes from a native api and not from the // caller of this method. The system creates the font handle. // IntSecurity.ObjectFromWin32Handle.Assert(); try { font = Font.FromLogFont(logfont); } catch (Exception e) { if (ClientUtils.IsSecurityOrCriticalException(e)) { throw; } //Looks like the font was not true type font = null; } } return font; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetInteger"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public int GetInteger(IntegerProperty prop) { //valid values are 0x961 to 0x978 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)IntegerProperty.ImageCount, (int)IntegerProperty.MinDpi5)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(IntegerProperty)); } int val = 0; lastHResult = SafeNativeMethods.GetThemeInt(new HandleRef(this, Handle), part, state, (int)prop, ref val); return val; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetPartSize"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Size GetPartSize(IDeviceContext dc, ThemeSizeType type) { if( dc == null ){ throw new ArgumentNullException("dc"); } //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(type, (int)type, (int)ThemeSizeType.Minimum, (int)ThemeSizeType.Draw)){ throw new InvalidEnumArgumentException("type", (int)type, typeof(ThemeSizeType)); } NativeMethods.SIZE size = new NativeMethods.SIZE(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemePartSize( new HandleRef( this, Handle ), hdc, part, state, null, type, size ); } return new Size(size.cx, size.cy); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetPartSize1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Size GetPartSize(IDeviceContext dc, Rectangle bounds, ThemeSizeType type) { if( dc == null ){ throw new ArgumentNullException("dc"); } //valid values are 0x0 to 0x2 if (!ClientUtils.IsEnumValid(type, (int)type, (int)ThemeSizeType.Minimum, (int)ThemeSizeType.Draw)) { throw new InvalidEnumArgumentException("type", (int)type, typeof(ThemeSizeType)); } NativeMethods.SIZE size = new NativeMethods.SIZE(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemePartSize( new HandleRef( this, Handle ), hdc, part, state, new NativeMethods.COMRECT( bounds ), type, size ); } return new Size(size.cx, size.cy); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetPoint"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Point GetPoint(PointProperty prop) { //valid values are 0xd49 to 0xd50 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)PointProperty.Offset, (int)PointProperty.MinSize5)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(PointProperty)); } NativeMethods.POINT point = new NativeMethods.POINT(); lastHResult = SafeNativeMethods.GetThemePosition(new HandleRef(this, Handle), part, state, (int)prop, point); return new Point(point.x, point.y); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetMargins"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Padding GetMargins(IDeviceContext dc, MarginProperty prop) { if( dc == null ){ throw new ArgumentNullException("dc"); } //valid values are 0xe11 to 0xe13 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)MarginProperty.SizingMargins, (int)MarginProperty.CaptionMargins)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(MarginProperty)); } NativeMethods.MARGINS margins = new NativeMethods.MARGINS(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeMargins( new HandleRef( this, Handle ), hdc, part, state, (int) prop, ref margins ); } return new Padding(margins.cxLeftWidth, margins.cyTopHeight, margins.cxRightWidth, margins.cyBottomHeight); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetString"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public string GetString(StringProperty prop) { //valid values are 0xc81 to 0xc81 if (!ClientUtils.IsEnumValid(prop, (int)prop, (int)StringProperty.Text, (int)StringProperty.Text)) { throw new InvalidEnumArgumentException("prop", (int)prop, typeof(StringProperty)); } StringBuilder aString = new StringBuilder(512); lastHResult = SafeNativeMethods.GetThemeString(new HandleRef(this, Handle), part, state, (int)prop, aString, aString.Capacity); return aString.ToString(); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetTextExtent"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Rectangle GetTextExtent(IDeviceContext dc, string textToDraw, TextFormatFlags flags) { if( dc == null ){ throw new ArgumentNullException("dc"); } if (String.IsNullOrEmpty(textToDraw)) { throw new ArgumentNullException("textToDraw"); } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeTextExtent( new HandleRef( this, Handle ), hdc, part, state, textToDraw, textToDraw.Length, (int) flags, null, rect ); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetTextExtent1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public Rectangle GetTextExtent(IDeviceContext dc, Rectangle bounds, string textToDraw, TextFormatFlags flags) { if( dc == null ){ throw new ArgumentNullException("dc"); } if (String.IsNullOrEmpty(textToDraw)) { throw new ArgumentNullException("textToDraw"); } NativeMethods.COMRECT rect = new NativeMethods.COMRECT(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeTextExtent( new HandleRef( this, Handle ), hdc, part, state, textToDraw, textToDraw.Length, (int) flags, new NativeMethods.COMRECT( bounds ), rect ); } return Rectangle.FromLTRB(rect.left, rect.top, rect.right, rect.bottom); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetTextMetric"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public TextMetrics GetTextMetrics(IDeviceContext dc) { if( dc == null ){ throw new ArgumentNullException("dc"); } TextMetrics tm = new TextMetrics(); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.GetThemeTextMetrics( new HandleRef( this, Handle ), hdc, part, state, ref tm ); } return tm; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.HitTestBackground"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRectangle, Point pt, HitTestOptions options) { if( dc == null ){ throw new ArgumentNullException("dc"); } int htCode = 0; NativeMethods.POINTSTRUCT point = new NativeMethods.POINTSTRUCT(pt.X, pt.Y); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.HitTestThemeBackground( new HandleRef( this, Handle ), hdc, part, state, (int) options, new NativeMethods.COMRECT( backgroundRectangle ), NativeMethods.NullHandleRef, point, ref htCode ); } return (HitTestCode)htCode; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.HitTestBackground1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public HitTestCode HitTestBackground(Graphics g, Rectangle backgroundRectangle, Region region, Point pt, HitTestOptions options) { if (g == null) { throw new ArgumentNullException("g"); } IntPtr hRgn = region.GetHrgn(g); return HitTestBackground(g, backgroundRectangle, hRgn, pt, options); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.HitTestBackground1"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> // PM team has reviewed and decided on naming changes already [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly")] public HitTestCode HitTestBackground(IDeviceContext dc, Rectangle backgroundRectangle, IntPtr hRgn, Point pt, HitTestOptions options) { if( dc == null ){ throw new ArgumentNullException("dc"); } int htCode = 0; NativeMethods.POINTSTRUCT point = new NativeMethods.POINTSTRUCT(pt.X, pt.Y); using( WindowsGraphicsWrapper wgr = new WindowsGraphicsWrapper( dc, AllGraphicsProperties ) ) { HandleRef hdc = new HandleRef( wgr, wgr.WindowsGraphics.DeviceContext.Hdc ); lastHResult = SafeNativeMethods.HitTestThemeBackground( new HandleRef( this, Handle ), hdc, part, state, (int) options, new NativeMethods.COMRECT( backgroundRectangle ), new HandleRef( this, hRgn ), point, ref htCode ); } return (HitTestCode)htCode; } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.IsBackgroundPartiallyTransparent"]/*' /> /// <devdoc> /// <para> /// [See win32 equivalent.] /// </para> /// </devdoc> public bool IsBackgroundPartiallyTransparent() { return (SafeNativeMethods.IsThemeBackgroundPartiallyTransparent(new HandleRef(this, Handle), part, state)); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetLastHResult"]/*' /> /// <devdoc> /// This is similar to GetLastError in Win32. It returns the last HRESULT returned from a native call /// into theme apis. We eat the errors and let the user handle any errors that occurred. /// </devdoc> public int LastHResult { get { return lastHResult; } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.CreateThemeHandleHashTable"]/*' /> /// <devdoc> /// <para> /// Instantiates the ThemeHandle cache hashtable. /// </para> /// </devdoc> private static void CreateThemeHandleHashtable() { themeHandles = new Hashtable(numberOfPossibleClasses); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.OnThemeChanged"]/*' /> /// <devdoc> /// <para> /// Handles the ThemeChanged event. Basically, we need to ensure all per-thread theme handle /// caches are refreshed. /// </para> /// </devdoc> private static void OnUserPreferenceChanging(object sender, UserPreferenceChangingEventArgs ea) { if (ea.Category == UserPreferenceCategory.VisualStyle) { // Let all threads know their cached handles are no longer valid; // cache refresh will happen at next handle access. // Note that if the theme changes 2^sizeof(long) times before a thread uses // its handle, this whole version hack won't work, but I don't see that happening. globalCacheVersion++; } } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.RefreshCache"]/*' /> /// <devdoc> /// <para> /// Refreshes this thread's theme handle cache. /// </para> /// </devdoc> private static void RefreshCache() { ThemeHandle tHandle = null; if (themeHandles != null) { string[] classNames = new string[themeHandles.Keys.Count]; themeHandles.Keys.CopyTo(classNames, 0); // We don't call IsSupported here, since that could cause RefreshCache to be called again, // leading to stack overflow. bool isSupported = (VisualStyleInformation.IsEnabledByUser && (Application.VisualStyleState == VisualStyleState.ClientAreaEnabled || Application.VisualStyleState == VisualStyleState.ClientAndNonClientAreasEnabled)); foreach (string className in classNames) { tHandle = (ThemeHandle) themeHandles[className]; if (tHandle != null) { tHandle.Dispose(); } if (isSupported) { tHandle = ThemeHandle.Create(className, false); if (tHandle != null) { themeHandles[className] = tHandle; } } } } } private static IntPtr GetHandle(string className) { return GetHandle(className, true); } /// <include file='doc\VisualStyleRenderer.uex' path='docs/doc[@for="VisualStyleRenderer.GetHandle"]/*' /> /// <devdoc> /// <para> /// Retrieves a IntPtr theme handle for the given class from the themeHandle cache. If its not /// present in the cache, it creates a new ThemeHandle object and stores it there. /// </para> /// </devdoc> private static IntPtr GetHandle(string className, bool throwExceptionOnFail) { ThemeHandle tHandle; if (themeHandles == null) { CreateThemeHandleHashtable(); } if (threadCacheVersion != globalCacheVersion) { RefreshCache(); threadCacheVersion = globalCacheVersion; } if (!themeHandles.Contains(className)) { // see if it is already in cache tHandle = ThemeHandle.Create(className, throwExceptionOnFail); if (tHandle == null) { return IntPtr.Zero; } themeHandles.Add(className, tHandle); } else { tHandle = (ThemeHandle) themeHandles[className]; } return tHandle.NativeHandle; } // This wrapper class is needed for safely cleaning up TLS cache of handles. private class ThemeHandle : IDisposable { private IntPtr _hTheme = IntPtr.Zero; private ThemeHandle(IntPtr hTheme) { _hTheme = hTheme; } public IntPtr NativeHandle { get { return _hTheme; } } public static ThemeHandle Create(string className, bool throwExceptionOnFail) { // HThemes don't require an HWND, so just use a null one IntPtr hTheme = IntPtr.Zero; try { hTheme = SafeNativeMethods.OpenThemeData(new HandleRef(null, IntPtr.Zero), className); } catch (Exception e) { //We don't want to eat critical exceptions if (ClientUtils.IsSecurityOrCriticalException(e)) { throw; } if (throwExceptionOnFail) { throw new InvalidOperationException(SR.GetString(SR.VisualStyleHandleCreationFailed), e); } else { return null; } } if (hTheme == IntPtr.Zero) { if (throwExceptionOnFail) { throw new InvalidOperationException(SR.GetString(SR.VisualStyleHandleCreationFailed)); } else { return null; } } return new ThemeHandle(hTheme); } public void Dispose() { if (_hTheme != IntPtr.Zero) { SafeNativeMethods.CloseThemeData(new HandleRef(null, _hTheme)); _hTheme = IntPtr.Zero; } GC.SuppressFinalize(this); } ~ThemeHandle() { Dispose(); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * 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 ShiftLeftLogical128BitLaneInt321() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321 { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Int32); private const int RetElementCount = VectorSize / sizeof(Int32); private static Int32[] _data = new Int32[Op1ElementCount]; private static Vector128<Int32> _clsVar; private Vector128<Int32> _fld; private SimpleUnaryOpTest__DataTable<Int32, Int32> _dataTable; static SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); } public SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld), ref Unsafe.As<Int32, byte>(ref _data[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (int)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, Int32>(_data, new Int32[RetElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Int32>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<Int32>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ShiftLeftLogical128BitLaneInt321(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int32[] inArray = new Int32[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int32[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != 2048) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 2048) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical128BitLane)}<Int32>(Vector128<Int32><9>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// 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 CompareGreaterThanSingle() { var test = new SimpleBinaryOpTest__CompareGreaterThanSingle(); 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(); // 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 works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__CompareGreaterThanSingle { private const int VectorSize = 16; private const int Op1ElementCount = VectorSize / sizeof(Single); private const int Op2ElementCount = VectorSize / sizeof(Single); private const int RetElementCount = VectorSize / 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 SimpleBinaryOpTest__DataTable<Single, Single, Single> _dataTable; static SimpleBinaryOpTest__CompareGreaterThanSingle() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _clsVar2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); } public SimpleBinaryOpTest__CompareGreaterThanSingle() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld1), ref Unsafe.As<Single, byte>(ref _data1[0]), VectorSize); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Single>, byte>(ref _fld2), ref Unsafe.As<Single, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = (float)(random.NextDouble()); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = (float)(random.NextDouble()); } _dataTable = new SimpleBinaryOpTest__DataTable<Single, Single, Single>(_data1, _data2, new Single[RetElementCount], VectorSize); } public bool IsSupported => Sse.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse.CompareGreaterThan( 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() { var result = Sse.CompareGreaterThan( 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() { var result = Sse.CompareGreaterThan( 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() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThan), 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() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThan), 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() { var result = typeof(Sse).GetMethod(nameof(Sse.CompareGreaterThan), 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() { var result = Sse.CompareGreaterThan( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Single>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Single>>(_dataTable.inArray2Ptr); var result = Sse.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse.LoadVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray1Ptr)); var right = Sse.LoadAlignedVector128((Single*)(_dataTable.inArray2Ptr)); var result = Sse.CompareGreaterThan(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__CompareGreaterThanSingle(); var result = Sse.CompareGreaterThan(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse.CompareGreaterThan(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Single> left, Vector128<Single> right, void* result, [CallerMemberName] string method = "") { Single[] inArray1 = new Single[Op1ElementCount]; Single[] inArray2 = new Single[Op2ElementCount]; Single[] outArray = new Single[RetElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { 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>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Single, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Single[] left, Single[] right, Single[] result, [CallerMemberName] string method = "") { if (BitConverter.SingleToInt32Bits(result[0]) != ((left[0] > right[0]) ? -1 : 0)) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (BitConverter.SingleToInt32Bits(result[i]) != ((left[i] > right[i]) ? -1 : 0)) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse)}.{nameof(Sse.CompareGreaterThan)}<Single>(Vector128<Single>, Vector128<Single>): {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
//--------------------------------------------------------------------- // <copyright file="ArraySet.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <summary> // a set, collection of unordered, distinct objects, implemented as an array // </summary> //--------------------------------------------------------------------- namespace System.Data.Services.Client { using System; using System.Collections.Generic; using System.Diagnostics; /// <summary>a set, collection of unordered, distinct objects, implemented as an array</summary> /// <typeparam name="T">element type</typeparam> [DebuggerDisplay("Count = {count}")] internal struct ArraySet<T> : IEnumerable<T> where T : class { /// <summary>item array of T</summary> private T[] items; /// <summary>count of elements in the items array</summary> private int count; /// <summary>number of Add and RemoveAt operations</summary> private int version; /// <summary> /// array set with an intial capacity /// </summary> /// <param name="capacity">initial capacity</param> public ArraySet(int capacity) { this.items = new T[capacity]; this.count = 0; this.version = 0; } /// <summary>count of elements in the set</summary> public int Count { get { return this.count; } } /// <summary>get an item from an index in the set</summary> /// <param name="index">index to access</param> public T this[int index] { get { Debug.Assert(index < this.count); return this.items[index]; } } /// <summary>add new element to the set</summary> /// <param name="item">element to add</param> /// <param name="equalityComparer">equality comparison function to avoid duplicates</param> /// <returns>true if actually added, false if a duplicate was discovered</returns> public bool Add(T item, Func<T, T, bool> equalityComparer) { if ((null != equalityComparer) && this.Contains(item, equalityComparer)) { return false; } int index = this.count++; if ((null == this.items) || (index == this.items.Length)) { // grow array in size, with minimum size being 32 Array.Resize<T>(ref this.items, Math.Min(Math.Max(index, 16), Int32.MaxValue / 2) * 2); } this.items[index] = item; unchecked { this.version++; } return true; } /// <summary>is the element contained within the set</summary> /// <param name="item">item to find</param> /// <param name="equalityComparer">comparer</param> /// <returns>true if the element is contained</returns> public bool Contains(T item, Func<T, T, bool> equalityComparer) { return (0 <= this.IndexOf(item, equalityComparer)); } /// <summary> /// enumerator /// </summary> /// <returns>enumerator</returns> public IEnumerator<T> GetEnumerator() { for (int i = 0; i < this.count; ++i) { yield return this.items[i]; } } /// <summary> /// enumerator /// </summary> /// <returns>enumerator</returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } /// <summary>Find the current index of element within the set</summary> /// <param name="item">item to find</param> /// <param name="comparer">comparision function</param> /// <returns>index of the item else (-1)</returns> public int IndexOf(T item, Func<T, T, bool> comparer) { return this.IndexOf(item, IdentitySelect, comparer); } /// <summary>Find the current index of element within the set</summary> /// <typeparam name="K">selected type</typeparam> /// <param name="item">item to find</param> /// <param name="select">selector for item to compare</param> /// <param name="comparer">item to compare</param> /// <returns>index of the item else (-1)</returns> public int IndexOf<K>(K item, Func<T, K> select, Func<K, K, bool> comparer) { T[] array = this.items; if (null != array) { int length = this.count; for (int i = 0; i < length; ++i) { if (comparer(item, select(array[i]))) { return i; } } } return -1; } /// <summary>Remove the matched item from within the set</summary> /// <param name="item">item to find within the set</param> /// <param name="equalityComparer">comparer to find item to remove</param> /// <returns>the item that was actually contained else its default</returns> public T Remove(T item, Func<T, T, bool> equalityComparer) { int index = this.IndexOf(item, equalityComparer); if (0 <= index) { item = this.items[index]; this.RemoveAt(index); return item; } return default(T); } /// <summary>Remove an item at a specific index from within the set</summary> /// <param name="index">index of item to remove within the set</param> public void RemoveAt(int index) { Debug.Assert(unchecked((uint)index < (uint)this.count), "index out of range"); T[] array = this.items; int lastIndex = --this.count; array[index] = array[lastIndex]; array[lastIndex] = default(T); if ((0 == lastIndex) && (256 <= array.Length)) { this.items = null; } else if ((256 < array.Length) && (lastIndex < array.Length / 4)) { // shrink to half size when count is a quarter Array.Resize(ref this.items, array.Length / 2); } unchecked { this.version++; } } /// <summary>Sort array based on selected value out of item being stored</summary> /// <typeparam name="K">selected type</typeparam> /// <param name="selector">selector</param> /// <param name="comparer">comparer</param> public void Sort<K>(Func<T, K> selector, Func<K, K, int> comparer) { if (null != this.items) { SelectorComparer<K> scomp; scomp.Selector = selector; scomp.Comparer = comparer; Array.Sort<T>(this.items, 0, this.count, scomp); } } /// <summary>Sets the capacity to the actual number of elements in the ArraySet.</summary> public void TrimToSize() { Array.Resize(ref this.items, this.count); } /// <summary>identity selector, returns self</summary> /// <param name="arg">input</param> /// <returns>output</returns> private static T IdentitySelect(T arg) { return arg; } /// <summary>Compare selected value out of t</summary> /// <typeparam name="K">comparison type</typeparam> private struct SelectorComparer<K> : IComparer<T> { /// <summary>Select something out of T</summary> internal Func<T, K> Selector; /// <summary>Comparer of selected value</summary> internal Func<K, K, int> Comparer; /// <summary>Compare</summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <returns>int</returns> int IComparer<T>.Compare(T x, T y) { return this.Comparer(this.Selector(x), this.Selector(y)); } } } }
////////////////////////////////////////////////// // Generated code by BareNET - 08.10.2021 14:58 // ////////////////////////////////////////////////// using System; using System.Linq; using System.Collections.Generic; namespace DM7_PPLUS_Integration.Messages.DM7 { public readonly struct Query_message { public readonly byte[] Value; public Query_message(byte[] value) { Value = value; } public byte[] Encoded() { return BareNET.Bare.Encode_data(Value); } public static Query_message Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Query_message, byte[]> Decode(byte[] data) { var value = BareNET.Bare.Decode_data(data); return new ValueTuple<Query_message, byte[]>( new Query_message(value.Item1), value.Item2); } } public interface Response_message { /* Base type of union */ } public readonly struct Query_succeeded : Response_message { public readonly byte[] Value; public Query_succeeded(byte[] value) { Value = value; } public byte[] Encoded() { return BareNET.Bare.Encode_data(Value); } public static Query_succeeded Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Query_succeeded, byte[]> Decode(byte[] data) { var value = BareNET.Bare.Decode_data(data); return new ValueTuple<Query_succeeded, byte[]>( new Query_succeeded(value.Item1), value.Item2); } } public readonly struct Query_failed : Response_message { public readonly string Reason; public Query_failed(string reason) { Reason = reason; } public byte[] Encoded() { return BareNET.Bare.Encode_string(Reason); } public static Query_failed Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Query_failed, byte[]> Decode(byte[] data) { var reason = BareNET.Bare.Decode_string(data); return new ValueTuple<Query_failed, byte[]>( new Query_failed(reason.Item1), reason.Item2); } } public readonly struct Capabilities { public readonly List<Capability> Value; public Capabilities(List<Capability> value) { Value = value; } public byte[] Encoded() { return BareNET.Bare.Encode_list(Value, ValueList => Encoding.Capability_Encoded(ValueList)); } public static Capabilities Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Capabilities, byte[]> Decode(byte[] data) { var value = BareNET.Bare.Decode_list(data, dataList => Encoding.Decode_Capability(dataList)); return new ValueTuple<Capabilities, byte[]>( new Capabilities(value.Item1.ToList()), value.Item2); } } public enum Capability { ALLE_LEISTUNGEN_V1, ALLE_MANDANTEN_V1 } public interface Query { /* Base type of union */ } public readonly struct Alle_leistungen_V1 : Query { public byte[] Encoded() { return new byte[0]; } public static Alle_leistungen_V1 Decoded(byte[] data) { return new Alle_leistungen_V1(); } public static ValueTuple<Alle_leistungen_V1, byte[]> Decode(byte[] data) { return new ValueTuple<Alle_leistungen_V1, byte[]>(new Alle_leistungen_V1(), data); } } public readonly struct Alle_mandanten_V1 : Query { public byte[] Encoded() { return new byte[0]; } public static Alle_mandanten_V1 Decoded(byte[] data) { return new Alle_mandanten_V1(); } public static ValueTuple<Alle_mandanten_V1, byte[]> Decode(byte[] data) { return new ValueTuple<Alle_mandanten_V1, byte[]>(new Alle_mandanten_V1(), data); } } public interface Query_result { /* Base type of union */ } public readonly struct IO_fehler : Query_result { public readonly string Reason; public IO_fehler(string reason) { Reason = reason; } public byte[] Encoded() { return BareNET.Bare.Encode_string(Reason); } public static IO_fehler Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<IO_fehler, byte[]> Decode(byte[] data) { var reason = BareNET.Bare.Decode_string(data); return new ValueTuple<IO_fehler, byte[]>( new IO_fehler(reason.Item1), reason.Item2); } } public readonly struct Leistungen_V1 : Query_result { public readonly List<Leistung_V1> Value; public Leistungen_V1(List<Leistung_V1> value) { Value = value; } public byte[] Encoded() { return BareNET.Bare.Encode_list(Value, ValueList => ValueList.Encoded()); } public static Leistungen_V1 Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Leistungen_V1, byte[]> Decode(byte[] data) { var value = BareNET.Bare.Decode_list(data, dataList => Leistung_V1.Decode(dataList)); return new ValueTuple<Leistungen_V1, byte[]>( new Leistungen_V1(value.Item1.ToList()), value.Item2); } } public readonly struct Mandanten_V1 : Query_result { public readonly List<Mandant_V1> Value; public Mandanten_V1(List<Mandant_V1> value) { Value = value; } public byte[] Encoded() { return BareNET.Bare.Encode_list(Value, ValueList => ValueList.Encoded()); } public static Mandanten_V1 Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Mandanten_V1, byte[]> Decode(byte[] data) { var value = BareNET.Bare.Decode_list(data, dataList => Mandant_V1.Decode(dataList)); return new ValueTuple<Mandanten_V1, byte[]>( new Mandanten_V1(value.Item1.ToList()), value.Item2); } } public readonly struct Leistung_V1 { public readonly UUID Id; public readonly string Bezeichnung; public Leistung_V1(UUID id, string bezeichnung) { Id = id; Bezeichnung = bezeichnung; } public byte[] Encoded() { return Id.Encoded() .Concat(BareNET.Bare.Encode_string(Bezeichnung)) .ToArray(); } public static Leistung_V1 Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Leistung_V1, byte[]> Decode(byte[] data) { var id = UUID.Decode(data); var bezeichnung = BareNET.Bare.Decode_string(id.Item2); return new ValueTuple<Leistung_V1, byte[]>( new Leistung_V1(id.Item1, bezeichnung.Item1), bezeichnung.Item2); } } public readonly struct Mandant_V1 { public readonly UUID Id; public readonly string Bezeichnung; public Mandant_V1(UUID id, string bezeichnung) { Id = id; Bezeichnung = bezeichnung; } public byte[] Encoded() { return Id.Encoded() .Concat(BareNET.Bare.Encode_string(Bezeichnung)) .ToArray(); } public static Mandant_V1 Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<Mandant_V1, byte[]> Decode(byte[] data) { var id = UUID.Decode(data); var bezeichnung = BareNET.Bare.Decode_string(id.Item2); return new ValueTuple<Mandant_V1, byte[]>( new Mandant_V1(id.Item1, bezeichnung.Item1), bezeichnung.Item2); } } public readonly struct UUID { public readonly byte[] Value; public UUID(byte[] value) { if (value.Length != 16) throw new ArgumentException("Length of list must be 16", nameof(value)); Value = value; } public byte[] Encoded() { return BareNET.Bare.Encode_data_fixed_length(16, Value); } public static UUID Decoded(byte[] data) { return Decode(data).Item1; } public static ValueTuple<UUID, byte[]> Decode(byte[] data) { var value = BareNET.Bare.Decode_data_fixed_length(16, data); return new ValueTuple<UUID, byte[]>( new UUID(value.Item1), value.Item2); } } public static class Encoding { private static readonly BareNET.Union<Response_message> _Response_message = BareNET.Union<Response_message>.Register() .With_Case<Query_succeeded>(v => ((Query_succeeded) v).Encoded(), d => { var decoded = Query_succeeded.Decode(d); return new ValueTuple<Response_message, byte[]>(decoded.Item1, decoded.Item2); }) .With_Case<Query_failed>(v => ((Query_failed) v).Encoded(), d => { var decoded = Query_failed.Decode(d); return new ValueTuple<Response_message, byte[]>(decoded.Item1, decoded.Item2); }); public static byte[] Response_message_Encoded(Response_message value) { return BareNET.Bare.Encode_union(value, _Response_message); } public static Response_message Response_message_Decoded(byte[] data) { return Decode_Response_message(data).Item1; } public static ValueTuple<Response_message, byte[]> Decode_Response_message(byte[] data) { return BareNET.Bare.Decode_union<Response_message>(data, _Response_message); } public static byte[] Capability_Encoded(Capability value) { return BareNET.Bare.Encode_enum(value); } public static Capability Capability_Decoded(byte[] data) { return Decode_Capability(data).Item1; } public static ValueTuple<Capability, byte[]> Decode_Capability(byte[] data) { return BareNET.Bare.Decode_enum<Capability>(data); } private static readonly BareNET.Union<Query> _Query = BareNET.Union<Query>.Register() .With_Case<Alle_leistungen_V1>(v => ((Alle_leistungen_V1) v).Encoded(), d => { var decoded = Alle_leistungen_V1.Decode(d); return new ValueTuple<Query, byte[]>(decoded.Item1, decoded.Item2); }) .With_Case<Alle_mandanten_V1>(v => ((Alle_mandanten_V1) v).Encoded(), d => { var decoded = Alle_mandanten_V1.Decode(d); return new ValueTuple<Query, byte[]>(decoded.Item1, decoded.Item2); }); public static byte[] Query_Encoded(Query value) { return BareNET.Bare.Encode_union(value, _Query); } public static Query Query_Decoded(byte[] data) { return Decode_Query(data).Item1; } public static ValueTuple<Query, byte[]> Decode_Query(byte[] data) { return BareNET.Bare.Decode_union<Query>(data, _Query); } private static readonly BareNET.Union<Query_result> _Query_result = BareNET.Union<Query_result>.Register() .With_Case<IO_fehler>(v => ((IO_fehler) v).Encoded(), d => { var decoded = IO_fehler.Decode(d); return new ValueTuple<Query_result, byte[]>(decoded.Item1, decoded.Item2); }) .With_Case<Leistungen_V1>(v => ((Leistungen_V1) v).Encoded(), d => { var decoded = Leistungen_V1.Decode(d); return new ValueTuple<Query_result, byte[]>(decoded.Item1, decoded.Item2); }) .With_Case<Mandanten_V1>(v => ((Mandanten_V1) v).Encoded(), d => { var decoded = Mandanten_V1.Decode(d); return new ValueTuple<Query_result, byte[]>(decoded.Item1, decoded.Item2); }); public static byte[] Query_result_Encoded(Query_result value) { return BareNET.Bare.Encode_union(value, _Query_result); } public static Query_result Query_result_Decoded(byte[] data) { return Decode_Query_result(data).Item1; } public static ValueTuple<Query_result, byte[]> Decode_Query_result(byte[] data) { return BareNET.Bare.Decode_union<Query_result>(data, _Query_result); } } }
#region [Copyright (c) 2015 Cristian Alexandru Geambasu] // Distributed under the terms of an MIT-style license: // // The MIT License // // Copyright (c) 2015 Cristian Alexandru Geambasu // // 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 UnityEngine; using UnityEditor; using System; using System.Linq; using System.Collections; using System.Collections.Generic; using TeamUtility.IO; using TeamUtilityEditor.IO.InputManager; using _InputManager = TeamUtility.IO.InputManager; namespace TeamUtilityEditor.IO { public sealed class AdvancedInputEditor : EditorWindow { #region [Menu Options] public enum FileMenuOptions { OverriteInputSettings = 0, CreateSnapshot, LoadSnapshot, Export, Import, ImportJoystickMapping, ConfigureForInputAdapter, CreateDefaultInputConfig } public enum EditMenuOptions { NewInputConfiguration = 0, NewAxisConfiguration, Duplicate, Delete, DeleteAll, SelectTarget, IgnoreTimescale, DontDestroyOnLoad, Copy, Paste } #endregion #region [SearchResult] [Serializable] private class SearchResult { public int configuration; public List<int> axes; public SearchResult() { configuration = 0; axes = new List<int>(); } public SearchResult(int configuration, IEnumerable<int> axes) { this.configuration = configuration; this.axes = new List<int>(axes); } } #endregion #region [Fields] [SerializeField] private _InputManager _inputManager; [SerializeField] private List<SearchResult> _searchResults; [SerializeField] private List<int> _selectionPath; [SerializeField] private Vector2 _hierarchyScrollPos = Vector2.zero; [SerializeField] private Vector2 _mainPanelScrollPos = Vector2.zero; [SerializeField] private float _hierarchyPanelWidth = _menuWidth * 2; [SerializeField] private Texture2D _highlightTexture; [SerializeField] private string _searchString = ""; [SerializeField] private string _keyString = string.Empty; private AxisConfiguration _copySource; private GUIStyle _whiteLabel; private GUIStyle _whiteFoldout; private GUIStyle _warningLabel; private float _minCursorRectWidth = 10.0f; private float _maxCursorRectWidth = 50.0f; private float _toolbarHeight = 18.0f; private float _hierarchyItemHeight = 18.0f; private bool _isResizingHierarchy = false; private bool _editingPositiveKey = false; private bool _editingAltPositiveKey = false; private bool _editingNegativeKey = false; private bool _editingAltNegativeKey = false; private bool _tryedToFindInputManagerInScene = false; private string[] _axisOptions = new string[] { "X", "Y", "3rd(Scrollwheel)", "4th", "5th", "6th", "7th", "8th", "9th", "10th" }; private string[] _joystickOptions = new string[] { "Joystick 1", "Joystick 2", "Joystick 3", "Joystick 4" }; private const float _menuWidth = 100.0f; private const float _minHierarchyPanelWidth = 150.0f; #endregion private void OnEnable() { EditorToolbox.ShowStartupWarning(); IsOpen = true; _tryedToFindInputManagerInScene = false; if(_inputManager == null) _inputManager = UnityEngine.Object.FindObjectOfType(typeof(_InputManager)) as _InputManager; if(_selectionPath == null) _selectionPath = new List<int>(); if(_searchResults == null) _searchResults = new List<SearchResult>(); if(_highlightTexture == null) CreateHighlightTexture(); EditorApplication.playmodeStateChanged += HandlePlayModeChanged; } private void OnDisable() { IsOpen = false; Texture2D.DestroyImmediate(_highlightTexture); _highlightTexture = null; _copySource = null; EditorApplication.playmodeStateChanged -= HandlePlayModeChanged; } private void CreateHighlightTexture() { _highlightTexture = new Texture2D(1, 1); _highlightTexture.SetPixel(0, 0, new Color32(50, 125, 255, 255)); _highlightTexture.Apply(); } private void ValidateGUIStyles() { if(_whiteLabel == null) { _whiteLabel = new GUIStyle(EditorStyles.label); _whiteLabel.normal.textColor = Color.white; } if(_whiteFoldout == null) { _whiteFoldout = new GUIStyle(EditorStyles.foldout); _whiteFoldout.normal.textColor = Color.white; _whiteFoldout.onNormal.textColor = Color.white; _whiteFoldout.active.textColor = Color.white; _whiteFoldout.onActive.textColor = Color.white; _whiteFoldout.focused.textColor = Color.white; _whiteFoldout.onFocused.textColor = Color.white; } if(_warningLabel == null) { _warningLabel = new GUIStyle(EditorStyles.largeLabel); _warningLabel.alignment = TextAnchor.MiddleCenter; _warningLabel.fontStyle = FontStyle.Bold; _warningLabel.fontSize = 14; } } public void AddInputConfiguration(InputConfiguration configuration) { _inputManager.inputConfigurations.Add(configuration); _selectionPath.Clear(); _selectionPath.Add(_inputManager.inputConfigurations.Count - 1); Repaint(); } private void ExportInputConfigurations() { string file = EditorUtility.SaveFilePanel("Export input profile", "", "profile.xml", "xml"); if(string.IsNullOrEmpty(file)) return; InputSaverXML inputSaver = new InputSaverXML(file); inputSaver.Save(_inputManager.GetSaveParameters()); if(file.StartsWith(Application.dataPath)) AssetDatabase.Refresh(); } private void ImportInputConfigurations() { string file = EditorUtility.OpenFilePanel("Import input profile", "", "xml"); if(string.IsNullOrEmpty(file)) return; bool replace = EditorUtility.DisplayDialog("Replace or Append", "Do you want to replace the current input configrations?", "Replace", "Append"); if(replace) { InputLoaderXML inputLoader = new InputLoaderXML(file); _inputManager.Load(inputLoader.Load()); _selectionPath.Clear(); } else { InputLoaderXML inputLoader = new InputLoaderXML(file); var parameters = inputLoader.Load(); if(parameters.inputConfigurations != null && parameters.inputConfigurations.Count > 0) { foreach(var config in parameters.inputConfigurations) { _inputManager.inputConfigurations.Add(config); } } } if(_searchString.Length > 0) { UpdateSearchResults(); } Repaint(); } private void LoadInputConfigurationsFromResource(string resourcePath) { if(_inputManager.inputConfigurations.Count > 0) { bool cont = EditorUtility.DisplayDialog("Warning", "This operation will replace the current input configrations!\nDo you want to continue?", "Yes", "No"); if(!cont) return; } TextAsset textAsset = Resources.Load<TextAsset>(resourcePath); if(textAsset != null) { using(System.IO.StringReader reader = new System.IO.StringReader(textAsset.text)) { InputLoaderXML inputLoader = new InputLoaderXML(reader); _inputManager.Load(inputLoader.Load()); _selectionPath.Clear(); } } else { EditorUtility.DisplayDialog("Error", "Failed to load input configurations. The resource file might have been deleted or renamed.", "OK"); } } private void TryToFindInputManagerInScene() { _inputManager = UnityEngine.Object.FindObjectOfType(typeof(_InputManager)) as _InputManager; _tryedToFindInputManagerInScene = true; } private void HandlePlayModeChanged() { if(_inputManager == null) TryToFindInputManagerInScene(); } #region [Menus] private void CreateFileMenu(Rect position) { GenericMenu fileMenu = new GenericMenu(); fileMenu.AddItem(new GUIContent("Overwrite Input Settings"), false, HandleFileMenuOption, FileMenuOptions.OverriteInputSettings); fileMenu.AddItem(new GUIContent("Default Input Configuration"), false, HandleFileMenuOption, FileMenuOptions.CreateDefaultInputConfig); if(EditorToolbox.HasInputAdapterAddon()) fileMenu.AddItem(new GUIContent("Configure For Input Adapter"), false, HandleFileMenuOption, FileMenuOptions.ConfigureForInputAdapter); fileMenu.AddSeparator(""); if(_inputManager.inputConfigurations.Count > 0) fileMenu.AddItem(new GUIContent("Create Snapshot"), false, HandleFileMenuOption, FileMenuOptions.CreateSnapshot); else fileMenu.AddDisabledItem(new GUIContent("Create Snapshot")); if(EditorToolbox.CanLoadSnapshot()) fileMenu.AddItem(new GUIContent("Restore Snapshot"), false, HandleFileMenuOption, FileMenuOptions.LoadSnapshot); else fileMenu.AddDisabledItem(new GUIContent("Restore Snapshot")); fileMenu.AddSeparator(""); if(_inputManager.inputConfigurations.Count > 0) fileMenu.AddItem(new GUIContent("Export"), false, HandleFileMenuOption, FileMenuOptions.Export); else fileMenu.AddDisabledItem(new GUIContent("Export")); fileMenu.AddItem(new GUIContent("Import"), false, HandleFileMenuOption, FileMenuOptions.Import); if(EditorToolbox.HasJoystickMappingAddon()) fileMenu.AddItem(new GUIContent("Import Joystick Mapping"), false, HandleFileMenuOption, FileMenuOptions.ImportJoystickMapping); fileMenu.DropDown(position); } private void HandleFileMenuOption(object arg) { FileMenuOptions option = (FileMenuOptions)arg; switch(option) { case FileMenuOptions.OverriteInputSettings: EditorToolbox.OverwriteInputSettings(); break; case FileMenuOptions.CreateSnapshot: EditorToolbox.CreateSnapshot(_inputManager); break; case FileMenuOptions.LoadSnapshot: EditorToolbox.LoadSnapshot(_inputManager); break; case FileMenuOptions.Export: ExportInputConfigurations(); break; case FileMenuOptions.Import: ImportInputConfigurations(); break; case FileMenuOptions.ImportJoystickMapping: EditorToolbox.OpenImportJoystickMappingWindow(this); break; case FileMenuOptions.ConfigureForInputAdapter: LoadInputConfigurationsFromResource(ResourcePaths.INPUT_ADAPTER_DEFAULT_CONFIG); break; case FileMenuOptions.CreateDefaultInputConfig: LoadInputConfigurationsFromResource(ResourcePaths.INPUT_MANAGER_DEFAULT_CONFIG); break; } } private void CreateEditMenu(Rect position) { GenericMenu editMenu = new GenericMenu(); editMenu.AddItem(new GUIContent("New Configuration"), false, HandleEditMenuOption, EditMenuOptions.NewInputConfiguration); if(_selectionPath.Count >= 1) editMenu.AddItem(new GUIContent("New Axis"), false, HandleEditMenuOption, EditMenuOptions.NewAxisConfiguration); else editMenu.AddDisabledItem(new GUIContent("New Axis")); editMenu.AddSeparator(""); if(_selectionPath.Count > 0) editMenu.AddItem(new GUIContent("Duplicate Shift+D"), false, HandleEditMenuOption, EditMenuOptions.Duplicate); else editMenu.AddDisabledItem(new GUIContent("Duplicate Shift+D")); if(_selectionPath.Count > 0) editMenu.AddItem(new GUIContent("Delete Del"), false, HandleEditMenuOption, EditMenuOptions.Delete); else editMenu.AddDisabledItem(new GUIContent("Delete Del")); if(_inputManager.inputConfigurations.Count > 0) editMenu.AddItem(new GUIContent("Delete All"), false, HandleEditMenuOption, EditMenuOptions.DeleteAll); else editMenu.AddDisabledItem(new GUIContent("Delete All")); if(_selectionPath.Count >= 2) editMenu.AddItem(new GUIContent("Copy"), false, HandleEditMenuOption, EditMenuOptions.Copy); else editMenu.AddDisabledItem(new GUIContent("Copy")); if(_copySource != null && _selectionPath.Count >= 2) editMenu.AddItem(new GUIContent("Paste"), false, HandleEditMenuOption, EditMenuOptions.Paste); else editMenu.AddDisabledItem(new GUIContent("Paste")); editMenu.AddSeparator(""); editMenu.AddItem(new GUIContent("Select Target"), false, HandleEditMenuOption, EditMenuOptions.SelectTarget); editMenu.AddItem(new GUIContent("Ignore Timescale"), _inputManager.ignoreTimescale, HandleEditMenuOption, EditMenuOptions.IgnoreTimescale); editMenu.AddItem(new GUIContent("Dont Destroy On Load"), _inputManager.dontDestroyOnLoad, HandleEditMenuOption, EditMenuOptions.DontDestroyOnLoad); editMenu.DropDown(position); } private void HandleEditMenuOption(object arg) { EditMenuOptions option = (EditMenuOptions)arg; switch(option) { case EditMenuOptions.NewInputConfiguration: CreateNewInputConfiguration(); break; case EditMenuOptions.NewAxisConfiguration: CreateNewAxisConfiguration(); break; case EditMenuOptions.Duplicate: Duplicate(); break; case EditMenuOptions.Delete: Delete(); break; case EditMenuOptions.DeleteAll: DeleteAll(); break; case EditMenuOptions.SelectTarget: Selection.activeGameObject = _inputManager.gameObject; break; case EditMenuOptions.IgnoreTimescale: _inputManager.ignoreTimescale = !_inputManager.ignoreTimescale; break; case EditMenuOptions.DontDestroyOnLoad: _inputManager.dontDestroyOnLoad = !_inputManager.dontDestroyOnLoad; break; case EditMenuOptions.Copy: CopySelectedAxisConfig(); break; case EditMenuOptions.Paste: PasteAxisConfig(); break; } } private void CreateNewInputConfiguration() { _inputManager.inputConfigurations.Add(new InputConfiguration()); _selectionPath.Clear(); _selectionPath.Add(_inputManager.inputConfigurations.Count - 1); Repaint(); } private void CreateNewAxisConfiguration() { if(_selectionPath.Count >= 1) { InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]]; inputConfig.axes.Add(new AxisConfiguration()); inputConfig.isExpanded = true; if(_selectionPath.Count == 2) { _selectionPath[1] = inputConfig.axes.Count - 1; } else { _selectionPath.Add(inputConfig.axes.Count - 1); } Repaint(); } } private void Duplicate() { if(_selectionPath.Count == 1) { DuplicateInputConfiguration(); } else if(_selectionPath.Count == 2) { DuplicateAxisConfiguration(); } } private void DuplicateAxisConfiguration() { InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]]; AxisConfiguration source = inputConfig.axes[_selectionPath[1]]; AxisConfiguration axisConfig = AxisConfiguration.Duplicate(source); if(_selectionPath[1] < inputConfig.axes.Count - 1) { inputConfig.axes.Insert(_selectionPath[1], axisConfig); _selectionPath[1]++; } else { inputConfig.axes.Add(axisConfig); _selectionPath[1] = inputConfig.axes.Count - 1; } if(_searchString.Length > 0) { UpdateSearchResults(); } Repaint(); } private void DuplicateInputConfiguration() { InputConfiguration source = _inputManager.inputConfigurations[_selectionPath[0]]; InputConfiguration inputConfig = InputConfiguration.Duplicate(source); if(_selectionPath[0] < _inputManager.inputConfigurations.Count - 1) { _inputManager.inputConfigurations.Insert(_selectionPath[0] + 1, inputConfig); _selectionPath[0]++; } else { _inputManager.inputConfigurations.Add(inputConfig); _selectionPath[0] = _inputManager.inputConfigurations.Count - 1; } if(_searchString.Length > 0) { UpdateSearchResults(); } Repaint(); } private void Delete() { if(_selectionPath.Count == 1) { _inputManager.inputConfigurations.RemoveAt(_selectionPath[0]); Repaint(); } else if(_selectionPath.Count == 2) { _inputManager.inputConfigurations[_selectionPath[0]].axes.RemoveAt(_selectionPath[1]); Repaint(); } _selectionPath.Clear(); if(_searchString.Length > 0) { UpdateSearchResults(); } } private void DeleteAll() { _inputManager.inputConfigurations.Clear(); _inputManager.playerOneDefault = string.Empty; _inputManager.playerTwoDefault = string.Empty; _inputManager.playerThreeDefault = string.Empty; _inputManager.playerFourDefault = string.Empty; _selectionPath.Clear(); if(_searchString.Length > 0) { UpdateSearchResults(); } Repaint(); } private void CopySelectedAxisConfig() { if(_copySource == null) _copySource = new AxisConfiguration(); InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]]; AxisConfiguration axisConfig = inputConfig.axes[_selectionPath[1]]; _copySource.Copy(axisConfig); } private void PasteAxisConfig() { InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]]; AxisConfiguration axisConfig = inputConfig.axes[_selectionPath[1]]; axisConfig.Copy(_copySource); } private void UpdateSearchResults() { _searchResults.Clear(); for(int i = 0; i < _inputManager.inputConfigurations.Count; i++) { IEnumerable<int> axes = from a in _inputManager.inputConfigurations[i].axes where (a.name.IndexOf(_searchString, System.StringComparison.InvariantCultureIgnoreCase) >= 0) select _inputManager.inputConfigurations[i].axes.IndexOf(a); if(axes.Count() > 0) { _searchResults.Add(new SearchResult(i, axes)); } } } #endregion #region [OnGUI] private void OnGUI() { ValidateGUIStyles(); if(_inputManager == null && !_tryedToFindInputManagerInScene) TryToFindInputManagerInScene(); if(_inputManager == null) { DisplayMissingInputManagerWarning(); return; } Undo.RecordObject(_inputManager, "InputManager"); UpdateHierarchyPanelWidth(); if(_searchString.Length > 0) { DisplaySearchResults(); } else { DisplayHierarchyPanel(); } if(_selectionPath.Count >= 1) { DisplayMainPanel(); } DisplayMainToolbar(); if(GUI.changed) EditorUtility.SetDirty(_inputManager); } private void DisplayMissingInputManagerWarning() { Rect warningRect = new Rect(0.0f, 20.0f, position.width, 40.0f); Rect buttonRect = new Rect(position.width / 2 - 100.0f, warningRect.yMax, 200.0f, 25.0f); EditorGUI.LabelField(warningRect, "Could not find an input manager instance in the scene!", _warningLabel); if(GUI.Button(buttonRect, "Try Again")) { TryToFindInputManagerInScene(); } } private void DisplayMainToolbar() { Rect screenRect = new Rect(0.0f, 0.0f, position.width, _toolbarHeight); Rect fileMenuRect = new Rect(0.0f, 0.0f, _menuWidth, screenRect.height); Rect editMenuRect = new Rect(fileMenuRect.xMax, 0.0f, _menuWidth, screenRect.height); Rect paddingLabelRect = new Rect(editMenuRect.xMax, 0.0f, screenRect.width - _menuWidth * 2, screenRect.height); Rect searchFieldRect = new Rect(screenRect.width - (_menuWidth * 1.5f + 5.0f), 2.0f, _menuWidth * 1.5f, screenRect.height - 2.0f); int lastSearchStringLength = _searchString.Length; GUI.BeginGroup(screenRect); DisplayFileMenu(fileMenuRect); DisplayEditMenu(editMenuRect); EditorGUI.LabelField(paddingLabelRect, "", EditorStyles.toolbarButton); GUILayout.BeginArea(searchFieldRect); _searchString = EditorToolbox.SearchField(_searchString); GUILayout.EndArea(); GUI.EndGroup(); if(lastSearchStringLength != _searchString.Length) { UpdateSearchResults(); } } private void DisplayFileMenu(Rect screenRect) { EditorGUI.LabelField(screenRect, "File", EditorStyles.toolbarDropDown); if(Event.current.type == EventType.MouseDown && Event.current.button == 0 && screenRect.Contains(Event.current.mousePosition)) { CreateFileMenu(new Rect(screenRect.x, screenRect.yMax, 0.0f, 0.0f)); } if(Event.current.type == EventType.KeyDown) { if(Event.current.keyCode == KeyCode.Q && (Event.current.control || Event.current.command)) { Close(); Event.current.Use(); } } } private void DisplayEditMenu(Rect screenRect) { EditorGUI.LabelField(screenRect, "Edit", EditorStyles.toolbarDropDown); if(Event.current.type == EventType.MouseDown && Event.current.button == 0 && screenRect.Contains(Event.current.mousePosition)) { CreateEditMenu(new Rect(screenRect.x, screenRect.yMax, 0.0f, 0.0f)); } if(Event.current.type == EventType.KeyDown) { if(Event.current.keyCode == KeyCode.D && Event.current.shift) { Duplicate(); Event.current.Use(); } if(Event.current.keyCode == KeyCode.Delete) { Delete(); Event.current.Use(); } } } private void UpdateHierarchyPanelWidth() { float cursorRectWidth = _isResizingHierarchy ? _maxCursorRectWidth : _minCursorRectWidth; Rect cursorRect = new Rect(_hierarchyPanelWidth - cursorRectWidth / 2, _toolbarHeight, cursorRectWidth, position.height - _toolbarHeight); Rect resizeRect = new Rect(_hierarchyPanelWidth - _minCursorRectWidth / 2, 0.0f, _minCursorRectWidth, position.height); EditorGUIUtility.AddCursorRect(cursorRect, MouseCursor.ResizeHorizontal); switch(Event.current.type) { case EventType.MouseDown: if(Event.current.button == 0 && resizeRect.Contains(Event.current.mousePosition)) { _isResizingHierarchy = true; Event.current.Use(); } break; case EventType.MouseUp: if(Event.current.button == 0 && _isResizingHierarchy) { _isResizingHierarchy = false; Event.current.Use(); } break; case EventType.MouseDrag: if(_isResizingHierarchy) { _hierarchyPanelWidth = Mathf.Clamp(_hierarchyPanelWidth + Event.current.delta.x, _minHierarchyPanelWidth, position.width / 2); Event.current.Use(); Repaint(); } break; default: break; } } private void DisplaySearchResults() { Rect screenRect = new Rect(0.0f, _toolbarHeight - 5.0f, _hierarchyPanelWidth, position.height - _toolbarHeight + 10.0f); GUI.Box(screenRect, ""); if(_searchResults.Count > 0) { Rect scrollView = new Rect(screenRect.x, screenRect.y + 5.0f, screenRect.width, position.height - screenRect.y); GUILayout.BeginArea(scrollView); _hierarchyScrollPos = EditorGUILayout.BeginScrollView(_hierarchyScrollPos); GUILayout.Space(5.0f); for(int i = 0; i < _searchResults.Count; i++) { DisplaySearchResult(screenRect, _searchResults[i]); } GUILayout.Space(5.0f); EditorGUILayout.EndScrollView(); GUILayout.EndArea(); } } private void DisplaySearchResult(Rect screenRect, SearchResult result) { DisplayHierarchyInputConfigItem(screenRect, result.configuration, _inputManager.inputConfigurations[result.configuration].name); if(_inputManager.inputConfigurations[result.configuration].isExpanded) { for(int i = 0; i < result.axes.Count; i++) { DisplayHierarchiAxisConfigItem(screenRect, result.configuration, result.axes[i], _inputManager.inputConfigurations[result.configuration].axes[result.axes[i]].name); } } } private void DisplayHierarchyPanel() { Rect screenRect = new Rect(0.0f, _toolbarHeight - 5.0f, _hierarchyPanelWidth, position.height - _toolbarHeight + 10.0f); Rect scrollView = new Rect(screenRect.x, screenRect.y + 5.0f, screenRect.width, position.height - screenRect.y); GUI.Box(screenRect, ""); GUILayout.BeginArea(scrollView); _hierarchyScrollPos = EditorGUILayout.BeginScrollView(_hierarchyScrollPos); GUILayout.Space(5.0f); for(int i = 0; i < _inputManager.inputConfigurations.Count; i++) { DisplayHierarchyInputConfigItem(screenRect, i, _inputManager.inputConfigurations[i].name); if(_inputManager.inputConfigurations[i].isExpanded) { for(int j = 0; j < _inputManager.inputConfigurations[i].axes.Count; j++) { DisplayHierarchiAxisConfigItem(screenRect, i, j, _inputManager.inputConfigurations[i].axes[j].name); } } } GUILayout.Space(5.0f); EditorGUILayout.EndScrollView(); GUILayout.EndArea(); } private void DisplayHierarchyInputConfigItem(Rect screenRect, int index, string name) { Rect configPos = GUILayoutUtility.GetRect(new GUIContent(name), EditorStyles.foldout, GUILayout.Height(_hierarchyItemHeight)); if(Event.current.type == EventType.MouseDown && Event.current.button == 0) { if(configPos.Contains(Event.current.mousePosition)) { _selectionPath.Clear(); _selectionPath.Add(index); GUI.FocusControl(null); Repaint(); } else if(screenRect.Contains(Event.current.mousePosition)) { _selectionPath.Clear(); GUI.FocusControl(null); Repaint(); } } if(_selectionPath.Count == 1 && _selectionPath[0] == index) { if(_highlightTexture == null) { CreateHighlightTexture(); } GUI.DrawTexture(configPos, _highlightTexture, ScaleMode.StretchToFill); _inputManager.inputConfigurations[index].isExpanded = EditorGUI.Foldout(configPos, _inputManager.inputConfigurations[index].isExpanded, name, _whiteFoldout); } else { _inputManager.inputConfigurations[index].isExpanded = EditorGUI.Foldout(configPos, _inputManager.inputConfigurations[index].isExpanded, name); } } private void DisplayHierarchiAxisConfigItem(Rect screenRect, int inputConfigIndex, int index, string name) { Rect configPos = GUILayoutUtility.GetRect(new GUIContent(name), EditorStyles.label, GUILayout.Height(_hierarchyItemHeight)); if(Event.current.type == EventType.MouseDown && Event.current.button == 0) { if(configPos.Contains(Event.current.mousePosition)) { _editingPositiveKey = false; _editingPositiveKey = false; _editingAltPositiveKey = false; _editingAltNegativeKey = false; _keyString = string.Empty; _selectionPath.Clear(); _selectionPath.Add(inputConfigIndex); _selectionPath.Add(index); GUI.FocusControl(null); Event.current.Use(); Repaint(); } else if(screenRect.Contains(Event.current.mousePosition)) { _selectionPath.Clear(); GUI.FocusControl(null); Repaint(); } } if(_selectionPath.Count == 2 && _selectionPath[0] == inputConfigIndex && _selectionPath[1] == index) { if(_highlightTexture == null) { CreateHighlightTexture(); } GUI.DrawTexture(configPos, _highlightTexture, ScaleMode.StretchToFill); configPos.x += 20.0f; EditorGUI.LabelField(configPos, name, _whiteLabel); } else { configPos.x += 20.0f; EditorGUI.LabelField(configPos, name); } } private void DisplayMainPanel() { Rect screenRect = new Rect(_hierarchyPanelWidth + 5.0f, _toolbarHeight + 5, position.width - (_hierarchyPanelWidth + 5.0f), position.height - _toolbarHeight - 5.0f); InputConfiguration inputConfig = _inputManager.inputConfigurations[_selectionPath[0]]; if(_selectionPath.Count < 2) { DisplayInputConfigurationFields(inputConfig, screenRect); } else { AxisConfiguration axisConfig = inputConfig.axes[_selectionPath[1]]; DisplayAxisConfigurationFields(inputConfig, axisConfig, screenRect); } } private void DisplayInputConfigurationFields(InputConfiguration inputConfig, Rect screenRect) { GUILayout.BeginArea(screenRect); _mainPanelScrollPos = EditorGUILayout.BeginScrollView(_mainPanelScrollPos); inputConfig.name = EditorGUILayout.TextField("Name", inputConfig.name); EditorGUILayout.Space(); GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerOneDefault != inputConfig.name); if(GUILayout.Button("Make Player One Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f))) { _inputManager.playerOneDefault = inputConfig.name; } GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerTwoDefault != inputConfig.name); if (GUILayout.Button("Make Player Two Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f))) { _inputManager.playerTwoDefault = inputConfig.name; } GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerThreeDefault != inputConfig.name); if (GUILayout.Button("Make Player Three Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f))) { _inputManager.playerThreeDefault = inputConfig.name; } GUI.enabled = (!EditorApplication.isPlaying && _inputManager.playerFourDefault != inputConfig.name); if (GUILayout.Button("Make Player Four Default", GUILayout.Width(200.0f), GUILayout.Height(25.0f))) { _inputManager.playerFourDefault = inputConfig.name; } //GUI.enabled = (EditorApplication.isPlaying && _InputManager.PlayerOneConfiguration.name != inputConfig.name); //if(GUILayout.Button("Switch To", GUILayout.Width(135.0f), GUILayout.Height(20.0f))) //{ // _InputManager.SetInputConfiguration(inputConfig.name, PlayerID.One); //} GUI.enabled = true; EditorGUILayout.EndScrollView(); GUILayout.EndArea(); } private void DisplayAxisConfigurationFields(InputConfiguration inputConfigx, AxisConfiguration axisConfig, Rect screenRect) { GUIContent gravityInfo = new GUIContent("Gravity", "The speed(in units/sec) at which a digital axis falls towards neutral."); GUIContent sensitivityInfo = new GUIContent("Sensitivity", "The speed(in units/sec) at which an axis moves towards the target value."); GUIContent snapInfo = new GUIContent("Snap", "If input switches direction, do we snap to neutral and continue from there? For digital axes only."); GUIContent deadZoneInfo = new GUIContent("Dead Zone", "Size of analog dead zone. Values within this range map to neutral."); GUILayout.BeginArea(screenRect); _mainPanelScrollPos = GUILayout.BeginScrollView(_mainPanelScrollPos); axisConfig.name = EditorGUILayout.TextField("Name", axisConfig.name); axisConfig.description = EditorGUILayout.TextField("Description", axisConfig.description); // Positive Key EditorToolbox.KeyCodeField(ref _keyString, ref _editingPositiveKey, "Positive", "editor_positive_key", axisConfig.positive); ProcessKeyString(ref axisConfig.positive, ref _editingPositiveKey); // Negative Key EditorToolbox.KeyCodeField(ref _keyString, ref _editingNegativeKey, "Negative", "editor_negative_key", axisConfig.negative); ProcessKeyString(ref axisConfig.negative, ref _editingNegativeKey); // Alt Positive Key EditorToolbox.KeyCodeField(ref _keyString, ref _editingAltPositiveKey, "Alt Positive", "editor_alt_positive_key", axisConfig.altPositive); ProcessKeyString(ref axisConfig.altPositive, ref _editingAltPositiveKey); // Alt Negative key EditorToolbox.KeyCodeField(ref _keyString, ref _editingAltNegativeKey, "Alt Negative", "editor_alt_negative_key", axisConfig.altNegative); ProcessKeyString(ref axisConfig.altNegative, ref _editingAltNegativeKey); axisConfig.gravity = EditorGUILayout.FloatField(gravityInfo, axisConfig.gravity); axisConfig.deadZone = EditorGUILayout.FloatField(deadZoneInfo, axisConfig.deadZone); axisConfig.sensitivity = EditorGUILayout.FloatField(sensitivityInfo, axisConfig.sensitivity); axisConfig.snap = EditorGUILayout.Toggle(snapInfo, axisConfig.snap); axisConfig.invert = EditorGUILayout.Toggle("Invert", axisConfig.invert); axisConfig.type = (InputType)EditorGUILayout.EnumPopup("Type", axisConfig.type); axisConfig.axis = EditorGUILayout.Popup("Axis", axisConfig.axis, _axisOptions); axisConfig.joystick = EditorGUILayout.Popup("Joystick", axisConfig.joystick, _joystickOptions); if(EditorApplication.isPlaying) { EditorGUILayout.Space(); GUI.enabled = false; EditorGUILayout.FloatField("Raw Axis", axisConfig.GetAxisRaw()); EditorGUILayout.FloatField("Axis", axisConfig.GetAxis()); EditorGUILayout.Toggle("Button", axisConfig.GetButton()); GUI.enabled = true; } GUILayout.EndScrollView(); GUILayout.EndArea(); } private void ProcessKeyString(ref KeyCode key, ref bool isEditing) { if(isEditing && Event.current.type == EventType.KeyUp) { key = AxisConfiguration.StringToKey(_keyString); if(key == KeyCode.None) { _keyString = string.Empty; } else { _keyString = key.ToString(); } isEditing = false; } } #endregion #region [Static Interface] public static bool IsOpen { get; private set; } [MenuItem("Team Utility/Input Manager/Open Input Editor", false, 0)] public static void OpenWindow() { if (!IsOpen) { if (UnityEngine.Object.FindObjectOfType(typeof(_InputManager)) == null) { bool create = EditorUtility.DisplayDialog("Warning", "There is no InputManager instance in the scene. Do you want to create one?", "Yes", "No"); if (create) { GameObject gameObject = new GameObject("InputManager"); gameObject.AddComponent<_InputManager>(); } else { return; } } EditorWindow.GetWindow<AdvancedInputEditor>("Input Editor"); } } public static void OpenWindow(_InputManager target) { if(!IsOpen) { var window = EditorWindow.GetWindow<AdvancedInputEditor>("Input Editor"); window._inputManager = target; } } public static void CloseWindow() { if(IsOpen) { var window = EditorWindow.GetWindow<AdvancedInputEditor>("Input Editor"); window.Close(); } } #endregion } }
// // Encog(tm) Core v3.3 - .Net Version // http://www.heatonresearch.com/encog/ // // Copyright 2008-2014 Heaton Research, 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. // // For more information on Heaton Research copyrights, licenses // and trademarks visit: // http://www.heatonresearch.com/copyright // using Encog.MathUtil; using Encog.ML.Data; using Encog.ML.Data.Basic; using Encog.Util; using System; namespace Encog.ML.HMM.Distributions { /// <summary> /// A discrete distribution is a distribution with a finite set of states that it /// can be in. /// </summary> [Serializable] public class DiscreteDistribution : IStateDistribution { /// <summary> /// The probabilities of moving between states. /// </summary> private readonly double[][] _probabilities; /// <summary> /// Construct a discrete distribution with the specified probabilities. /// </summary> /// <param name="theProbabilities">The probabilities.</param> public DiscreteDistribution(double[][] theProbabilities) { if (theProbabilities.Length == 0) { throw new EncogError("Invalid empty array"); } _probabilities = new double[theProbabilities.Length][]; for (int i = 0; i < theProbabilities.Length; i++) { if (theProbabilities[i].Length == 0) { throw new EncogError("Invalid empty array"); } _probabilities[i] = new double[theProbabilities[i].Length]; for (int j = 0; j < _probabilities[i].Length; j++) { if ((_probabilities[i][j] = theProbabilities[i][j]) < 0.0) { throw new EncogError("Invalid probability."); } } } } /// <summary> /// Construct a discrete distribution. /// </summary> /// <param name="cx">The count of each.</param> public DiscreteDistribution(int[] cx) { _probabilities = new double[cx.Length][]; for (int i = 0; i < cx.Length; i++) { int c = cx[i]; _probabilities[i] = new double[c]; for (int j = 0; j < c; j++) { _probabilities[i][j] = 1.0/c; } } } /// <summary> /// The state probabilities. /// </summary> public double[][] Probabilities { get { return _probabilities; } } #region IStateDistribution Members /// <summary> /// Fit this distribution to the specified data. /// </summary> /// <param name="co">THe data to fit to.</param> public void Fit(IMLDataSet co) { if (co.Count < 1) { throw new EncogError("Empty observation set"); } for (int i = 0; i < _probabilities.Length; i++) { for (int j = 0; j < _probabilities[i].Length; j++) { _probabilities[i][j] = 0.0; } foreach (IMLDataPair o in co) { _probabilities[i][(int) o.Input[i]]++; } for (int j = 0; j < _probabilities[i].Length; j++) { _probabilities[i][j] /= co.Count; } } } /// <summary> /// Fit this distribution to the specified data, with weights. /// </summary> /// <param name="co">The data to fit to.</param> /// <param name="weights">The weights.</param> public void Fit(IMLDataSet co, double[] weights) { if ((co.Count < 1) || (co.Count != weights.Length)) { throw new EncogError("Invalid weight size."); } for (int i = 0; i < _probabilities.Length; i++) { EngineArray.Fill(_probabilities[i], 0.0); int j = 0; foreach (IMLDataPair o in co) { _probabilities[i][(int) o.Input[i]] += weights[j++]; } } } /// <summary> /// Generate a random sequence. /// </summary> /// <returns>The random element.</returns> public IMLDataPair Generate() { var result = new BasicMLData(_probabilities.Length); for (int i = 0; i < _probabilities.Length; i++) { double rand = ThreadSafeRandom.NextDouble(); result[i] = _probabilities[i].Length - 1; for (int j = 0; j < (_probabilities[i].Length - 1); j++) { if ((rand -= _probabilities[i][j]) < 0.0) { result[i] = j; break; } } } return new BasicMLDataPair(result); } /// <summary> /// Determine the probability of the specified data pair. /// </summary> /// <param name="o">THe data pair.</param> /// <returns>The probability.</returns> public double Probability(IMLDataPair o) { double result = 1; for (int i = 0; i < _probabilities.Length; i++) { if (o.Input[i] > (_probabilities[i].Length - 1)) { throw new EncogError("Wrong observation value"); } result *= _probabilities[i][(int) o.Input[i]]; } return result; } /// <summary> /// Clone. /// </summary> /// <returns>A clone of the distribution.</returns> IStateDistribution IStateDistribution.Clone() { return new DiscreteDistribution((double[][])_probabilities.Clone()); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. namespace Microsoft.Azure.Management.Dns { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; public partial class DnsManagementClient : ServiceClient<DnsManagementClient>, IDnsManagementClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public 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> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// Gets subscription credentials which uniquely identify Microsoft Azure /// subscription. The subscription ID forms part of the URI for every service /// call. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// Client Api Version. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IRecordSetsOperations. /// </summary> public virtual IRecordSetsOperations RecordSets { get; private set; } /// <summary> /// Gets the IZonesOperations. /// </summary> public virtual IZonesOperations Zones { get; private set; } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected DnsManagementClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the DnsManagementClient 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> protected DnsManagementClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the DnsManagementClient 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> protected DnsManagementClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DnsManagementClient 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> protected DnsManagementClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public DnsManagementClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </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> public DnsManagementClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public DnsManagementClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the DnsManagementClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </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> public DnsManagementClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.RecordSets = new RecordSetsOperations(this); this.Zones = new ZonesOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-04-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; SerializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new TransformationJsonConverter()); DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// FileSystemScanner.cs // // Copyright 2005 John Reilly // // 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. // // Linking this library statically or dynamically with other modules is // making a combined work based on this library. Thus, the terms and // conditions of the GNU General Public License cover the whole // combination. // // As a special exception, the copyright holders of this library give you // permission to link this library with independent modules to produce an // executable, regardless of the license terms of these independent // modules, and to copy and distribute the resulting executable under // terms of your choice, provided that you also meet, for each linked // independent module, the terms and conditions of the license of that // module. An independent module is a module which is not derived from // or based on this library. If you modify this library, you may extend // this exception to your version of the library, but you are not // obligated to do so. If you do not wish to do so, delete this // exception statement from your version. using System; namespace GitHub.ICSharpCode.SharpZipLib.Core { #region EventArgs /// <summary> /// Event arguments for scanning. /// </summary> public class ScanEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name.</param> public ScanEventArgs(string name) { name_ = name; } #endregion /// <summary> /// The file or directory name for this event. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating if scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments during processing of a single file or directory. /// </summary> public class ProgressEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanEventArgs"/> /// </summary> /// <param name="name">The file or directory name if known.</param> /// <param name="processed">The number of bytes processed so far</param> /// <param name="target">The total number of bytes to process, 0 if not known</param> public ProgressEventArgs(string name, long processed, long target) { name_ = name; processed_ = processed; target_ = target; } #endregion /// <summary> /// The name for this event if known. /// </summary> public string Name { get { return name_; } } /// <summary> /// Get set a value indicating wether scanning should continue or not. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } /// <summary> /// Get a percentage representing how much of the <see cref="Target"></see> has been processed /// </summary> /// <value>0.0 to 100.0 percent; 0 if target is not known.</value> public float PercentComplete { get { float result; if (target_ <= 0) { result = 0; } else { result = ((float)processed_ / (float)target_) * 100.0f; } return result; } } /// <summary> /// The number of bytes processed so far /// </summary> public long Processed { get { return processed_; } } /// <summary> /// The number of bytes to process. /// </summary> /// <remarks>Target may be 0 or negative if the value isnt known.</remarks> public long Target { get { return target_; } } #region Instance Fields string name_; long processed_; long target_; bool continueRunning_ = true; #endregion } /// <summary> /// Event arguments for directories. /// </summary> public class DirectoryEventArgs : ScanEventArgs { #region Constructors /// <summary> /// Initialize an instance of <see cref="DirectoryEventArgs"></see>. /// </summary> /// <param name="name">The name for this directory.</param> /// <param name="hasMatchingFiles">Flag value indicating if any matching files are contained in this directory.</param> public DirectoryEventArgs(string name, bool hasMatchingFiles) : base (name) { hasMatchingFiles_ = hasMatchingFiles; } #endregion /// <summary> /// Get a value indicating if the directory contains any matching files or not. /// </summary> public bool HasMatchingFiles { get { return hasMatchingFiles_; } } #region Instance Fields bool hasMatchingFiles_; #endregion } /// <summary> /// Arguments passed when scan failures are detected. /// </summary> public class ScanFailureEventArgs : EventArgs { #region Constructors /// <summary> /// Initialise a new instance of <see cref="ScanFailureEventArgs"></see> /// </summary> /// <param name="name">The name to apply.</param> /// <param name="e">The exception to use.</param> public ScanFailureEventArgs(string name, Exception e) { name_ = name; exception_ = e; continueRunning_ = true; } #endregion /// <summary> /// The applicable name. /// </summary> public string Name { get { return name_; } } /// <summary> /// The applicable exception. /// </summary> public Exception Exception { get { return exception_; } } /// <summary> /// Get / set a value indicating wether scanning should continue. /// </summary> public bool ContinueRunning { get { return continueRunning_; } set { continueRunning_ = value; } } #region Instance Fields string name_; Exception exception_; bool continueRunning_; #endregion } #endregion #region Delegates /// <summary> /// Delegate invoked before starting to process a directory. /// </summary> public delegate void ProcessDirectoryHandler(object sender, DirectoryEventArgs e); /// <summary> /// Delegate invoked before starting to process a file. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProcessFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked during processing of a file or directory /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void ProgressHandler(object sender, ProgressEventArgs e); /// <summary> /// Delegate invoked when a file has been completely processed. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void CompletedFileHandler(object sender, ScanEventArgs e); /// <summary> /// Delegate invoked when a directory failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void DirectoryFailureHandler(object sender, ScanFailureEventArgs e); /// <summary> /// Delegate invoked when a file failure is detected. /// </summary> /// <param name="sender">The source of the event</param> /// <param name="e">The event arguments.</param> public delegate void FileFailureHandler(object sender, ScanFailureEventArgs e); #endregion /// <summary> /// FileSystemScanner provides facilities scanning of files and directories. /// </summary> public class FileSystemScanner { #region Constructors /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="filter">The <see cref="PathFilter">file filter</see> to apply when scanning.</param> public FileSystemScanner(string filter) { fileFilter_ = new PathFilter(filter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The <see cref="PathFilter">file filter</see> to apply.</param> /// <param name="directoryFilter">The <see cref="PathFilter"> directory filter</see> to apply.</param> public FileSystemScanner(string fileFilter, string directoryFilter) { fileFilter_ = new PathFilter(fileFilter); directoryFilter_ = new PathFilter(directoryFilter); } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter) { fileFilter_ = fileFilter; } /// <summary> /// Initialise a new instance of <see cref="FileSystemScanner"></see> /// </summary> /// <param name="fileFilter">The file <see cref="IScanFilter">filter</see> to apply.</param> /// <param name="directoryFilter">The directory <see cref="IScanFilter">filter</see> to apply.</param> public FileSystemScanner(IScanFilter fileFilter, IScanFilter directoryFilter) { fileFilter_ = fileFilter; directoryFilter_ = directoryFilter; } #endregion #region Delegates /// <summary> /// Delegate to invoke when a directory is processed. /// </summary> public ProcessDirectoryHandler ProcessDirectory; /// <summary> /// Delegate to invoke when a file is processed. /// </summary> public ProcessFileHandler ProcessFile; /// <summary> /// Delegate to invoke when processing for a file has finished. /// </summary> public CompletedFileHandler CompletedFile; /// <summary> /// Delegate to invoke when a directory failure is detected. /// </summary> public DirectoryFailureHandler DirectoryFailure; /// <summary> /// Delegate to invoke when a file failure is detected. /// </summary> public FileFailureHandler FileFailure; #endregion /// <summary> /// Raise the DirectoryFailure event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="e">The exception detected.</param> bool OnDirectoryFailure(string directory, Exception e) { DirectoryFailureHandler handler = DirectoryFailure; bool result = (handler != null); if ( result ) { ScanFailureEventArgs args = new ScanFailureEventArgs(directory, e); handler(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the FileFailure event. /// </summary> /// <param name="file">The file name.</param> /// <param name="e">The exception detected.</param> bool OnFileFailure(string file, Exception e) { FileFailureHandler handler = FileFailure; bool result = (handler != null); if ( result ){ ScanFailureEventArgs args = new ScanFailureEventArgs(file, e); FileFailure(this, args); alive_ = args.ContinueRunning; } return result; } /// <summary> /// Raise the ProcessFile event. /// </summary> /// <param name="file">The file name.</param> void OnProcessFile(string file) { ProcessFileHandler handler = ProcessFile; if ( handler!= null ) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the complete file event /// </summary> /// <param name="file">The file name</param> void OnCompleteFile(string file) { CompletedFileHandler handler = CompletedFile; if (handler != null) { ScanEventArgs args = new ScanEventArgs(file); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Raise the ProcessDirectory event. /// </summary> /// <param name="directory">The directory name.</param> /// <param name="hasMatchingFiles">Flag indicating if the directory has matching files.</param> void OnProcessDirectory(string directory, bool hasMatchingFiles) { ProcessDirectoryHandler handler = ProcessDirectory; if ( handler != null ) { DirectoryEventArgs args = new DirectoryEventArgs(directory, hasMatchingFiles); handler(this, args); alive_ = args.ContinueRunning; } } /// <summary> /// Scan a directory. /// </summary> /// <param name="directory">The base directory to scan.</param> /// <param name="recurse">True to recurse subdirectories, false to scan a single directory.</param> public void Scan(string directory, bool recurse) { alive_ = true; ScanDir(directory, recurse); } void ScanDir(string directory, bool recurse) { try { string[] names = System.IO.Directory.GetFiles(directory); bool hasMatch = false; for (int fileIndex = 0; fileIndex < names.Length; ++fileIndex) { if ( !fileFilter_.IsMatch(names[fileIndex]) ) { names[fileIndex] = null; } else { hasMatch = true; } } OnProcessDirectory(directory, hasMatch); if ( alive_ && hasMatch ) { foreach (string fileName in names) { try { if ( fileName != null ) { OnProcessFile(fileName); if ( !alive_ ) { break; } } } catch (Exception e) { if (!OnFileFailure(fileName, e)) { throw; } } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } if ( alive_ && recurse ) { try { string[] names = System.IO.Directory.GetDirectories(directory); foreach (string fulldir in names) { if ((directoryFilter_ == null) || (directoryFilter_.IsMatch(fulldir))) { ScanDir(fulldir, true); if ( !alive_ ) { break; } } } } catch (Exception e) { if (!OnDirectoryFailure(directory, e)) { throw; } } } } #region Instance Fields /// <summary> /// The file filter currently in use. /// </summary> IScanFilter fileFilter_; /// <summary> /// The directory filter currently in use. /// </summary> IScanFilter directoryFilter_; /// <summary> /// Flag indicating if scanning should continue running. /// </summary> bool alive_; #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Xunit; namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012; using System; using System.Collections; using System.IO; using System.Globalization; using System.Reflection; using System.Resources; using Microsoft.CSharp.RuntimeBinder; public enum ErrorElementId { None, SK_METHOD, // method SK_CLASS, // type SK_NAMESPACE, // namespace SK_FIELD, // field SK_PROPERTY, // property SK_UNKNOWN, // element SK_VARIABLE, // variable SK_EVENT, // event SK_TYVAR, // type parameter SK_ALIAS, // using alias ERRORSYM, // <error> NULL, // <null> GlobalNamespace, // <global namespace> MethodGroup, // method group AnonMethod, // anonymous method Lambda, // lambda expression AnonymousType, // anonymous type } public enum ErrorMessageId { None, BadBinaryOps, // Operator '{0}' cannot be applied to operands of type '{1}' and '{2}' IntDivByZero, // Division by constant zero BadIndexLHS, // Cannot apply indexing with [] to an expression of type '{0}' BadIndexCount, // Wrong number of indices inside []; expected '{0}' BadUnaryOp, // Operator '{0}' cannot be applied to operand of type '{1}' NoImplicitConv, // Cannot implicitly convert type '{0}' to '{1}' NoExplicitConv, // Cannot convert type '{0}' to '{1}' ConstOutOfRange, // Constant value '{0}' cannot be converted to a '{1}' AmbigBinaryOps, // Operator '{0}' is ambiguous on operands of type '{1}' and '{2}' AmbigUnaryOp, // Operator '{0}' is ambiguous on an operand of type '{1}' ValueCantBeNull, // Cannot convert null to '{0}' because it is a non-nullable value type WrongNestedThis, // Cannot access a non-static member of outer type '{0}' via nested type '{1}' NoSuchMember, // '{0}' does not contain a definition for '{1}' ObjectRequired, // An object reference is required for the non-static field, method, or property '{0}' AmbigCall, // The call is ambiguous between the following methods or properties: '{0}' and '{1}' BadAccess, // '{0}' is inaccessible due to its protection level MethDelegateMismatch, // No overload for '{0}' matches delegate '{1}' AssgLvalueExpected, // The left-hand side of an assignment must be a variable, property or indexer NoConstructors, // The type '{0}' has no constructors defined BadDelegateConstructor, // The delegate '{0}' does not have a valid constructor PropertyLacksGet, // The property or indexer '{0}' cannot be used in this context because it lacks the get accessor ObjectProhibited, // Member '{0}' cannot be accessed with an instance reference; qualify it with a type name instead AssgReadonly, // A readonly field cannot be assigned to (except in a constructor or a variable initializer) RefReadonly, // A readonly field cannot be passed ref or out (except in a constructor) AssgReadonlyStatic, // A static readonly field cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic, // A static readonly field cannot be passed ref or out (except in a static constructor) AssgReadonlyProp, // Property or indexer '{0}' cannot be assigned to -- it is read only AbstractBaseCall, // Cannot call an abstract base member: '{0}' RefProperty, // A property or indexer may not be passed as an out or ref parameter ManagedAddr, // Cannot take the address of, get the size of, or declare a pointer to a managed type ('{0}') FixedNotNeeded, // You cannot use the fixed statement to take the address of an already fixed expression UnsafeNeeded, // Dynamic calls cannot be used in conjunction with pointers BadBoolOp, // In order to be applicable as a short circuit operator a user-defined logical operator ('{0}') must have the same return type as the type of its 2 parameters MustHaveOpTF, // The type ('{0}') must contain declarations of operator true and operator false CheckedOverflow, // The operation overflows at compile time in checked mode ConstOutOfRangeChecked, // Constant value '{0}' cannot be converted to a '{1}' (use 'unchecked' syntax to override) AmbigMember, // Ambiguity between '{0}' and '{1}' SizeofUnsafe, // '{0}' does not have a predefined size, therefore sizeof can only be used in an unsafe context (consider using System.Runtime.InteropServices.Marshal.SizeOf) FieldInitRefNonstatic, // A field initializer cannot reference the non-static field, method, or property '{0}' CallingFinalizeDepracated, // Destructors and object.Finalize cannot be called directly. Consider calling IDisposable.Dispose if available. CallingBaseFinalizeDeprecated, // Do not directly call your base class Finalize method. It is called automatically from your destructor. BadCastInFixed, // The right hand side of a fixed statement assignment may not be a cast expression NoImplicitConvCast, // Cannot implicitly convert type '{0}' to '{1}'. An explicit conversion exists (are you missing a cast?) InaccessibleGetter, // The property or indexer '{0}' cannot be used in this context because the get accessor is inaccessible InaccessibleSetter, // The property or indexer '{0}' cannot be used in this context because the set accessor is inaccessible BadArity, // Using the generic {1} '{0}' requires '{2}' type arguments BadTypeArgument, // The type '{0}' may not be used as a type argument TypeArgsNotAllowed, // The {1} '{0}' cannot be used with type arguments HasNoTypeVars, // The non-generic {1} '{0}' cannot be used with type arguments NewConstraintNotSatisfied, // '{2}' must be a non-abstract type with a public parameterless constructor in order to use it as parameter '{1}' in the generic type or method '{0}' GenericConstraintNotSatisfiedRefType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no implicit reference conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedNullableEnum, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. GenericConstraintNotSatisfiedNullableInterface, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. The nullable type '{3}' does not satisfy the constraint of '{1}'. Nullable types can not satisfy any interface constraints. GenericConstraintNotSatisfiedTyVar, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion or type parameter conversion from '{3}' to '{1}'. GenericConstraintNotSatisfiedValType, // The type '{3}' cannot be used as type parameter '{2}' in the generic type or method '{0}'. There is no boxing conversion from '{3}' to '{1}'. TypeVarCantBeNull, // Cannot convert null to type parameter '{0}' because it could be a non-nullable value type. Consider using 'default({0})' instead. BadRetType, // '{1} {0}' has the wrong return type CantInferMethTypeArgs, // The type arguments for method '{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly. MethGrpToNonDel, // Cannot convert method group '{0}' to non-delegate type '{1}'. Did you intend to invoke the method? RefConstraintNotSatisfied, // The type '{2}' must be a reference type in order to use it as parameter '{1}' in the generic type or method '{0}' ValConstraintNotSatisfied, // The type '{2}' must be a non-nullable value type in order to use it as parameter '{1}' in the generic type or method '{0}' CircularConstraint, // Circular constraint dependency involving '{0}' and '{1}' BaseConstraintConflict, // Type parameter '{0}' inherits conflicting constraints '{1}' and '{2}' ConWithValCon, // Type parameter '{1}' has the 'struct' constraint so '{1}' cannot be used as a constraint for '{0}' AmbigUDConv, // Ambiguous user defined conversions '{0}' and '{1}' when converting from '{2}' to '{3}' PredefinedTypeNotFound, // Predefined type '{0}' is not defined or imported PredefinedTypeBadType, // Predefined type '{0}' is declared incorrectly BindToBogus, // '{0}' is not supported by the language CantCallSpecialMethod, // '{0}': cannot explicitly call operator or accessor BogusType, // '{0}' is a type not supported by the language MissingPredefinedMember, // Missing compiler required member '{0}.{1}' LiteralDoubleCast, // Literal of type double cannot be implicitly converted to type '{1}'; use an '{0}' suffix to create a literal of this type UnifyingInterfaceInstantiations, // '{0}' cannot implement both '{1}' and '{2}' because they may unify for some type parameter substitutions ConvertToStaticClass, // Cannot convert to static type '{0}' GenericArgIsStaticClass, // '{0}': static types cannot be used as type arguments PartialMethodToDelegate, // Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration IncrementLvalueExpected, // The operand of an increment or decrement operator must be a variable, property or indexer NoSuchMemberOrExtension, // '{0}' does not contain a definition for '{1}' and no extension method '{1}' accepting a first argument of type '{0}' could be found (are you missing a using directive or an assembly reference?) ValueTypeExtDelegate, // Extension methods '{0}' defined on value type '{1}' cannot be used to create delegates BadArgCount, // No overload for method '{0}' takes '{1}' arguments BadArgTypes, // The best overloaded method match for '{0}' has some invalid arguments BadArgType, // Argument '{0}': cannot convert from '{1}' to '{2}' RefLvalueExpected, // A ref or out argument must be an assignable variable BadProtectedAccess, // Cannot access protected member '{0}' via a qualifier of type '{1}'; the qualifier must be of type '{2}' (or derived from it) BindToBogusProp2, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor methods '{1}' or '{2}' BindToBogusProp1, // Property, indexer, or event '{0}' is not supported by the language; try directly calling accessor method '{1}' BadDelArgCount, // Delegate '{0}' does not take '{1}' arguments BadDelArgTypes, // Delegate '{0}' has some invalid arguments AssgReadonlyLocal, // Cannot assign to '{0}' because it is read-only RefReadonlyLocal, // Cannot pass '{0}' as a ref or out argument because it is read-only ReturnNotLValue, // Cannot modify the return value of '{0}' because it is not a variable BadArgExtraRef, // Argument '{0}' should not be passed with the '{1}' keyword // DelegateOnConditional, // Cannot create delegate with '{0}' because it has a Conditional attribute (REMOVED) BadArgRef, // Argument '{0}' must be passed with the '{1}' keyword AssgReadonly2, // Members of readonly field '{0}' cannot be modified (except in a constructor or a variable initializer) RefReadonly2, // Members of readonly field '{0}' cannot be passed ref or out (except in a constructor) AssgReadonlyStatic2, // Fields of static readonly field '{0}' cannot be assigned to (except in a static constructor or a variable initializer) RefReadonlyStatic2, // Fields of static readonly field '{0}' cannot be passed ref or out (except in a static constructor) AssgReadonlyLocalCause, // Cannot assign to '{0}' because it is a '{1}' RefReadonlyLocalCause, // Cannot pass '{0}' as a ref or out argument because it is a '{1}' ThisStructNotInAnonMeth, // Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. DelegateOnNullable, // Cannot bind delegate to '{0}' because it is a member of 'System.Nullable<T>' BadCtorArgCount, // '{0}' does not contain a constructor that takes '{1}' arguments BadExtensionArgTypes, // '{0}' does not contain a definition for '{1}' and the best extension method overload '{2}' has some invalid arguments BadInstanceArgType, // Instance argument: cannot convert from '{0}' to '{1}' BadArgTypesForCollectionAdd, // The best overloaded Add method '{0}' for the collection initializer has some invalid arguments InitializerAddHasParamModifiers, // The best overloaded method match '{0}' for the collection initializer element cannot be used. Collection initializer 'Add' methods cannot have ref or out parameters. NonInvocableMemberCalled, // Non-invocable member '{0}' cannot be used like a method. NamedArgumentSpecificationBeforeFixedArgument, // Named argument specifications must appear after all fixed arguments have been specified BadNamedArgument, // The best overload for '{0}' does not have a parameter named '{1}' BadNamedArgumentForDelegateInvoke, // The delegate '{0}' does not have a parameter named '{1}' DuplicateNamedArgument, // Named argument '{0}' cannot be specified multiple times NamedArgumentUsedInPositional, // Named argument '{0}' specifies a parameter for which a positional argument has already been given } public enum RuntimeErrorId { None, // RuntimeBinderInternalCompilerException InternalCompilerError, // An unexpected exception occurred while binding a dynamic operation // ArgumentException BindRequireArguments, // Cannot bind call with no calling object // RuntimeBinderException BindCallFailedOverloadResolution, // Overload resolution failed // ArgumentException BindBinaryOperatorRequireTwoArguments, // Binary operators must be invoked with two arguments // ArgumentException BindUnaryOperatorRequireOneArgument, // Unary operators must be invoked with one argument // RuntimeBinderException BindPropertyFailedMethodGroup, // The name '{0}' is bound to a method and cannot be used like a property // RuntimeBinderException BindPropertyFailedEvent, // The event '{0}' can only appear on the left hand side of += or -= // RuntimeBinderException BindInvokeFailedNonDelegate, // Cannot invoke a non-delegate type // ArgumentException BindImplicitConversionRequireOneArgument, // Implicit conversion takes exactly one argument // ArgumentException BindExplicitConversionRequireOneArgument, // Explicit conversion takes exactly one argument // ArgumentException BindBinaryAssignmentRequireTwoArguments, // Binary operators cannot be invoked with one argument // RuntimeBinderException BindBinaryAssignmentFailedNullReference, // Cannot perform member assignment on a null reference // RuntimeBinderException NullReferenceOnMemberException, // Cannot perform runtime binding on a null reference // RuntimeBinderException BindCallToConditionalMethod, // Cannot dynamically invoke method '{0}' because it has a Conditional attribute // RuntimeBinderException BindToVoidMethodButExpectResult, // Cannot implicitly convert type 'void' to 'object' // EE? EmptyDynamicView, // No further information on this object could be discovered // MissingMemberException GetValueonWriteOnlyProperty, // Write Only properties are not supported } } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param012.param012; // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> //<Expects Status=warning>\(23,23\).*CS0649</Expects> public struct myStruct { public int Field; } public class Foo { public int this[params int[] x] { get { return 1; } } } public class Test { public static int Status; [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; try { var rez = f[d]; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> } namespace ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param014.param014 { using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.errorverifier.errorverifier; using ManagedTests.DynamicCSharp.Conformance.dynamic.dynamicType.overloadResolution.indexer.getter.Oneclass.Oneparam.param014.param014; // <Title>Call methods that have different parameter modifiers with dynamic</Title> // <Description> // </Description> // <RelatedBugs></RelatedBugs> //<Expects Status=success></Expects> // <Code> public struct myStruct { public int Field; } public class Foo { public int this[params int[] x] { get { return 1; } } } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { Foo f = new Foo(); dynamic d = "foo"; dynamic d2 = 3; try { var rez = f[d2, d]; } catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) { return 0; } return 1; } } // </Code> }
using System; using System.Diagnostics; using System.IO; using System.Runtime.InteropServices; using System.Threading; namespace SIL.Media.AlsaAudio { /// <summary> /// Simplified wrapper around the standard Linux Alsa audio library. This wrapper defaults /// to recording simple 16-bit PCM mono WAVE files at 22KHz, and plays back using libsndfile /// to read the sound data. (The number of input channels and the sample rate can be changed /// if desired and if the hardware supports the new setting.) /// </summary> public class AlsaAudioDevice { [DllImport ("libasound.so.2")] static extern int snd_pcm_open(ref IntPtr pcm, string pc_name, int stream, int mode); [DllImport ("libasound.so.2")] static extern int snd_pcm_close(IntPtr pcm); [DllImport ("libasound.so.2")] static extern int snd_pcm_drain(IntPtr pcm); // The next five methods are really all the same method, just with the data being passed // in different forms. (yes, this appears to work okay!) [DllImport ("libasound.so.2")] static extern int snd_pcm_writei(IntPtr pcm, byte[] buf, int size); [DllImport ("libasound.so.2")] static extern int snd_pcm_writei(IntPtr pcm, short[] buf, int size); [DllImport ("libasound.so.2")] static extern int snd_pcm_writei(IntPtr pcm, int[] buf, int size); [DllImport ("libasound.so.2")] static extern int snd_pcm_writei(IntPtr pcm, float[] buf, int size); [DllImport ("libasound.so.2")] static extern int snd_pcm_writei(IntPtr pcm, double[] buf, int size); [DllImport ("libasound.so.2")] static extern int snd_pcm_set_params(IntPtr pcm, int format, int access, int channels, int rate, int soft_resample, int latency); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_malloc(ref IntPtr hwparams); [DllImport ("libasound.so.2")] static extern void snd_pcm_hw_params_free(IntPtr hwparams); [DllImport ("libasound.so.2")] static extern int snd_pcm_sw_params_malloc(ref IntPtr swparams); [DllImport ("libasound.so.2")] static extern void snd_pcm_sw_params_free(IntPtr swparams); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_any(IntPtr pcm, IntPtr hwparams); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_set_access(IntPtr pcm, IntPtr hwparams, int access); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_set_format(IntPtr pcm, IntPtr hwparams, int format); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_set_channels(IntPtr pcm, IntPtr hwparams, uint val); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_set_rate_near(IntPtr pcm, IntPtr hwparams, ref uint val, ref int dir); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params(IntPtr pcm, IntPtr hwparams); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_get_period_size(IntPtr hwparams, ref int val, ref int dir); [DllImport ("libasound.so.2")] static extern int snd_pcm_hw_params_get_buffer_size(IntPtr hwparams, ref int val); [DllImport ("libasound.so.2")] static extern int snd_pcm_sw_params_current(IntPtr pcm, IntPtr swparams); [DllImport ("libasound.so.2")] static extern int snd_pcm_sw_params_set_avail_min(IntPtr pcm, IntPtr swparams, ulong val); [DllImport ("libasound.so.2")] static extern int snd_pcm_sw_params_set_start_threshold(IntPtr pcm, IntPtr swparams, ulong val); [DllImport ("libasound.so.2")] static extern int snd_pcm_sw_params_set_stop_threshold(IntPtr pcm, IntPtr swparams, ulong val); [DllImport ("libasound.so.2")] static extern int snd_pcm_sw_params(IntPtr pcm, IntPtr swparams); [DllImport ("libasound.so.2")] static extern int snd_pcm_format_physical_width(int format); [DllImport ("libasound.so.2")] static extern long snd_pcm_readi(IntPtr pcm, byte[] buffer, long size); [DllImport ("libasound.so.2")] static extern int snd_pcm_nonblock(IntPtr pcm, int nonblock); // These constants are cribbed from alsa/pcm.h. const int SND_PCM_STREA_PLAYBACK = 0; const int SND_PCM_STREA_CAPTURE = 1; const int SND_PCM_FORMAT_U8 = 1; const int SND_PCM_FORMAT_S16_LE = 2; const int SND_PCM_FORMAT_S24_LE = 6; const int SND_PCM_FORMAT_S32_LE = 10; const int SND_PCM_FORMAT_FLOAT_LE = 14; const int SND_PCM_FORMAT_FLOAT64_LE = 16; const int SND_PCM_FORMAT_S24_3LE = 32; const int SND_PCM_ACCESS_RW_INTERLEAVED = 3; // This constant is cribbed from Microsoft. const ushort WAV_FMT_PCM = 1; /// <summary> /// The SF_Mode enum is adapted from sndfile.h /// </summary> internal enum SF_Mode { /* True and false */ FALSE = 0, TRUE = 1, /* Modes for opening files. */ READ = 0x10, WRITE = 0x20, RDWR = 0x30, AMBISONIC_NONE = 0x40, AMBISONIC_B_FORMAT = 0x41 } /// <summary> /// The SF_Format enum is adapted from sndfile.h /// </summary> [Flags] internal enum SF_Format : uint { /* Major formats. */ WAV = 0x010000, /* Microsoft WAV format (little endian default). */ AIFF = 0x020000, /* Apple/SGI AIFF format (big endian). */ AU = 0x030000, /* Sun/NeXT AU format (big endian). */ RAW = 0x040000, /* RAW PCM data. */ PAF = 0x050000, /* Ensoniq PARIS file format. */ SVX = 0x060000, /* Amiga IFF / SVX8 / SV16 format. */ NIST = 0x070000, /* Sphere NIST format. */ VOC = 0x080000, /* VOC files. */ IRCAM = 0x0A0000, /* Berkeley/IRCAM/CARL */ W64 = 0x0B0000, /* Sonic Foundry's 64 bit RIFF/WAV */ MAT4 = 0x0C0000, /* Matlab (tm) V4.2 / GNU Octave 2.0 */ MAT5 = 0x0D0000, /* Matlab (tm) V5.0 / GNU Octave 2.1 */ PVF = 0x0E0000, /* Portable Voice Format */ XI = 0x0F0000, /* Fasttracker 2 Extended Instrument */ HTK = 0x100000, /* HMM Tool Kit format */ SDS = 0x110000, /* Midi Sample Dump Standard */ AVR = 0x120000, /* Audio Visual Research */ WAVEX = 0x130000, /* MS WAVE with WAVEFORMATEX */ SD2 = 0x160000, /* Sound Designer 2 */ FLAC = 0x170000, /* FLAC lossless file format */ CAF = 0x180000, /* Core Audio File format */ WVE = 0x190000, /* Psion WVE format */ OGG = 0x200000, /* Xiph OGG container */ MPC2K = 0x210000, /* Akai MPC 2000 sampler */ RF64 = 0x220000, /* RF64 WAV file */ /* Subtypes from here on. */ PCM_S8 = 0x0001, /* Signed 8 bit data */ PCM_16 = 0x0002, /* Signed 16 bit data */ PCM_24 = 0x0003, /* Signed 24 bit data */ PCM_32 = 0x0004, /* Signed 32 bit data */ PCM_U8 = 0x0005, /* Unsigned 8 bit data (WAV and RAW only) */ FLOAT = 0x0006, /* 32 bit float data */ DOUBLE = 0x0007, /* 64 bit float data */ ULAW = 0x0010, /* U-Law encoded. */ ALAW = 0x0011, /* A-Law encoded. */ IMA_ADPCM = 0x0012, /* IMA ADPCM. */ MS_ADPCM = 0x0013, /* Microsoft ADPCM. */ GSM610 = 0x0020, /* GSM 6.10 encoding. */ VOX_ADPCM = 0x0021, /* OKI / Dialogix ADPCM */ G721_32 = 0x0030, /* 32kbs G721 ADPCM encoding. */ G723_24 = 0x0031, /* 24kbs G723 ADPCM encoding. */ G723_40 = 0x0032, /* 40kbs G723 ADPCM encoding. */ DWVW_12 = 0x0040, /* 12 bit Delta Width Variable Word encoding. */ DWVW_16 = 0x0041, /* 16 bit Delta Width Variable Word encoding. */ DWVW_24 = 0x0042, /* 24 bit Delta Width Variable Word encoding. */ DWVW_N = 0x0043, /* N bit Delta Width Variable Word encoding. */ DPCM_8 = 0x0050, /* 8 bit differential PCM (XI only) */ DPCM_16 = 0x0051, /* 16 bit differential PCM (XI only) */ VORBIS = 0x0060, /* Xiph Vorbis encoding. */ /* Endian-ness options. */ ENDIAN_FILE = 0x00000000, /* Default file endian-ness. */ ENDIAN_LITTLE = 0x10000000, /* Force little endian-ness. */ ENDIAN_BIG = 0x20000000, /* Force big endian-ness. */ ENDIAN_CPU = 0x30000000, /* Force CPU endian-ness. */ SUBMASK = 0x0000FFFF, TYPEMASK = 0x0FFF0000, ENDMASK = 0x30000000 } /// <summary> /// The SF_INFO struct is adapted from sndfile.h /// </summary> [StructLayout(LayoutKind.Sequential)] internal struct SF_INFO { public long frames; public int samplerate; public int channels; public SF_Format format; public int sections; public int seekable; } [DllImport("libsndfile.so.1")] internal static extern IntPtr sf_open(string path, SF_Mode mode, ref SF_INFO info); [DllImport("libsndfile.so.1")] internal static extern long sf_readf_short(IntPtr sndfile, short[] ptr, long frames) ; [DllImport("libsndfile.so.1")] internal static extern long sf_readf_int(IntPtr sndfile, int[] ptr, long frames) ; [DllImport("libsndfile.so.1")] internal static extern long sf_readf_float(IntPtr sndfile, float[] ptr, long frames) ; [DllImport("libsndfile.so.1")] internal static extern long sf_readf_double(IntPtr sndfile, double[] ptr, long frames) ; [DllImport("libsndfile.so.1")] internal static extern int sf_close(IntPtr sndfile); IntPtr _hpcm; IntPtr _hwparams; IntPtr _swparams; Thread _recordingThread; Thread _playbackThread; /// <summary>flag to stop recording or playing</summary> bool _fAsyncQuit; int _pcmFormat; ushort _channelCount; uint _sampleRate; int _startDelay; int _chunkSize = 1024; int _bufferSize; byte[] _audiobuf; ushort _bitsPerFrame; string _tempfile; int _chunkBytes; int _cbWritten; string _filename; IntPtr _hsf; SF_INFO _info; #region Construction and Destruction /// <summary> /// Initialize a new instance of the <see cref="SIL.Media.AlsaAudio.AlsaAudioDevice"/> class. /// </summary> public AlsaAudioDevice() { // Set the defaults for recording. DesiredSampleRate = 22000; DesiredChannelCount = 1; DesiredInputDevice = "default"; } /// <summary> /// Delete any temporary file created during recording that somehow still exists. /// </summary> ~AlsaAudioDevice() { if (!String.IsNullOrEmpty(_tempfile) && File.Exists(_tempfile)) File.Delete(_tempfile); } #endregion #region Public methods and properties /// <summary> /// Play the specified sound file. /// </summary> /// <param name='fileName'> /// true if successful, false if an error occurs /// </param> public bool StartPlaying(string fileName) { if (!File.Exists(fileName)) return false; if (IsPlaying || IsRecording) return false; _info = new SF_INFO(); _hsf = sf_open(fileName, SF_Mode.READ, ref _info); if (_hsf == IntPtr.Zero) { ShowError(String.Format("Sound player cannot open {0}", fileName)); return false; } _filename = fileName; _fAsyncQuit = false; // Create the thread object, passing in the Record method // via a ThreadStart delegate. This does not start the thread. _playbackThread = new Thread(new ThreadStart(Play)); // Start the thread _playbackThread.Start(); // Wait for the started thread to become alive: while (!_playbackThread.IsAlive) ; return true; } /// <summary> /// Start recording into a temporary file. The actual recording is done on its own /// thread, so that it can be stopped asynchronously by user action. /// </summary> /// <returns> /// true if successful, false if an error occurs /// </returns> public bool StartRecording() { if (IsRecording || IsPlaying) return false; _fAsyncQuit = false; // Create the thread object, passing in the Record method // via a ThreadStart delegate. This does not start the thread. _recordingThread = new Thread(new ThreadStart(Record)); // Start the thread _recordingThread.Start(); // Wait for the started thread to become alive: while (!_recordingThread.IsAlive) ; return true; } /// <summary> /// true iff recording is underway. /// </summary> public bool IsRecording { get { return _recordingThread != null && _recordingThread.IsAlive; } } /// <summary> /// Stop the recording, waiting for the thread to die. /// </summary> public void StopRecording() { if (!IsRecording) return; _fAsyncQuit = true; _recordingThread.Join(1000); if (_recordingThread.IsAlive) _recordingThread.Abort(); _recordingThread = null; } /// <summary> /// Write the stored audio data as a WAVE file. /// </summary> public void SaveAsWav(string filePath) { // Make sure we have data. if (String.IsNullOrEmpty(_tempfile)) { _cbWritten = 0; return; } if (!File.Exists(_tempfile)) { _tempfile = null; _cbWritten = 0; return; } if (_cbWritten == 0) { File.Delete(_tempfile); _tempfile = null; return; } FileInfo fi = new FileInfo(_tempfile); Debug.Assert(fi.Length == _cbWritten); WaveFileWriter writer = new WaveFileWriter(filePath); writer.WriteFileHeader((int)fi.Length); WaveFormatChunk format = new WaveFormatChunk(); format.chunkId = "fmt "; format.chunkSize = 16; // size of the struct in bytes - 8 format.audioFormat = WAV_FMT_PCM; format.channelCount = _channelCount; format.sampleRate = _sampleRate; format.byteRate = (uint)(_sampleRate * _channelCount * _bitsPerFrame / 8); format.blockAlign = (ushort)(_channelCount * _bitsPerFrame / 8); format.bitsPerSample = _bitsPerFrame; writer.WriteFormatChunk(format); writer.WriteDataHeader((int)fi.Length); byte[] data = File.ReadAllBytes(_tempfile); Debug.Assert(data.Length == _cbWritten); writer.WriteData(data); writer.Close(); // Clean up the temporary data from the recording process. File.Delete(_tempfile); _tempfile = null; _cbWritten = 0; } /// <summary> /// true iff a sound file is playing. /// </summary> public bool IsPlaying { get { return _playbackThread != null && _playbackThread.IsAlive; } } /// <summary> /// Stop the playing, waiting for the thread to die. /// </summary> public void StopPlaying() { if (!IsPlaying) return; _fAsyncQuit = true; _playbackThread.Join(1000); if (_playbackThread.IsAlive) _playbackThread.Abort(); _playbackThread = null; } public uint DesiredSampleRate { get; set; } public ushort DesiredChannelCount { get; set; } public string DesiredInputDevice { get; set; } #endregion /// <summary> /// Notify the user about an error (not that he'll be able to do anything about it...). /// </summary> void ShowError(string msg) { Console.WriteLine("Audio Device Error: {0}", msg); } /// <summary> /// Initialize the library for recording. /// </summary> /// <returns> /// true if successful, false if an error occurs /// </returns> bool InitializeForRecording() { _pcmFormat = SND_PCM_FORMAT_S16_LE; _channelCount = DesiredChannelCount; _sampleRate = DesiredSampleRate; _startDelay = 1; int res = snd_pcm_open(ref _hpcm, DesiredInputDevice, SND_PCM_STREA_CAPTURE, 0); if (res < 0) { ShowError(String.Format("Cannot open {0} sound device for recording", DesiredInputDevice)); _hpcm = IntPtr.Zero; return false; } _audiobuf = new byte[_chunkSize]; return true; } /// <summary> /// Sets the parameters for either recording or playing a sound file. /// </summary> /// <returns> /// true if successful, false if an error occurs. /// </returns> bool SetParams() { // allocate fresh data structures if (_hwparams != IntPtr.Zero) snd_pcm_hw_params_free(_hwparams); int res = snd_pcm_hw_params_malloc(ref _hwparams); if (res < 0) { return false; } if (_swparams != IntPtr.Zero) snd_pcm_sw_params_free(_swparams); res = snd_pcm_sw_params_malloc(ref _swparams); if (res < 0) { return false; } // Set the values we want for sound processing. res = snd_pcm_hw_params_any(_hpcm, _hwparams); if (res < 0) { return false; } res = snd_pcm_hw_params_set_access(_hpcm, _hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); if (res < 0) { ShowError("Interleaved sound channel access is not available"); Cleanup(); return false; } res = snd_pcm_hw_params_set_format(_hpcm, _hwparams, _pcmFormat); if (res < 0) { ShowError("The desired sound format is not available"); Cleanup(); return false; } res = snd_pcm_hw_params_set_channels(_hpcm, _hwparams, (uint)_channelCount); if (res < 0) { ShowError("The desired sound channel count is not available"); Cleanup(); return false; } uint rate = _sampleRate; int dir = 0; res = snd_pcm_hw_params_set_rate_near(_hpcm, _hwparams, ref rate, ref dir); System.Diagnostics.Debug.Assert(res >= 0); _sampleRate = rate; res = snd_pcm_hw_params(_hpcm, _hwparams); if (res < 0) { ShowError("Unable to install hw params:"); Cleanup(); return false; } snd_pcm_hw_params_get_period_size(_hwparams, ref _chunkSize, ref dir); snd_pcm_hw_params_get_buffer_size(_hwparams, ref _bufferSize); if (_chunkSize == _bufferSize) { ShowError(String.Format("Can't use period equal to buffer size (%lu == %lu)", _chunkSize, _bufferSize)); Cleanup(); return false; } snd_pcm_sw_params_current(_hpcm, _swparams); ulong n = (ulong)_chunkSize; res = snd_pcm_sw_params_set_avail_min(_hpcm, _swparams, n); /* round up to closest transfer boundary */ n = (ulong)_bufferSize; ulong start_threshold; if (_startDelay <= 0) { start_threshold = n + (ulong)((double) rate * _startDelay / 1000000); } else { start_threshold = (ulong)((double) rate * _startDelay / 1000000); } if (start_threshold < 1) start_threshold = 1; if (start_threshold > n) start_threshold = n; res = snd_pcm_sw_params_set_start_threshold(_hpcm, _swparams, start_threshold); Debug.Assert(res >= 0); ulong stop_threshold = (ulong)_bufferSize; res = snd_pcm_sw_params_set_stop_threshold(_hpcm, _swparams, stop_threshold); Debug.Assert(res >= 0); if (snd_pcm_sw_params(_hpcm, _swparams) < 0) { ShowError("unable to install sw params:"); Cleanup(); return false; } int bitsPerSample = snd_pcm_format_physical_width(_pcmFormat); _bitsPerFrame = (ushort)(bitsPerSample * _channelCount); _chunkBytes = _chunkSize * _bitsPerFrame / 8; _audiobuf = new byte[_chunkBytes]; return true; } /// <summary> /// Cleanup this instance by releasing any allocated resources. /// </summary> void Cleanup() { if (_audiobuf != null) _audiobuf = null; if (_hwparams != IntPtr.Zero) { snd_pcm_hw_params_free(_hwparams); _hwparams = IntPtr.Zero; } if (_swparams != IntPtr.Zero) { snd_pcm_sw_params_free(_swparams); _swparams = IntPtr.Zero; } if (_hpcm != IntPtr.Zero) { snd_pcm_close(_hpcm); _hpcm = IntPtr.Zero; } if (_hsf != IntPtr.Zero) { sf_close(_hsf); _hsf = IntPtr.Zero; } } /// <summary> /// Record until out of room for a WAVE file, or until interrupted by the user. /// Write the raw audio data to a temporary file. /// </summary> void Record() { if (!InitializeForRecording()) return; SetParams(); _tempfile = Path.GetTempFileName(); var file = File.Create(_tempfile); int rest = Int32.MaxValue; _cbWritten = 0; while (rest > 0 && !_fAsyncQuit) { int byteCount = (rest < _chunkBytes) ? rest : _chunkBytes; int frameCount = byteCount * 8 / _bitsPerFrame; Debug.Assert(frameCount == _chunkSize); int count = (int)snd_pcm_readi(_hpcm, _audiobuf, (long)frameCount); if (count < 0) { Console.WriteLine("AlsaAudioDevice: stopping because returned count ({0}) signals an error", count); break; } if (count != frameCount) { Debug.WriteLine(String.Format("AlsaAudioDevice: short read ({0} < requested {1} frames)", count, frameCount)); byteCount = (count * _bitsPerFrame) / 8; } file.Write(_audiobuf, 0, byteCount); rest -= byteCount; _cbWritten += byteCount; } file.Close(); file.Dispose(); Cleanup(); _fAsyncQuit = false; } /// <summary> /// Initialize the library for playing a sound file. /// </summary> /// <returns> /// true if successful, false if an error occurs /// </returns> bool InitializeForPlayback() { if (_hsf == IntPtr.Zero) return false; int res = snd_pcm_open(ref _hpcm, "default", SND_PCM_STREA_PLAYBACK, 0); if (res < 0) { ShowError("Cannot open default sound device for recording"); _hpcm = IntPtr.Zero; return false; } switch (_info.format & SF_Format.SUBMASK) { case SF_Format.PCM_24: case SF_Format.PCM_32: _pcmFormat = SND_PCM_FORMAT_S32_LE; break; case SF_Format.FLOAT: _pcmFormat = SND_PCM_FORMAT_FLOAT_LE; break; case SF_Format.DOUBLE: _pcmFormat = SND_PCM_FORMAT_FLOAT64_LE; break; default: _pcmFormat = SND_PCM_FORMAT_S16_LE; break; } _channelCount = (ushort)_info.channels; _sampleRate = (uint)_info.samplerate; _startDelay = 0; SetParams(); return true; } /// <summary> /// Play the sound file that we've opened. The playback occurs on its own thread so that /// the user can asynchronously stop the playback. /// </summary> void Play() { if (!InitializeForPlayback()) return; try { int remaining = (int)_info.frames; switch (_pcmFormat) { case SND_PCM_FORMAT_S32_LE: var ints = new int[1024 * _info.channels]; while (remaining > 0) { int num = (remaining >= 1024) ? 1024 : remaining; long cf = sf_readf_int(_hsf, ints, num); if (cf != num) break; int num2 = snd_pcm_writei(_hpcm, ints, num); if (num2 != num) break; remaining -= num; } break; case SND_PCM_FORMAT_FLOAT_LE: var floats = new float[1024 * _info.channels]; while (remaining > 0) { int num = (remaining >= 1024) ? 1024 : remaining; long cf = sf_readf_float(_hsf, floats, num); if (cf != num) break; int num2 = snd_pcm_writei(_hpcm, floats, num); if (num2 != num) break; remaining -= num; } break; case SND_PCM_FORMAT_FLOAT64_LE: var doubles = new double[1024 * _info.channels]; while (remaining > 0) { int num = (remaining >= 1024) ? 1024 : remaining; long cf = sf_readf_double(_hsf, doubles, num); if (cf != num) break; int num2 = snd_pcm_writei(_hpcm, doubles, num); if (num2 != num) break; remaining -= num; } break; default: var shorts = new short[1024 * _info.channels]; while (remaining > 0) { int num = (remaining >= 1024) ? 1024 : remaining; long cf = sf_readf_short(_hsf, shorts, num); if (cf != num) break; int num2 = snd_pcm_writei(_hpcm, shorts, num); if (num2 != num) break; remaining -= num; } break; } if (remaining > 0) { ShowError(String.Format("Error trying to play {0}", _filename)); } snd_pcm_nonblock(_hpcm, 0); snd_pcm_drain(_hpcm); snd_pcm_nonblock(_hpcm, 0); } finally { Cleanup(); _fAsyncQuit = false; } } /// <summary> /// The common heading of every "chunk" of a WAVE file. /// </summary> public class WaveChunk { /// <summary>The chunk identifier (four 8-bit chars in the file)</summary> public string chunkId; /// <summary>The size of the chunk following this header</summary> public UInt32 chunkSize; } /// <summary> /// Wave format block: chunkId == "fmt ", chunkSize >= 16 /// </summary> public class WaveFormatChunk : WaveChunk { /// <summary>must == 1 (PCM) for us to work with this file</summary> public UInt16 audioFormat; /// <summary>number of channels (tracks) in the recording</summary> public UInt16 channelCount; /// <summary>number of samples per second</summary> public UInt32 sampleRate; /// <summary>number of bytes consumed per second</summary> public UInt32 byteRate; /// <summary>number of bytes per sample</summary> public UInt16 blockAlign; /// <summary>number of bits per sample (better be a small multiple of 8!)</summary> public UInt16 bitsPerSample; /// <summary>extra information found in some files</summary> public byte[] extraInfo; } /// <summary> /// Utility class for writing a WAVE file. /// </summary> public class WaveFileWriter { BinaryWriter _writer; /// <summary> /// Initializes a new instance of the <see cref="SIL.Media.AlsaAudio.AlsaAudioDevice.WaveFileWriter"/> class. /// </summary> public WaveFileWriter(string filename) { _writer = new BinaryWriter(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None)); } /// <summary> /// Writes the WAVE file header. /// </summary> public void WriteFileHeader(int dataSize) { if (_writer == null) return; _writer.Write((byte)'R'); _writer.Write((byte)'I'); _writer.Write((byte)'F'); _writer.Write((byte)'F'); _writer.Write((Int32)(dataSize + 4 + 24 + 8)); _writer.Write((byte)'W'); _writer.Write((byte)'A'); _writer.Write((byte)'V'); _writer.Write((byte)'E'); } /// <summary> /// Writes the WAVE format block. /// </summary> public void WriteFormatChunk(WaveFormatChunk format) { if (_writer == null) return; _writer.Write((byte)'f'); _writer.Write((byte)'m'); _writer.Write((byte)'t'); _writer.Write((byte)' '); _writer.Write(format.chunkSize); _writer.Write(format.audioFormat); _writer.Write(format.channelCount); _writer.Write(format.sampleRate); _writer.Write(format.byteRate); _writer.Write(format.blockAlign); _writer.Write(format.bitsPerSample); } /// <summary> /// Writes the WAVE data header. /// </summary> public void WriteDataHeader(int dataSize) { if (_writer == null) return; _writer.Write((byte)'d'); _writer.Write((byte)'a'); _writer.Write((byte)'t'); _writer.Write((byte)'a'); _writer.Write(dataSize); } /// <summary> /// Writes the WAVE sound data. /// </summary> public void WriteData(byte[] data) { if (_writer == null) return; _writer.Write(data); } /// <summary> /// Close this instance. /// </summary> public void Close() { if (_writer != null) { _writer.Close(); _writer = null; } } } } }
// 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.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; using System.Security.Principal; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace System.IO.Pipes { public abstract partial class PipeStream : Stream { internal const bool CheckOperationsRequiresSetHandle = true; internal ThreadPoolBoundHandle _threadPoolBinding; // In Windows we don't use isCurrentUserOnly flag for the path because we set an ACL to the pipe. internal static string GetPipePath(string serverName, string pipeName, bool isCurrentUserOnly) { string normalizedPipePath = Path.GetFullPath(@"\\" + serverName + @"\pipe\" + pipeName); if (String.Equals(normalizedPipePath, @"\\.\pipe\" + AnonymousPipeName, StringComparison.OrdinalIgnoreCase)) { throw new ArgumentOutOfRangeException(nameof(pipeName), SR.ArgumentOutOfRange_AnonymousReserved); } return normalizedPipePath; } /// <summary>Throws an exception if the supplied handle does not represent a valid pipe.</summary> /// <param name="safePipeHandle">The handle to validate.</param> internal void ValidateHandleIsPipe(SafePipeHandle safePipeHandle) { // Check that this handle is infact a handle to a pipe. if (Interop.Kernel32.GetFileType(safePipeHandle) != Interop.Kernel32.FileTypes.FILE_TYPE_PIPE) { throw new IOException(SR.IO_InvalidPipeHandle); } } /// <summary>Initializes the handle to be used asynchronously.</summary> /// <param name="handle">The handle.</param> private void InitializeAsyncHandle(SafePipeHandle handle) { // If the handle is of async type, bind the handle to the ThreadPool so that we can use // the async operations (it's needed so that our native callbacks get called). _threadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle); } private void DisposeCore(bool disposing) { if (disposing) { _threadPoolBinding?.Dispose(); } } private unsafe int ReadCore(Span<byte> buffer) { int errorCode = 0; int r = ReadFileNative(_handle, buffer, null, out errorCode); if (r == -1) { // If the other side has broken the connection, set state to Broken and return 0 if (errorCode == Interop.Errors.ERROR_BROKEN_PIPE || errorCode == Interop.Errors.ERROR_PIPE_NOT_CONNECTED) { State = PipeState.Broken; r = 0; } else { throw Win32Marshal.GetExceptionForWin32Error(errorCode, String.Empty); } } _isMessageComplete = (errorCode != Interop.Errors.ERROR_MORE_DATA); Debug.Assert(r >= 0, "PipeStream's ReadCore is likely broken."); return r; } private Task<int> ReadAsyncCore(Memory<byte> buffer, CancellationToken cancellationToken) { var completionSource = new ReadWriteCompletionSource(this, buffer, isWrite: false); // Queue an async ReadFile operation and pass in a packed overlapped int errorCode = 0; int r; unsafe { r = ReadFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode); } // ReadFile, the OS version, will return 0 on failure, but this ReadFileNative wrapper // returns -1. This will return the following: // - On error, r==-1. // - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING // - On async requests that completed sequentially, r==0 // // You will NEVER RELIABLY be able to get the number of buffer read back from this call // when using overlapped structures! You must not pass in a non-null lpNumBytesRead to // ReadFile when using overlapped structures! This is by design NT behavior. if (r == -1) { switch (errorCode) { // One side has closed its handle or server disconnected. // Set the state to Broken and do some cleanup work case Interop.Errors.ERROR_BROKEN_PIPE: case Interop.Errors.ERROR_PIPE_NOT_CONNECTED: State = PipeState.Broken; unsafe { // Clear the overlapped status bit for this special case. Failure to do so looks // like we are freeing a pending overlapped. completionSource.Overlapped->InternalLow = IntPtr.Zero; } completionSource.ReleaseResources(); UpdateMessageCompletion(true); return s_zeroTask; case Interop.Errors.ERROR_IO_PENDING: break; default: throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } completionSource.RegisterForCancellation(cancellationToken); return completionSource.Task; } private unsafe void WriteCore(ReadOnlySpan<byte> buffer) { int errorCode = 0; int r = WriteFileNative(_handle, buffer, null, out errorCode); if (r == -1) { throw WinIOError(errorCode); } Debug.Assert(r >= 0, "PipeStream's WriteCore is likely broken."); } private Task WriteAsyncCore(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken) { var completionSource = new ReadWriteCompletionSource(this, buffer, isWrite: true); int errorCode = 0; // Queue an async WriteFile operation and pass in a packed overlapped int r; unsafe { r = WriteFileNative(_handle, buffer.Span, completionSource.Overlapped, out errorCode); } // WriteFile, the OS version, will return 0 on failure, but this WriteFileNative // wrapper returns -1. This will return the following: // - On error, r==-1. // - On async requests that are still pending, r==-1 w/ hr==ERROR_IO_PENDING // - On async requests that completed sequentially, r==0 // // You will NEVER RELIABLY be able to get the number of buffer written back from this // call when using overlapped structures! You must not pass in a non-null // lpNumBytesWritten to WriteFile when using overlapped structures! This is by design // NT behavior. if (r == -1 && errorCode != Interop.Errors.ERROR_IO_PENDING) { completionSource.ReleaseResources(); throw WinIOError(errorCode); } completionSource.RegisterForCancellation(cancellationToken); return completionSource.Task; } // Blocks until the other end of the pipe has read in all written buffer. public void WaitForPipeDrain() { CheckWriteOperations(); if (!CanWrite) { throw Error.GetWriteNotSupported(); } // Block until other end of the pipe has read everything. if (!Interop.Kernel32.FlushFileBuffers(_handle)) { throw WinIOError(Marshal.GetLastWin32Error()); } } // Gets the transmission mode for the pipe. This is virtual so that subclassing types can // override this in cases where only one mode is legal (such as anonymous pipes) public virtual PipeTransmissionMode TransmissionMode { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (_isFromExistingHandle) { int pipeFlags; if (!Interop.Kernel32.GetNamedPipeInfo(_handle, out pipeFlags, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } if ((pipeFlags & Interop.Kernel32.PipeOptions.PIPE_TYPE_MESSAGE) != 0) { return PipeTransmissionMode.Message; } else { return PipeTransmissionMode.Byte; } } else { return _transmissionMode; } } } // Gets the buffer size in the inbound direction for the pipe. This checks if pipe has read // access. If that passes, call to GetNamedPipeInfo will succeed. public virtual int InBufferSize { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")] get { CheckPipePropertyOperations(); if (!CanRead) { throw new NotSupportedException(SR.NotSupported_UnreadableStream); } int inBufferSize; if (!Interop.Kernel32.GetNamedPipeInfo(_handle, IntPtr.Zero, IntPtr.Zero, out inBufferSize, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } return inBufferSize; } } // Gets the buffer size in the outbound direction for the pipe. This uses cached version // if it's an outbound only pipe because GetNamedPipeInfo requires read access to the pipe. // However, returning cached is good fallback, especially if user specified a value in // the ctor. public virtual int OutBufferSize { [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] get { CheckPipePropertyOperations(); if (!CanWrite) { throw new NotSupportedException(SR.NotSupported_UnwritableStream); } int outBufferSize; // Use cached value if direction is out; otherwise get fresh version if (_pipeDirection == PipeDirection.Out) { outBufferSize = _outBufferSize; } else if (!Interop.Kernel32.GetNamedPipeInfo(_handle, IntPtr.Zero, out outBufferSize, IntPtr.Zero, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } return outBufferSize; } } public virtual PipeTransmissionMode ReadMode { get { CheckPipePropertyOperations(); // get fresh value if it could be stale if (_isFromExistingHandle || IsHandleExposed) { UpdateReadMode(); } return _readMode; } [SuppressMessage("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands", Justification = "Security model of pipes: demand at creation but no subsequent demands")] set { // Nothing fancy here. This is just a wrapper around the Win32 API. Note, that NamedPipeServerStream // and the AnonymousPipeStreams override this. CheckPipePropertyOperations(); if (value < PipeTransmissionMode.Byte || value > PipeTransmissionMode.Message) { throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_TransmissionModeByteOrMsg); } unsafe { int pipeReadType = (int)value << 1; if (!Interop.Kernel32.SetNamedPipeHandleState(_handle, &pipeReadType, IntPtr.Zero, IntPtr.Zero)) { throw WinIOError(Marshal.GetLastWin32Error()); } else { _readMode = value; } } } } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- private unsafe int ReadFileNative(SafePipeHandle handle, Span<byte> buffer, NativeOverlapped* overlapped, out int errorCode) { DebugAssertHandleValid(handle); Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to ReadFileNative."); // You can't use the fixed statement on an array of length 0. Note that async callers // check to avoid calling this first, so they can call user's callback if (buffer.Length == 0) { errorCode = 0; return 0; } int r = 0; int numBytesRead = 0; fixed (byte* p = &MemoryMarshal.GetReference(buffer)) { r = _isAsync ? Interop.Kernel32.ReadFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) : Interop.Kernel32.ReadFile(handle, p, buffer.Length, out numBytesRead, IntPtr.Zero); } if (r == 0) { // In message mode, the ReadFile can inform us that there is more data to come. errorCode = Marshal.GetLastWin32Error(); return errorCode == Interop.Errors.ERROR_MORE_DATA ? numBytesRead : -1; } else { errorCode = 0; return numBytesRead; } } private unsafe int WriteFileNative(SafePipeHandle handle, ReadOnlySpan<byte> buffer, NativeOverlapped* overlapped, out int errorCode) { DebugAssertHandleValid(handle); Debug.Assert((_isAsync && overlapped != null) || (!_isAsync && overlapped == null), "Async IO parameter screwup in call to WriteFileNative."); // You can't use the fixed statement on an array of length 0. Note that async callers // check to avoid calling this first, so they can call user's callback if (buffer.Length == 0) { errorCode = 0; return 0; } int r = 0; int numBytesWritten = 0; fixed (byte* p = &MemoryMarshal.GetReference(buffer)) { r = _isAsync ? Interop.Kernel32.WriteFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) : Interop.Kernel32.WriteFile(handle, p, buffer.Length, out numBytesWritten, IntPtr.Zero); } if (r == 0) { errorCode = Marshal.GetLastWin32Error(); return -1; } else { errorCode = 0; return numBytesWritten; } } internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES(); secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES); secAttrs.bInheritHandle = Interop.BOOL.TRUE; } return secAttrs; } internal static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability, PipeSecurity pipeSecurity, ref GCHandle pinningHandle) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default(Interop.Kernel32.SECURITY_ATTRIBUTES); secAttrs.nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs.bInheritHandle = Interop.BOOL.TRUE; } if (pipeSecurity != null) { byte[] securityDescriptor = pipeSecurity.GetSecurityDescriptorBinaryForm(); pinningHandle = GCHandle.Alloc(securityDescriptor, GCHandleType.Pinned); fixed (byte* pSecurityDescriptor = securityDescriptor) { secAttrs.lpSecurityDescriptor = (IntPtr)pSecurityDescriptor; } } return secAttrs; } /// <summary> /// Determine pipe read mode from Win32 /// </summary> private void UpdateReadMode() { int flags; if (!Interop.Kernel32.GetNamedPipeHandleState(SafePipeHandle, out flags, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, 0)) { throw WinIOError(Marshal.GetLastWin32Error()); } if ((flags & Interop.Kernel32.PipeOptions.PIPE_READMODE_MESSAGE) != 0) { _readMode = PipeTransmissionMode.Message; } else { _readMode = PipeTransmissionMode.Byte; } } /// <summary> /// Filter out all pipe related errors and do some cleanup before calling Error.WinIOError. /// </summary> /// <param name="errorCode"></param> internal Exception WinIOError(int errorCode) { switch (errorCode) { case Interop.Errors.ERROR_BROKEN_PIPE: case Interop.Errors.ERROR_PIPE_NOT_CONNECTED: case Interop.Errors.ERROR_NO_DATA: // Other side has broken the connection _state = PipeState.Broken; return new IOException(SR.IO_PipeBroken, Win32Marshal.MakeHRFromErrorCode(errorCode)); case Interop.Errors.ERROR_HANDLE_EOF: return Error.GetEndOfFile(); case Interop.Errors.ERROR_INVALID_HANDLE: // For invalid handles, detect the error and mark our handle // as invalid to give slightly better error messages. Also // help ensure we avoid handle recycling bugs. _handle.SetHandleAsInvalid(); _state = PipeState.Broken; break; } return Win32Marshal.GetExceptionForWin32Error(errorCode); } } }
/* Copyright (c) 2006-2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* Change history * Oct 13 2008 Joe Feser [email protected] * Converted ArrayLists and other .NET 1.1 collections to use Generics * Combined IExtensionElement and IExtensionElementFactory interfaces * */ using System; using System.IO; using System.Collections; using System.Text; using System.Xml; using Google.GData.Client; namespace Google.GData.Extensions { /// <summary> /// GData schema extension describing a nested feed link. /// </summary> public class FeedLink : IExtensionElementFactory { /// <summary>holds the href property</summary> private string href; /// <summary>holds the readOnly property</summary> private bool readOnly; /// <summary>holds the feed property</summary> private AtomFeed feed; /// <summary>holds the rel attribute of the EntyrLink element</summary> private string rel; private bool readOnlySet; private int countHint; /// <summary> /// constructor /// </summary> public FeedLink() { this.countHint = -1; this.readOnly = true; } /// <summary> /// Entry URI /// </summary> public string Href { get { return href;} set { href = value;} } /// <summary> /// Read only flag. /// </summary> public bool ReadOnly { get { return readOnly;} set { this.readOnly = value; this.readOnlySet = true;} } /// <summary> /// Count hint. /// </summary> public int CountHint { get { return countHint;} set { countHint = value;} } /// <summary> /// Nested entry (optional). /// </summary> public AtomFeed Feed { get { return feed;} set { feed = value;} } ////////////////////////////////////////////////////////////////////// /// <summary>accessor method public string Rel</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// public string Rel { get {return this.rel;} set {this.rel = value;} } ///////////////////////////////////////////////////////////////////////////// #region FeedLink Parser ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create an FeedLink object.</summary> /// <param name="node">feedLink node</param> /// <returns> the created FeedLink object</returns> ////////////////////////////////////////////////////////////////////// public static FeedLink ParseFeedLink(XmlNode node) { Tracing.TraceCall(); FeedLink link = null; Tracing.Assert(node != null, "node should not be null"); if (node == null) { throw new ArgumentNullException("node"); } object localname = node.LocalName; if (localname.Equals(GDataParserNameTable.XmlFeedLinkElement)) { link = new FeedLink(); if (node.Attributes != null) { if (node.Attributes[GDataParserNameTable.XmlAttributeHref] != null) { link.Href = node.Attributes[GDataParserNameTable.XmlAttributeHref].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeReadOnly] != null) { link.ReadOnly = node.Attributes[GDataParserNameTable.XmlAttributeReadOnly].Value.Equals(Utilities.XSDTrue); } if (node.Attributes[GDataParserNameTable.XmlAttributeRel] != null) { link.Rel = node.Attributes[GDataParserNameTable.XmlAttributeRel].Value; } if (node.Attributes[GDataParserNameTable.XmlAttributeCountHint] != null) { try { link.CountHint = Int32.Parse(node.Attributes[GDataParserNameTable.XmlAttributeCountHint].Value); } catch (FormatException fe) { throw new ArgumentException("Invalid g:feedLink/@countHint.", fe); } } } if (node.HasChildNodes) { XmlNode feedChild = node.FirstChild; while (feedChild != null && feedChild is XmlElement) { if (feedChild.LocalName == AtomParserNameTable.XmlFeedElement && feedChild.NamespaceURI == BaseNameTable.NSAtom) { if (link.Feed == null) { link.Feed = new AtomFeed(null, new Service()); Stream feedStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(feedChild.OuterXml)); link.Feed.Parse(feedStream, AlternativeFormat.Atom); } else { throw new ArgumentException("Only one feed is allowed inside the g:feedLink"); } } feedChild = feedChild.NextSibling; } } } return link; } #endregion #region overloaded from IExtensionElementFactory ////////////////////////////////////////////////////////////////////// /// <summary>Parses an xml node to create a Where object.</summary> /// <param name="node">the node to parse node</param> /// <param name="parser">the xml parser to use if we need to dive deeper</param> /// <returns>the created Where object</returns> ////////////////////////////////////////////////////////////////////// public IExtensionElementFactory CreateInstance(XmlNode node, AtomFeedParser parser) { return FeedLink.ParseFeedLink(node); } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlName { get { return GDataParserNameTable.XmlFeedLinkElement;} } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlNameSpace { get { return BaseNameTable.gNamespace; } } ////////////////////////////////////////////////////////////////////// /// <summary>Returns the constant representing this XML element.</summary> ////////////////////////////////////////////////////////////////////// public string XmlPrefix { get { return BaseNameTable.gDataPrefix; } } #endregion #region overloaded for persistence /// <summary> /// Persistence method for the FeedLink object /// </summary> /// <param name="writer">the xmlwriter to write into</param> public void Save(XmlWriter writer) { if (Utilities.IsPersistable(this.Href) || this.Feed != null) { writer.WriteStartElement(XmlPrefix, XmlName, XmlNameSpace); if (Utilities.IsPersistable(this.Href)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeHref, this.Href); } // do not save the default if (this.readOnlySet) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeReadOnly, Utilities.ConvertBooleanToXSDString(this.ReadOnly)); } if (Utilities.IsPersistable(this.Rel)) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeRel, this.Rel); } if (this.countHint > -1) { writer.WriteAttributeString(GDataParserNameTable.XmlAttributeCountHint, this.countHint.ToString()); } if (Feed != null) { Feed.SaveToXml(writer); } writer.WriteEndElement(); } } #endregion } }
using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Listener.Configuration; using Microsoft.VisualStudio.Services.Agent.Util; using System; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio.Services.Common; namespace Microsoft.VisualStudio.Services.Agent.Listener { [ServiceLocator(Default = typeof(Agent))] public interface IAgent : IAgentService { Task<int> ExecuteCommand(CommandSettings command); } public sealed class Agent : AgentService, IAgent { private IMessageListener _listener; private ITerminal _term; private bool _inConfigStage; private ManualResetEvent _completedCommand = new ManualResetEvent(false); public override void Initialize(IHostContext hostContext) { base.Initialize(hostContext); _term = HostContext.GetService<ITerminal>(); } public async Task<int> ExecuteCommand(CommandSettings command) { try { var agentWebProxy = HostContext.GetService<IVstsAgentWebProxy>(); VssHttpMessageHandler.DefaultWebProxy = agentWebProxy; _inConfigStage = true; _completedCommand.Reset(); _term.CancelKeyPress += CtrlCHandler; //register a SIGTERM handler HostContext.Unloading += Agent_Unloading; // TODO Unit test to cover this logic Trace.Info(nameof(ExecuteCommand)); var configManager = HostContext.GetService<IConfigurationManager>(); // command is not required, if no command it just starts and/or configures if not configured // TODO: Invalid config prints usage if (command.Help) { PrintUsage(); return Constants.Agent.ReturnCode.Success; } if (command.Version) { _term.WriteLine(Constants.Agent.Version); return Constants.Agent.ReturnCode.Success; } if (command.Commit) { _term.WriteLine(BuildConstants.Source.CommitHash); return Constants.Agent.ReturnCode.Success; } // Configure agent prompt for args if not supplied // Unattend configure mode will not prompt for args if not supplied and error on any missing or invalid value. if (command.Configure) { try { await configManager.ConfigureAsync(command); return Constants.Agent.ReturnCode.Success; } catch (Exception ex) { Trace.Error(ex); _term.WriteError(ex.Message); return Constants.Agent.ReturnCode.TerminatedError; } } // Unconfigure, remove config files, service and exit if (command.Unconfigure) { try { await configManager.UnconfigureAsync(command); return Constants.Agent.ReturnCode.Success; } catch (Exception ex) { Trace.Error(ex); _term.WriteError(ex.Message); return Constants.Agent.ReturnCode.TerminatedError; } } _inConfigStage = false; // YAML string yamlFile = command.GetYaml(); if (!string.IsNullOrEmpty(yamlFile)) { _term.WriteLine("Local run mode is currently experimental. The interface and behavior will change in a future version."); if (!command.Unattended) { _term.WriteLine("Press Enter to continue."); _term.ReadLine(); } HostContext.RunMode = RunMode.Local; command.SetUnattended(); var localRunner = HostContext.GetService<ILocalRunner>(); return await localRunner.RunAsync(command, HostContext.AgentShutdownToken); } AgentSettings settings = configManager.LoadSettings(); var store = HostContext.GetService<IConfigurationStore>(); bool configuredAsService = store.IsServiceConfigured(); // Run agent //if (command.Run) // this line is current break machine provisioner. //{ // Error if agent not configured. if (!configManager.IsConfigured()) { _term.WriteError(StringUtil.Loc("AgentIsNotConfigured")); PrintUsage(); return Constants.Agent.ReturnCode.TerminatedError; } Trace.Verbose($"Configured as service: '{configuredAsService}'"); //Get the startup type of the agent i.e., autostartup, service, manualinteractive StartupType startType; var startupTypeAsString = command.GetStartupType(); if (string.IsNullOrEmpty(startupTypeAsString) && configuredAsService) { // We need try our best to make the startup type accurate // The problem is coming from agent autoupgrade, which result an old version service host binary but a newer version agent binary // At that time the servicehost won't pass --startuptype to agent.listener while the agent is actually running as service. // We will guess the startup type only when the agent is configured as service and the guess will based on whether STDOUT/STDERR/STDIN been redirect or not Trace.Info($"Try determine agent startup type base on console redirects."); startType = (Console.IsErrorRedirected && Console.IsInputRedirected && Console.IsOutputRedirected) ? StartupType.Service : StartupType.ManualInteractive; } else { if (!Enum.TryParse(startupTypeAsString, true, out startType)) { Trace.Info($"Could not parse the argument value '{startupTypeAsString}' for StartupType. Defaulting to {StartupType.ManualInteractive}"); startType = StartupType.ManualInteractive; } } Trace.Info($"Set agent startup type - {startType}"); HostContext.StartupType = startType; #if OS_WINDOWS if (store.IsAutoLogonConfigured()) { if(HostContext.StartupType != StartupType.Service) { Trace.Info($"Autologon is configured on the machine, dumping all the autologon related registry settings"); var autoLogonRegManager = HostContext.GetService<IAutoLogonRegistryManager>(); autoLogonRegManager.DumpAutoLogonRegistrySettings(); } else { Trace.Info($"Autologon is configured on the machine but current Agent.Listner.exe is launched from the windows service"); } } #endif // Run the agent interactively or as service return await RunAsync(settings); } finally { _term.CancelKeyPress -= CtrlCHandler; HostContext.Unloading -= Agent_Unloading; _completedCommand.Set(); } } private void Agent_Unloading(object sender, EventArgs e) { if ((!_inConfigStage) && (!HostContext.AgentShutdownToken.IsCancellationRequested)) { HostContext.ShutdownAgent(ShutdownReason.UserCancelled); _completedCommand.WaitOne(Constants.Agent.ExitOnUnloadTimeout); } } private void CtrlCHandler(object sender, EventArgs e) { _term.WriteLine("Exiting..."); if (_inConfigStage) { HostContext.Dispose(); Environment.Exit(Constants.Agent.ReturnCode.TerminatedError); } else { ConsoleCancelEventArgs cancelEvent = e as ConsoleCancelEventArgs; if (cancelEvent != null && HostContext.GetService<IConfigurationStore>().IsServiceConfigured()) { ShutdownReason reason; if (cancelEvent.SpecialKey == ConsoleSpecialKey.ControlBreak) { Trace.Info("Received Ctrl-Break signal from agent service host, this indicate the operating system is shutting down."); reason = ShutdownReason.OperatingSystemShutdown; } else { Trace.Info("Received Ctrl-C signal, stop agent.listener and agent.worker."); reason = ShutdownReason.UserCancelled; } HostContext.ShutdownAgent(reason); } else { HostContext.ShutdownAgent(ShutdownReason.UserCancelled); } } } //create worker manager, create message listener and start listening to the queue private async Task<int> RunAsync(AgentSettings settings) { Trace.Info(nameof(RunAsync)); _listener = HostContext.GetService<IMessageListener>(); if (!await _listener.CreateSessionAsync(HostContext.AgentShutdownToken)) { return Constants.Agent.ReturnCode.TerminatedError; } _term.WriteLine(StringUtil.Loc("ListenForJobs", DateTime.UtcNow)); IJobDispatcher jobDispatcher = null; CancellationTokenSource messageQueueLoopTokenSource = CancellationTokenSource.CreateLinkedTokenSource(HostContext.AgentShutdownToken); try { var notification = HostContext.GetService<IJobNotification>(); if (!String.IsNullOrEmpty(settings.NotificationSocketAddress)) { notification.StartClient(settings.NotificationSocketAddress); } else { notification.StartClient(settings.NotificationPipeName, HostContext.AgentShutdownToken); } // this is not a reliable way to disable auto update. // we need server side work to really enable the feature // https://github.com/Microsoft/vsts-agent/issues/446 (Feature: Allow agent / pool to opt out of automatic updates) bool disableAutoUpdate = !string.IsNullOrEmpty(Environment.GetEnvironmentVariable("agent.disableupdate")); bool autoUpdateInProgress = false; Task<bool> selfUpdateTask = null; jobDispatcher = HostContext.CreateService<IJobDispatcher>(); while (!HostContext.AgentShutdownToken.IsCancellationRequested) { TaskAgentMessage message = null; bool skipMessageDeletion = false; try { Task<TaskAgentMessage> getNextMessage = _listener.GetNextMessageAsync(messageQueueLoopTokenSource.Token); if (autoUpdateInProgress) { Trace.Verbose("Auto update task running at backend, waiting for getNextMessage or selfUpdateTask to finish."); Task completeTask = await Task.WhenAny(getNextMessage, selfUpdateTask); if (completeTask == selfUpdateTask) { autoUpdateInProgress = false; if (await selfUpdateTask) { Trace.Info("Auto update task finished at backend, an agent update is ready to apply exit the current agent instance."); Trace.Info("Stop message queue looping."); messageQueueLoopTokenSource.Cancel(); try { await getNextMessage; } catch (Exception ex) { Trace.Info($"Ignore any exception after cancel message loop. {ex}"); } return Constants.Agent.ReturnCode.AgentUpdating; } else { Trace.Info("Auto update task finished at backend, there is no available agent update needs to apply, continue message queue looping."); } } } message = await getNextMessage; //get next message if (string.Equals(message.MessageType, AgentRefreshMessage.MessageType, StringComparison.OrdinalIgnoreCase)) { if (disableAutoUpdate) { Trace.Info("Refresh message received, skip autoupdate since environment variable agent.disableupdate is set."); } else { if (autoUpdateInProgress == false) { autoUpdateInProgress = true; var agentUpdateMessage = JsonUtility.FromString<AgentRefreshMessage>(message.Body); var selfUpdater = HostContext.GetService<ISelfUpdater>(); selfUpdateTask = selfUpdater.SelfUpdate(agentUpdateMessage, jobDispatcher, HostContext.StartupType != StartupType.Service, HostContext.AgentShutdownToken); Trace.Info("Refresh message received, kick-off selfupdate background process."); } else { Trace.Info("Refresh message received, skip autoupdate since a previous autoupdate is already running."); } } } else if (string.Equals(message.MessageType, JobRequestMessageTypes.AgentJobRequest, StringComparison.OrdinalIgnoreCase)) { if (autoUpdateInProgress) { skipMessageDeletion = true; } else { var newJobMessage = JsonUtility.FromString<AgentJobRequestMessage>(message.Body); jobDispatcher.Run(newJobMessage); } } else if (string.Equals(message.MessageType, JobCancelMessage.MessageType, StringComparison.OrdinalIgnoreCase)) { var cancelJobMessage = JsonUtility.FromString<JobCancelMessage>(message.Body); bool jobCancelled = jobDispatcher.Cancel(cancelJobMessage); skipMessageDeletion = autoUpdateInProgress && !jobCancelled; } else { Trace.Error($"Received message {message.MessageId} with unsupported message type {message.MessageType}."); } } finally { if (!skipMessageDeletion && message != null) { try { await _listener.DeleteMessageAsync(message); } catch (Exception ex) { Trace.Error($"Catch exception during delete message from message queue. message id: {message.MessageId}"); Trace.Error(ex); } finally { message = null; } } } } } finally { if (jobDispatcher != null) { await jobDispatcher.ShutdownAsync(); } //TODO: make sure we don't mask more important exception await _listener.DeleteSessionAsync(); messageQueueLoopTokenSource.Dispose(); } return Constants.Agent.ReturnCode.Success; } private void PrintUsage() { _term.WriteLine(StringUtil.Loc("ListenerHelp")); } } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.IO; using System.Data; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using System.Xml; using System.Xml.Serialization; using WebsitePanel.Server; using WebsitePanel.Providers; using WebsitePanel.Providers.OS; using OS = WebsitePanel.Providers.OS; using System.Collections; namespace WebsitePanel.EnterpriseServer { public class OperatingSystemController : IImportController, IBackupController { private const int FILE_BUFFER_LENGTH = 5000000; // ~5MB private static OS.OperatingSystem GetOS(int serviceId) { OS.OperatingSystem os = new OS.OperatingSystem(); ServiceProviderProxy.Init(os, serviceId); return os; } #region ODBC DSNs public static DataSet GetRawOdbcSourcesPaged(int packageId, string filterColumn, string filterValue, string sortColumn, int startRow, int maximumRows) { return PackageController.GetRawPackageItemsPaged(packageId, ResourceGroups.Os, typeof(SystemDSN), true, filterColumn, filterValue, sortColumn, startRow, maximumRows); } public static List<SystemDSN> GetOdbcSources(int packageId, bool recursive) { List<ServiceProviderItem> items = PackageController.GetPackageItemsByType( packageId, ResourceGroups.Os, typeof(SystemDSN), recursive); return items.ConvertAll<SystemDSN>( new Converter<ServiceProviderItem, SystemDSN>(ConvertItemToSystemDSN)); } private static SystemDSN ConvertItemToSystemDSN(ServiceProviderItem item) { return (SystemDSN)item; } public static string[] GetInstalledOdbcDrivers(int packageId) { // load service item int serviceId = PackageController.GetPackageServiceId(packageId, ResourceGroups.Os); OS.OperatingSystem os = GetOS(serviceId); return os.GetInstalledOdbcDrivers(); } public static SystemDSN GetOdbcSource(int itemId) { // load meta item SystemDSN item = (SystemDSN)PackageController.GetPackageItem(itemId); // load service item OS.OperatingSystem os = GetOS(item.ServiceId); SystemDSN dsn = os.GetDSN(item.Name); // add common properties dsn.Id = item.Id; dsn.PackageId = item.PackageId; dsn.ServiceId = item.ServiceId; if(dsn.Driver == "MsAccess" || dsn.Driver == "Excel" || dsn.Driver == "Text") dsn.DatabaseName = FilesController.GetVirtualPackagePath(item.PackageId, dsn.DatabaseName); return dsn; } public static int AddOdbcSource(SystemDSN item) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // check package int packageCheck = SecurityContext.CheckPackage(item.PackageId, DemandPackage.IsActive); if (packageCheck < 0) return packageCheck; // check quota QuotaValueInfo quota = PackageController.GetPackageQuota(item.PackageId, Quotas.OS_ODBC); if (quota.QuotaExhausted) return BusinessErrorCodes.ERROR_OS_DSN_RESOURCE_QUOTA_LIMIT; // check if mail resource is available int serviceId = PackageController.GetPackageServiceId(item.PackageId, ResourceGroups.Os); if (serviceId == 0) return BusinessErrorCodes.ERROR_OS_RESOURCE_UNAVAILABLE; // check package items if (PackageController.GetPackageItemByName(item.PackageId, item.Name, typeof(SystemDSN)) != null) return BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_EXISTS; // place log record TaskManager.StartTask("ODBC_DSN", "ADD", item.Name); try { // check service items OS.OperatingSystem os = GetOS(serviceId); if (os.GetDSN(item.Name) != null) return BusinessErrorCodes.ERROR_OS_DSN_SERVICE_ITEM_EXISTS; string[] dbNameParts = item.DatabaseName.Split('|'); string groupName = null; if (dbNameParts.Length > 1) { item.DatabaseName = dbNameParts[0]; groupName = dbNameParts[1]; } // get database server address item.DatabaseServer = GetDatabaseServerName(groupName, item.PackageId); if (item.Driver == "MsAccess" || item.Driver == "Excel" || item.Driver == "Text") item.DatabaseName = FilesController.GetFullPackagePath(item.PackageId, item.DatabaseName); // add service item os.CreateDSN(item); // save item item.DatabasePassword = CryptoUtils.Encrypt(item.DatabasePassword); item.ServiceId = serviceId; int itemId = PackageController.AddPackageItem(item); TaskManager.ItemId = itemId; return itemId; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } public static int UpdateOdbcSource(SystemDSN item) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // load original meta item SystemDSN origItem = (SystemDSN)PackageController.GetPackageItem(item.Id); if (origItem == null) return BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_NOT_FOUND; // check package int packageCheck = SecurityContext.CheckPackage(origItem.PackageId, DemandPackage.IsActive); if (packageCheck < 0) return packageCheck; // place log record TaskManager.StartTask("ODBC_DSN", "UPDATE", origItem.Name); TaskManager.ItemId = item.Id; try { // get service OS.OperatingSystem os = GetOS(origItem.ServiceId); // password item.Driver = origItem.Driver; item.Name = origItem.Name; if (item.DatabasePassword == "") item.DatabasePassword = CryptoUtils.Decrypt(origItem.DatabasePassword); string[] dbNameParts = item.DatabaseName.Split('|'); string groupName = null; if (dbNameParts.Length > 1) { item.DatabaseName = dbNameParts[0]; groupName = dbNameParts[1]; } // get database server address item.DatabaseServer = GetDatabaseServerName(groupName, item.PackageId); if (item.Driver == "MsAccess" || item.Driver == "Excel" || item.Driver == "Text") item.DatabaseName = FilesController.GetFullPackagePath(origItem.PackageId, item.DatabaseName); // update service item os.UpdateDSN(item); // update meta item if (item.DatabasePassword != "") { item.DatabasePassword = CryptoUtils.Encrypt(item.DatabasePassword); PackageController.UpdatePackageItem(item); } return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } private static string GetDatabaseServerName(string groupName, int packageId) { int sqlServiceId = PackageController.GetPackageServiceId(packageId, groupName); if (sqlServiceId > 0) { StringDictionary sqlSettings = ServerController.GetServiceSettings(sqlServiceId); return sqlSettings["ExternalAddress"]; } return ""; } public static int DeleteOdbcSource(int itemId) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo); if (accountCheck < 0) return accountCheck; // load original meta item SystemDSN origItem = (SystemDSN)PackageController.GetPackageItem(itemId); if (origItem == null) return BusinessErrorCodes.ERROR_OS_DSN_PACKAGE_ITEM_NOT_FOUND; // place log record TaskManager.StartTask("ODBC_DSN", "DELETE", origItem.Name); TaskManager.ItemId = itemId; try { // get service OS.OperatingSystem os = GetOS(origItem.ServiceId); // delete service item os.DeleteDSN(origItem.Name); // delete meta item PackageController.DeletePackageItem(origItem.Id); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } #endregion private static WindowsServer GetServerService(int serverId) { WindowsServer winServer = new WindowsServer(); ServiceProviderProxy.ServerInit(winServer, serverId); return winServer; } #region Terminal Services Sessions public static TerminalSession[] GetTerminalServicesSessions(int serverId) { return GetServerService(serverId).GetTerminalServicesSessions(); } public static int CloseTerminalServicesSession(int serverId, int sessionId) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // load server info ServerInfo server = ServerController.GetServerById(serverId); // place log record TaskManager.StartTask("SERVER", "RESET_TERMINAL_SESSION", sessionId); TaskManager.ItemId = serverId; try { GetServerService(serverId).CloseTerminalServicesSession(sessionId); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } #endregion #region Windows Processes public static WindowsProcess[] GetWindowsProcesses(int serverId) { return GetServerService(serverId).GetWindowsProcesses(); } public static int TerminateWindowsProcess(int serverId, int pid) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // load server info ServerInfo server = ServerController.GetServerById(serverId); // place log record TaskManager.StartTask("SERVER", "TERMINATE_SYSTEM_PROCESS", pid); TaskManager.ItemId = serverId; try { GetServerService(serverId).TerminateWindowsProcess(pid); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } #endregion #region Windows Services public static WindowsService[] GetWindowsServices(int serverId) { return GetServerService(serverId).GetWindowsServices(); } public static int ChangeWindowsServiceStatus(int serverId, string id, WindowsServiceStatus status) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // load server info ServerInfo server = ServerController.GetServerById(serverId); // place log record TaskManager.StartTask("SERVER", "CHANGE_WINDOWS_SERVICE_STATUS", id); TaskManager.ItemId = serverId; TaskManager.WriteParameter("New Status", status); try { GetServerService(serverId).ChangeWindowsServiceStatus(id, status); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } // Check If FSRM Role services were installed public static bool CheckFileServicesInstallation(int serviceId) { OS.OperatingSystem os = GetOS(serviceId); return os.CheckFileServicesInstallation(); } #endregion #region Web Platform Installer public static bool CheckLoadUserProfile(int serverId) { int serviceId = getWebServiceId(serverId); if (serviceId != -1) { return WebServerController.GetWebServer(serviceId).CheckLoadUserProfile(); } return false; } private static int getWebServiceId(int serverId) { DataSet dsServices = ServerController.GetRawServicesByServerId(serverId); int webGroup = -1; if (dsServices.Tables.Count < 1) return -1; foreach (DataRow r in dsServices.Tables[0].Rows) { if (r["GroupName"].ToString() == "Web") { webGroup = (int)r["GroupID"]; break; } } if (webGroup == -1) return -1; foreach (DataRow r in dsServices.Tables[1].Rows) { if ((int)r["GroupID"] == webGroup) { return (int)r["ServiceID"]; } } return -1; } public static void EnableLoadUserProfile(int serverId) { int serviceId = getWebServiceId(serverId); if (serviceId != -1) { WebServerController.GetWebServer(serviceId).EnableLoadUserProfile(); } } public static void InitWPIFeeds(int serverId, string feedUrls) { GetServerService(serverId).InitWPIFeeds(feedUrls); } public static WPITab[] GetWPITabs(int serverId) { return GetServerService(serverId).GetWPITabs(); } public static WPIKeyword[] GetWPIKeywords(int serverId) { return GetServerService(serverId).GetWPIKeywords(); } public static WPIProduct[] GetWPIProducts(int serverId, string tabId, string keywordId) { return GetServerService(serverId).GetWPIProducts(tabId, keywordId); } public static WPIProduct[] GetWPIProductsFiltered(int serverId, string keywordId) { return GetServerService(serverId).GetWPIProductsFiltered(keywordId); } public static WPIProduct GetWPIProductById(int serverId, string productdId) { return GetServerService(serverId).GetWPIProductById(productdId); } public static WPIProduct[] GetWPIProductsWithDependencies(int serverId, string[] products) { return GetServerService(serverId).GetWPIProductsWithDependencies(products); } public static void InstallWPIProducts(int serverId, string[] products) { GetServerService(serverId).InstallWPIProducts(products); } public static void CancelInstallWPIProducts(int serverId) { GetServerService(serverId).CancelInstallWPIProducts(); } public static string GetWPIStatus(int serverId) { return GetServerService(serverId).GetWPIStatus(); } public static string WpiGetLogFileDirectory(int serverId) { return GetServerService(serverId).WpiGetLogFileDirectory(); } public static SettingPair[] WpiGetLogsInDirectory(int serverId, string Path) { return GetServerService(serverId).WpiGetLogsInDirectory(Path); } #endregion #region Event Viewer public static string[] GetLogNames(int serverId) { return GetServerService(serverId).GetLogNames(); } public static SystemLogEntry[] GetLogEntries(int serverId, string logName) { return GetServerService(serverId).GetLogEntries(logName); } public static SystemLogEntriesPaged GetLogEntriesPaged(int serverId, string logName, int startRow, int maximumRows) { return GetServerService(serverId).GetLogEntriesPaged(logName, startRow, maximumRows); } public static int ClearLog(int serverId, string logName) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; TaskManager.StartTask("SERVER", "CLEAR_EVENT_LOG", logName); TaskManager.ItemId = serverId; try { GetServerService(serverId).ClearLog(logName); } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } return 0; } #endregion #region Server Reboot public static int RebootSystem(int serverId) { // check account int accountCheck = SecurityContext.CheckAccount(DemandAccount.NotDemo | DemandAccount.IsAdmin | DemandAccount.IsActive); if (accountCheck < 0) return accountCheck; // load server info ServerInfo server = ServerController.GetServerById(serverId); // place log record TaskManager.StartTask("SERVER", "REBOOT"); TaskManager.ItemId = serverId; try { GetServerService(serverId).RebootSystem(); return 0; } catch (Exception ex) { throw TaskManager.WriteError(ex); } finally { TaskManager.CompleteTask(); } } #endregion #region IImportController Members public List<string> GetImportableItems(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group) { List<string> items = new List<string>(); // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) return items; OS.OperatingSystem os = GetOS(serviceId); if (itemType == typeof(SystemDSN)) items.AddRange(os.GetDSNNames()); return items; } public void ImportItem(int packageId, int itemTypeId, Type itemType, ResourceGroupInfo group, string itemName) { // get service id int serviceId = PackageController.GetPackageServiceId(packageId, group.GroupName); if (serviceId == 0) return; if (itemType == typeof(SystemDSN)) { // save DSN info SystemDSN dsn = new SystemDSN(); dsn.Name = itemName; dsn.ServiceId = serviceId; dsn.PackageId = packageId; PackageController.AddPackageItem(dsn); } } #endregion #region IBackupController Members public int BackupItem(string tempFolder, System.Xml.XmlWriter writer, ServiceProviderItem item, ResourceGroupInfo group) { if (item is HomeFolder) { // backup home folder files string backupName = String.Format("SpaceFiles_{0}_{1}.zip", item.Id, DateTime.Now.Ticks); // get the list of remote files List<SystemFile> files = FilesController.GetFiles(item.PackageId, "\\", true); string[] zipFiles = new string[files.Count]; for(int i = 0; i < zipFiles.Length; i++) zipFiles[i] = files[i].Name; // zip remote files FilesController.ZipFiles(item.PackageId, zipFiles, backupName); // download zipped file string localBackupPath = Path.Combine(tempFolder, backupName); byte[] buffer = null; FileStream stream = new FileStream(localBackupPath, FileMode.Create, FileAccess.Write); int offset = 0; long length = 0; do { // read remote content buffer = FilesController.GetFileBinaryChunk(item.PackageId, backupName, offset, FILE_BUFFER_LENGTH); // write remote content stream.Write(buffer, 0, buffer.Length); length += buffer.Length; offset += FILE_BUFFER_LENGTH; } while (buffer.Length == FILE_BUFFER_LENGTH); stream.Close(); // delete zipped file if (FilesController.FileExists(item.PackageId, backupName)) FilesController.DeleteFiles(item.PackageId, new string[] { backupName }); // add file pointer BackupController.WriteFileElement(writer, "SpaceFiles", backupName, length); // store meta item XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder)); serializer.Serialize(writer, item); } else if (item is SystemDSN) { // backup ODBC DSN OS.OperatingSystem os = GetOS(item.ServiceId); // read DSN info SystemDSN itemDsn = item as SystemDSN; SystemDSN dsn = os.GetDSN(item.Name); dsn.DatabasePassword = itemDsn.DatabasePassword; XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN)); serializer.Serialize(writer, dsn); } return 0; } public int RestoreItem(string tempFolder, System.Xml.XmlNode itemNode, int itemId, Type itemType, string itemName, int packageId, int serviceId, ResourceGroupInfo group) { if (itemType == typeof(HomeFolder)) { OS.OperatingSystem os = GetOS(serviceId); // extract meta item XmlSerializer serializer = new XmlSerializer(typeof(HomeFolder)); HomeFolder homeFolder = (HomeFolder)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("HomeFolder"))); // create home folder if required if (!os.DirectoryExists(homeFolder.Name)) { os.CreatePackageFolder(homeFolder.Name); } // copy database backup to remote server XmlNode fileNode = itemNode.SelectSingleNode("File[@name='SpaceFiles']"); string backupFileName = fileNode.Attributes["path"].Value; long backupFileLength = Int64.Parse(fileNode.Attributes["size"].Value); string localBackupFilePath = Path.Combine(tempFolder, backupFileName); if (new FileInfo(localBackupFilePath).Length != backupFileLength) return -3; FileStream stream = new FileStream(localBackupFilePath, FileMode.Open, FileAccess.Read); byte[] buffer = new byte[FILE_BUFFER_LENGTH]; int readBytes = 0; long length = 0; string remoteBackupPath = Path.Combine(homeFolder.Name, backupFileName); do { // read package file readBytes = stream.Read(buffer, 0, FILE_BUFFER_LENGTH); length += readBytes; if (readBytes < FILE_BUFFER_LENGTH) // resize buffer Array.Resize<byte>(ref buffer, readBytes); // write remote backup file os.AppendFileBinaryContent(remoteBackupPath, buffer); } while (readBytes == FILE_BUFFER_LENGTH); stream.Close(); // unzip files os.UnzipFiles(remoteBackupPath, homeFolder.Name); // delete archive if (os.FileExists(remoteBackupPath)) os.DeleteFile(remoteBackupPath); // add meta-item if required if (PackageController.GetPackageItemByName(packageId, itemName, typeof(HomeFolder)) == null) { homeFolder.PackageId = packageId; homeFolder.ServiceId = serviceId; PackageController.AddPackageItem(homeFolder); } } else if (itemType == typeof(SystemDSN)) { OS.OperatingSystem os = GetOS(serviceId); // extract meta item XmlSerializer serializer = new XmlSerializer(typeof(SystemDSN)); SystemDSN dsn = (SystemDSN)serializer.Deserialize( new XmlNodeReader(itemNode.SelectSingleNode("SystemDSN"))); // create DSN if required if (os.GetDSN(itemName) == null) { dsn.DatabasePassword = CryptoUtils.Decrypt(dsn.DatabasePassword); os.CreateDSN(dsn); // restore password dsn.DatabasePassword = CryptoUtils.Encrypt(dsn.DatabasePassword); } // add meta-item if required if (PackageController.GetPackageItemByName(packageId, itemName, typeof(SystemDSN)) == null) { dsn.PackageId = packageId; dsn.ServiceId = serviceId; PackageController.AddPackageItem(dsn); } } return 0; } #endregion } }
// // Copyright 2011-2013, Xamarin 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.IO; using System.Threading; using System.Threading.Tasks; using Android.App; using Android.Content; using Android.Database; using Android.OS; using Android.Provider; using Environment = Android.OS.Environment; using Path = System.IO.Path; using Uri = Android.Net.Uri; using Plugin.Media.Abstractions; using Android.Net; namespace Plugin.Media { /// <summary> /// Picker /// </summary> [Activity(ConfigurationChanges=Android.Content.PM.ConfigChanges.Orientation | Android.Content.PM.ConfigChanges.ScreenSize)] [Android.Runtime.Preserve(AllMembers = true)] public class MediaPickerActivity : Activity, Android.Media.MediaScannerConnection.IOnScanCompletedListener { internal const string ExtraPath = "path"; internal const string ExtraLocation = "location"; internal const string ExtraType = "type"; internal const string ExtraId = "id"; internal const string ExtraAction = "action"; internal const string ExtraTasked = "tasked"; internal const string ExtraSaveToAlbum = "album_save"; internal const string ExtraFront = "android.intent.extras.CAMERA_FACING"; internal static event EventHandler<MediaPickedEventArgs> MediaPicked; private int id; private int front; private string title; private string description; private string type; /// <summary> /// The user's destination path. /// </summary> private Uri path; private bool isPhoto; private bool saveToAlbum; private string action; private int seconds; private VideoQuality quality; private bool tasked; /// <summary> /// OnSaved /// </summary> /// <param name="outState"></param> protected override void OnSaveInstanceState(Bundle outState) { outState.PutBoolean("ran", true); outState.PutString(MediaStore.MediaColumns.Title, this.title); outState.PutString(MediaStore.Images.ImageColumns.Description, this.description); outState.PutInt(ExtraId, this.id); outState.PutString(ExtraType, this.type); outState.PutString(ExtraAction, this.action); outState.PutInt(MediaStore.ExtraDurationLimit, this.seconds); outState.PutInt(MediaStore.ExtraVideoQuality, (int)this.quality); outState.PutBoolean(ExtraSaveToAlbum, saveToAlbum); outState.PutBoolean(ExtraTasked, this.tasked); outState.PutInt(ExtraFront, this.front); if (this.path != null) outState.PutString(ExtraPath, this.path.Path); base.OnSaveInstanceState(outState); } /// <summary> /// OnCreate /// </summary> /// <param name="savedInstanceState"></param> protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Bundle b = (savedInstanceState ?? Intent.Extras); bool ran = b.GetBoolean("ran", defaultValue: false); this.title = b.GetString(MediaStore.MediaColumns.Title); this.description = b.GetString(MediaStore.Images.ImageColumns.Description); this.tasked = b.GetBoolean(ExtraTasked); this.id = b.GetInt(ExtraId, 0); this.type = b.GetString(ExtraType); this.front = b.GetInt(ExtraFront); if (this.type == "image/*") this.isPhoto = true; this.action = b.GetString(ExtraAction); Intent pickIntent = null; try { pickIntent = new Intent(this.action); if (this.action == Intent.ActionPick) pickIntent.SetType(type); else { if (!this.isPhoto) { this.seconds = b.GetInt(MediaStore.ExtraDurationLimit, 0); if (this.seconds != 0) pickIntent.PutExtra(MediaStore.ExtraDurationLimit, seconds); } this.saveToAlbum = b.GetBoolean(ExtraSaveToAlbum); pickIntent.PutExtra(ExtraSaveToAlbum, this.saveToAlbum); this.quality = (VideoQuality)b.GetInt(MediaStore.ExtraVideoQuality, (int)VideoQuality.High); pickIntent.PutExtra(MediaStore.ExtraVideoQuality, GetVideoQuality(this.quality)); if (front != 0) pickIntent.PutExtra(ExtraFront, (int)Android.Hardware.CameraFacing.Front); if (!ran) { this.path = GetOutputMediaFile(this, b.GetString(ExtraPath), this.title, this.isPhoto, this.saveToAlbum); Touch(); pickIntent.PutExtra(MediaStore.ExtraOutput, this.path); } else this.path = Uri.Parse(b.GetString(ExtraPath)); } if (!ran) StartActivityForResult(pickIntent, this.id); } catch (Exception ex) { OnMediaPicked(new MediaPickedEventArgs(this.id, ex)); } finally { if (pickIntent != null) pickIntent.Dispose(); } } private void Touch() { if (this.path.Scheme != "file") return; File.Create(GetLocalPath(this.path)).Close(); } internal static Task<MediaPickedEventArgs> GetMediaFileAsync(Context context, int requestCode, string action, bool isPhoto, ref Uri path, Uri data, bool saveToAlbum) { Task<Tuple<string, bool>> pathFuture; string originalPath = null; if (action != Intent.ActionPick) { originalPath = path.Path; // Not all camera apps respect EXTRA_OUTPUT, some will instead // return a content or file uri from data. if (data != null && data.Path != originalPath) { originalPath = data.ToString(); string currentPath = path.Path; pathFuture = TryMoveFileAsync(context, data, path, isPhoto, saveToAlbum).ContinueWith(t => new Tuple<string, bool>(t.Result ? currentPath : null, false)); } else { pathFuture = TaskFromResult(new Tuple<string, bool>(path.Path, false)); } } else if (data != null) { originalPath = data.ToString(); path = data; pathFuture = GetFileForUriAsync(context, path, isPhoto, saveToAlbum); } else pathFuture = TaskFromResult<Tuple<string, bool>>(null); return pathFuture.ContinueWith(t => { string resultPath = t.Result.Item1; if (resultPath != null && File.Exists(t.Result.Item1)) { string aPath = null; if (saveToAlbum) { aPath = resultPath; try { var f = new Java.IO.File(resultPath); //MediaStore.Images.Media.InsertImage(context.ContentResolver, // f.AbsolutePath, f.Name, null); try { Android.Media.MediaScannerConnection.ScanFile(context, new [] { f.AbsolutePath }, null, context as MediaPickerActivity); ContentValues values = new ContentValues(); values.Put(MediaStore.Images.Media.InterfaceConsts.Title, Path.GetFileNameWithoutExtension(f.AbsolutePath)); values.Put(MediaStore.Images.Media.InterfaceConsts.Description, string.Empty); values.Put(MediaStore.Images.Media.InterfaceConsts.DateTaken, Java.Lang.JavaSystem.CurrentTimeMillis()); values.Put(MediaStore.Images.ImageColumns.BucketId, f.ToString().ToLowerInvariant().GetHashCode()); values.Put(MediaStore.Images.ImageColumns.BucketDisplayName, f.Name.ToLowerInvariant()); values.Put("_data", f.AbsolutePath); var cr = context.ContentResolver; cr.Insert(MediaStore.Images.Media.ExternalContentUri, values); } catch (Exception ex1) { Console.WriteLine("Unable to save to scan file: " + ex1); } var contentUri = Uri.FromFile(f); var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile, contentUri); context.SendBroadcast(mediaScanIntent); } catch (Exception ex2) { Console.WriteLine("Unable to save to gallery: " + ex2); } } var mf = new MediaFile(resultPath, () => { return File.OpenRead(resultPath); }, deletePathOnDispose: t.Result.Item2, dispose: (dis) => { if (t.Result.Item2) { try { File.Delete(t.Result.Item1); // We don't really care if this explodes for a normal IO reason. } catch (UnauthorizedAccessException) { } catch (DirectoryNotFoundException) { } catch (IOException) { } } }, albumPath: aPath); return new MediaPickedEventArgs(requestCode, false, mf); } else return new MediaPickedEventArgs(requestCode, new MediaFileNotFoundException(originalPath)); }); } /// <summary> /// OnActivity Result /// </summary> /// <param name="requestCode"></param> /// <param name="resultCode"></param> /// <param name="data"></param> protected override async void OnActivityResult(int requestCode, Result resultCode, Intent data) { base.OnActivityResult(requestCode, resultCode, data); if (this.tasked) { Task<MediaPickedEventArgs> future; if (resultCode == Result.Canceled) { future = TaskFromResult(new MediaPickedEventArgs(requestCode, isCanceled: true)); Finish(); future.ContinueWith(t => OnMediaPicked(t.Result)); } else { if ((int)Build.VERSION.SdkInt >= 22) { var e = await GetMediaFileAsync(this, requestCode, this.action, this.isPhoto, ref this.path, (data != null) ? data.Data : null, saveToAlbum); OnMediaPicked(e); Finish(); } else { future = GetMediaFileAsync(this, requestCode, this.action, this.isPhoto, ref this.path, (data != null) ? data.Data : null, saveToAlbum); Finish(); future.ContinueWith(t => OnMediaPicked(t.Result)); } } } else { if (resultCode == Result.Canceled) SetResult(Result.Canceled); else { Intent resultData = new Intent(); resultData.PutExtra("MediaFile", (data != null) ? data.Data : null); resultData.PutExtra("path", this.path); resultData.PutExtra("isPhoto", this.isPhoto); resultData.PutExtra("action", this.action); resultData.PutExtra(ExtraSaveToAlbum, this.saveToAlbum); SetResult(Result.Ok, resultData); } Finish(); } } private static Task<bool> TryMoveFileAsync(Context context, Uri url, Uri path, bool isPhoto, bool saveToAlbum) { string moveTo = GetLocalPath(path); return GetFileForUriAsync(context, url, isPhoto, saveToAlbum).ContinueWith(t => { if (t.Result.Item1 == null) return false; File.Delete(moveTo); File.Move(t.Result.Item1, moveTo); if (url.Scheme == "content") context.ContentResolver.Delete(url, null, null); return true; }, TaskScheduler.Default); } private static int GetVideoQuality(VideoQuality videoQuality) { switch (videoQuality) { case VideoQuality.Medium: case VideoQuality.High: return 1; default: return 0; } } private static string GetUniquePath(string folder, string name, bool isPhoto) { string ext = Path.GetExtension(name); if (ext == String.Empty) ext = ((isPhoto) ? ".jpg" : ".mp4"); name = Path.GetFileNameWithoutExtension(name); string nname = name + ext; int i = 1; while (File.Exists(Path.Combine(folder, nname))) nname = name + "_" + (i++) + ext; return Path.Combine(folder, nname); } private static Uri GetOutputMediaFile(Context context, string subdir, string name, bool isPhoto, bool saveToAlbum) { subdir = subdir ?? String.Empty; if (String.IsNullOrWhiteSpace(name)) { string timestamp = DateTime.Now.ToString("yyyyMMdd_HHmmss"); if (isPhoto) name = "IMG_" + timestamp + ".jpg"; else name = "VID_" + timestamp + ".mp4"; } string mediaType = (isPhoto) ? Environment.DirectoryPictures : Environment.DirectoryMovies; var directory = saveToAlbum ? Environment.GetExternalStoragePublicDirectory(mediaType) : context.GetExternalFilesDir(mediaType); using (Java.IO.File mediaStorageDir = new Java.IO.File(directory, subdir)) { if (!mediaStorageDir.Exists()) { if (!mediaStorageDir.Mkdirs()) throw new IOException("Couldn't create directory, have you added the WRITE_EXTERNAL_STORAGE permission?"); // Ensure this media doesn't show up in gallery apps using (Java.IO.File nomedia = new Java.IO.File(mediaStorageDir, ".nomedia")) nomedia.CreateNewFile(); } return Uri.FromFile(new Java.IO.File(GetUniquePath(mediaStorageDir.Path, name, isPhoto))); } } internal static Task<Tuple<string, bool>> GetFileForUriAsync(Context context, Uri uri, bool isPhoto, bool saveToAlbum) { var tcs = new TaskCompletionSource<Tuple<string, bool>>(); if (uri.Scheme == "file") tcs.SetResult(new Tuple<string, bool>(new System.Uri(uri.ToString()).LocalPath, false)); else if (uri.Scheme == "content") { Task.Factory.StartNew(() => { ICursor cursor = null; try { string[] proj = null; if ((int)Build.VERSION.SdkInt >= 22) proj = new[] { MediaStore.MediaColumns.Data }; cursor = context.ContentResolver.Query(uri, proj, null, null, null); if (cursor == null || !cursor.MoveToNext()) tcs.SetResult(new Tuple<string, bool>(null, false)); else { int column = cursor.GetColumnIndex(MediaStore.MediaColumns.Data); string contentPath = null; if (column != -1) contentPath = cursor.GetString(column); // If they don't follow the "rules", try to copy the file locally if (contentPath == null || !contentPath.StartsWith("file")) { Uri outputPath = GetOutputMediaFile(context, "temp", null, isPhoto, saveToAlbum); try { using (Stream input = context.ContentResolver.OpenInputStream(uri)) using (Stream output = File.Create(outputPath.Path)) input.CopyTo(output); contentPath = outputPath.Path; } catch (Java.IO.FileNotFoundException) { // If there's no data associated with the uri, we don't know // how to open this. contentPath will be null which will trigger // MediaFileNotFoundException. } } tcs.SetResult(new Tuple<string, bool>(contentPath, false)); } } finally { if (cursor != null) { cursor.Close(); cursor.Dispose(); } } }, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); } else tcs.SetResult(new Tuple<string, bool>(null, false)); return tcs.Task; } private static string GetLocalPath(Uri uri) { return new System.Uri(uri.ToString()).LocalPath; } private static Task<T> TaskFromResult<T>(T result) { var tcs = new TaskCompletionSource<T>(); tcs.SetResult(result); return tcs.Task; } private static void OnMediaPicked(MediaPickedEventArgs e) { var picked = MediaPicked; if (picked != null) picked(null, e); } public void OnScanCompleted(string path, Uri uri) { Console.WriteLine("scan complete: " + path); } } internal class MediaPickedEventArgs : EventArgs { public MediaPickedEventArgs(int id, Exception error) { if (error == null) throw new ArgumentNullException("error"); RequestId = id; Error = error; } public MediaPickedEventArgs(int id, bool isCanceled, MediaFile media = null) { RequestId = id; IsCanceled = isCanceled; if (!IsCanceled && media == null) throw new ArgumentNullException("media"); Media = media; } public int RequestId { get; private set; } public bool IsCanceled { get; private set; } public Exception Error { get; private set; } public MediaFile Media { get; private set; } public Task<MediaFile> ToTask() { var tcs = new TaskCompletionSource<MediaFile>(); if (IsCanceled) tcs.SetResult(null); else if (Error != null) tcs.SetResult(null); else tcs.SetResult(Media); return tcs.Task; } } }
using System; using System.Collections.Generic; using System.IO; using System.Threading; using CodePlex.TfsLibrary.RepositoryWebSvc; using SvnBridge.Handlers; using SvnBridge.Interfaces; using SvnBridge.Protocol; using SvnBridge.SourceControl; using SvnBridge.Utility; namespace SvnBridge.Infrastructure { internal class UpdateReportService { private readonly RequestHandlerBase handler; private readonly TFSSourceControlProvider sourceControlProvider; public UpdateReportService(RequestHandlerBase handler, TFSSourceControlProvider sourceControlProvider) { this.handler = handler; this.sourceControlProvider = sourceControlProvider; } public void ProcessUpdateReportForFile(UpdateReportData updateReportRequest, ItemMetaData item, StreamWriter output, bool parentFolderWasDeleted) { if (item is DeleteMetaData) { if (!parentFolderWasDeleted) { output.Write("<S:delete-entry name=\"" + Helper.EncodeB(GetFileName(item.Name)) + "\"/>\n"); } } else { bool existingFile = false; string srcPath = GetSrcPath(updateReportRequest); int clientRevisionForItem = GetClientRevisionFor(updateReportRequest.Entries, StripBasePath(item, srcPath)); if (ItemExistsAtTheClient(item, updateReportRequest, srcPath, clientRevisionForItem)) { existingFile = true; } //another item with the same name already exists, need to remove it. if (!parentFolderWasDeleted && ShouldDeleteItemBeforeSendingToClient(item, updateReportRequest, srcPath, clientRevisionForItem, existingFile)) { output.Write("<S:delete-entry name=\"" + Helper.EncodeB(GetFileName(item.Name)) + "\"/>\n"); } if (existingFile) { output.Write("<S:open-file name=\"" + Helper.EncodeB(GetFileName(item.Name)) + "\" rev=\"" + clientRevisionForItem + "\">\n"); } else { output.Write("<S:add-file name=\"" + Helper.EncodeB(GetFileName(item.Name)) + "\">\n"); } string localPath = handler.GetLocalPath("/!svn/ver/" + item.Revision + "/" + Helper.Encode(item.Name, true)); output.Write("<D:checked-in><D:href>" + localPath + "</D:href></D:checked-in>\n"); output.Write("<S:set-prop name=\"svn:entry:committed-rev\">" + item.Revision + "</S:set-prop>\n"); output.Write("<S:set-prop name=\"svn:entry:committed-date\">" + Helper.FormatDate(item.LastModifiedDate) + "</S:set-prop>\n"); output.Write("<S:set-prop name=\"svn:entry:last-author\">" + item.Author + "</S:set-prop>\n"); if(sourceControlProvider == null) output.Write("<S:set-prop name=\"svn:entry:uuid\">" + new Guid() + "</S:set-prop>\n"); else output.Write("<S:set-prop name=\"svn:entry:uuid\">" + sourceControlProvider.GetRepositoryUuid() + "</S:set-prop>\n"); foreach (KeyValuePair<string, string> property in item.Properties) { output.Write("<S:set-prop name=\"" + property.Key + "\">" + property.Value + "</S:set-prop>\n"); } while (item.DataLoaded == false) // <== Uha Thread.Sleep(100); output.Write("<S:txdelta>"); output.Write(item.Base64DiffData); output.Write("\n</S:txdelta>"); output.Write("<S:prop><V:md5-checksum>" + item.Md5Hash + "</V:md5-checksum></S:prop>\n"); // Release data memory item.DataLoaded = false; item.Base64DiffData = null; if (existingFile) { output.Write("</S:open-file>\n"); } else { output.Write("</S:add-file>\n"); } } } private bool ItemExistsAtTheClient(ItemMetaData item, UpdateReportData updateReportRequest, string srcPath, int clientRevisionForItem) { if (sourceControlProvider != null) { return updateReportRequest.IsCheckOut == false && IsMissing(updateReportRequest, srcPath, item.Name) == false && // we need to check both name and id to ensure that the item was not renamed sourceControlProvider.ItemExists(item.Name, clientRevisionForItem) && sourceControlProvider.ItemExists(item.Id, clientRevisionForItem); } else { return false; } } private string GetSrcPath(UpdateReportData updateReportRequest) { string url = handler.GetLocalPathFromUrl(updateReportRequest.SrcPath); if (updateReportRequest.UpdateTarget != null) return url + "/" + updateReportRequest.UpdateTarget; return url; } public void ProcessUpdateReportForDirectory(UpdateReportData updateReportRequest, FolderMetaData folder, StreamWriter output, bool rootFolder, bool parentFolderWasDeleted) { if (folder is DeleteFolderMetaData) { if (!parentFolderWasDeleted) { output.Write("<S:delete-entry name=\"" + Helper.EncodeB(GetFileName(folder.Name)) + "\"/>\n"); } } else { bool existingFolder = false; bool folderWasDeleted = parentFolderWasDeleted; if (rootFolder) { output.Write("<S:open-directory rev=\"" + updateReportRequest.Entries[0].Rev + "\">\n"); } else { string srcPath = GetSrcPath(updateReportRequest); int clientRevisionForItem = GetClientRevisionFor(updateReportRequest.Entries, StripBasePath(folder, srcPath)); if (ItemExistsAtTheClient(folder, updateReportRequest, srcPath, clientRevisionForItem)) { existingFolder = true; } //another item with the same name already exists, need to remove it. if (!parentFolderWasDeleted && ShouldDeleteItemBeforeSendingToClient(folder, updateReportRequest, srcPath, clientRevisionForItem, existingFolder)) { output.Write("<S:delete-entry name=\"" + Helper.EncodeB(GetFileName(folder.Name)) + "\"/>\n"); folderWasDeleted = true; } if (existingFolder) { output.Write("<S:open-directory name=\"" + Helper.EncodeB(GetFileName(folder.Name)) + "\" rev=\"" + updateReportRequest.Entries[0].Rev + "\">\n"); } else { output.Write("<S:add-directory name=\"" + Helper.EncodeB(GetFileName(folder.Name)) + "\" bc-url=\"" + handler.GetLocalPath("/!svn/bc/" + folder.Revision + "/" + Helper.Encode(folder.Name, true)) + "\">\n"); } } if (!rootFolder || updateReportRequest.UpdateTarget == null) { string svnVer = handler.GetLocalPath("/!svn/ver/" + folder.Revision + "/" + Helper.Encode(folder.Name, true)); output.Write("<D:checked-in><D:href>" + svnVer + "</D:href></D:checked-in>\n"); output.Write("<S:set-prop name=\"svn:entry:committed-rev\">" + folder.Revision + "</S:set-prop>\n"); output.Write("<S:set-prop name=\"svn:entry:committed-date\">" + Helper.FormatDate(folder.LastModifiedDate) + "</S:set-prop>\n"); output.Write("<S:set-prop name=\"svn:entry:last-author\">" + folder.Author + "</S:set-prop>\n"); if(sourceControlProvider == null) output.Write("<S:set-prop name=\"svn:entry:uuid\">" + new Guid() + "</S:set-prop>\n"); else output.Write("<S:set-prop name=\"svn:entry:uuid\">" + sourceControlProvider.GetRepositoryUuid() + "</S:set-prop>\n"); foreach (KeyValuePair<string, string> property in folder.Properties) { output.Write("<S:set-prop name=\"" + property.Key + "\">" + property.Value + "</S:set-prop>\n"); } } for (int i = 0; i < folder.Items.Count; i++) { ItemMetaData item = folder.Items[i]; if (item.ItemType == ItemType.Folder) { ProcessUpdateReportForDirectory(updateReportRequest, (FolderMetaData)item, output, false, folderWasDeleted); } else { ProcessUpdateReportForFile(updateReportRequest, item, output, folderWasDeleted); } } output.Write("<S:prop></S:prop>\n"); if (rootFolder || existingFolder) { output.Write("</S:open-directory>\n"); } else { output.Write("</S:add-directory>\n"); } } } private bool ShouldDeleteItemBeforeSendingToClient(ItemMetaData folder, UpdateReportData updateReportRequest, string srcPath, int clientRevisionForItem, bool existingFolder) { if (sourceControlProvider != null) { return existingFolder == false && updateReportRequest.IsCheckOut == false && IsMissing(updateReportRequest, srcPath, folder.Name) == false && sourceControlProvider.ItemExists(folder.Name, clientRevisionForItem); } else { return existingFolder == false && updateReportRequest.IsCheckOut == false && IsMissing(updateReportRequest, srcPath, folder.Name) == false; } } private static string GetFileName(string path) { int slashIndex = path.LastIndexOfAny(new char[] { '/', '\\' }); return path.Substring(slashIndex + 1); } private string StripBasePath(ItemMetaData item, string basePath) { string name = item.Name; if (name.StartsWith("/")) name = name.Substring(1); if (basePath.StartsWith("/")) basePath = basePath.Substring(1); basePath = basePath + "/"; if (name.StartsWith(basePath)) { name = name.Substring(basePath.Length); if (name.StartsWith(@"/")) name = name.Substring(1); } return name; } private int GetClientRevisionFor(List<EntryData> entries, string name) { EntryData bestMatch = entries[0]; foreach (EntryData entry in entries) { if (entry.path == name)// found a best match { bestMatch = entry; break; } if (entry.path == null || name.StartsWith(entry.path, StringComparison.InvariantCultureIgnoreCase) == false) continue; // if the current entry is longer than the previous best match, than this // is a better match, because it is more deeply nested, so likely // to be a better parent if (bestMatch.path == null || bestMatch.path.Length < entry.path.Length) bestMatch = entry; } return int.Parse(bestMatch.Rev); } private bool IsMissing(UpdateReportData data, string localPath, string name) { if (data.Missing == null || data.Missing.Count == 0) return false; string path = localPath.Substring(1); if (path.EndsWith("/") == false) path += "/"; if (name.StartsWith(path)) name = name.Substring(path.Length); if (data.Missing.Contains(name)) return true; foreach (string missing in data.Missing) { if (name.StartsWith(missing))// the missing is the parent of this item return true; } return false; } } }
//------------------------------------------------------------------------------ // <copyright file="DataGridViewCheckBoxCell.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Windows.Forms { using System; using System.Diagnostics; using System.Drawing; using System.ComponentModel; using System.Windows.Forms.VisualStyles; using System.Runtime.InteropServices; using System.Security; using System.Security.Permissions; using System.Windows.Forms.Internal; using System.Windows.Forms.ButtonInternal; using System.Diagnostics.CodeAnalysis; using System.Globalization; /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell"]/*' /> /// <devdoc> /// <para>Identifies a checkbox cell in the DataGridView.</para> /// </devdoc> public class DataGridViewCheckBoxCell : DataGridViewCell, IDataGridViewEditingCell { private static readonly DataGridViewContentAlignment anyLeft = DataGridViewContentAlignment.TopLeft | DataGridViewContentAlignment.MiddleLeft | DataGridViewContentAlignment.BottomLeft; private static readonly DataGridViewContentAlignment anyRight = DataGridViewContentAlignment.TopRight | DataGridViewContentAlignment.MiddleRight | DataGridViewContentAlignment.BottomRight; private static readonly DataGridViewContentAlignment anyCenter = DataGridViewContentAlignment.TopCenter | DataGridViewContentAlignment.MiddleCenter | DataGridViewContentAlignment.BottomCenter; private static readonly DataGridViewContentAlignment anyBottom = DataGridViewContentAlignment.BottomRight | DataGridViewContentAlignment.BottomCenter | DataGridViewContentAlignment.BottomLeft; private static readonly DataGridViewContentAlignment anyMiddle = DataGridViewContentAlignment.MiddleRight | DataGridViewContentAlignment.MiddleCenter | DataGridViewContentAlignment.MiddleLeft; private static readonly VisualStyleElement CheckBoxElement = VisualStyleElement.Button.CheckBox.UncheckedNormal; private static readonly int PropButtonCellState = PropertyStore.CreateKey(); private static readonly int PropTrueValue = PropertyStore.CreateKey(); private static readonly int PropFalseValue = PropertyStore.CreateKey(); private static readonly int PropFlatStyle = PropertyStore.CreateKey(); private static readonly int PropIndeterminateValue = PropertyStore.CreateKey(); private static Bitmap checkImage = null; private const byte DATAGRIDVIEWCHECKBOXCELL_threeState = 0x01; private const byte DATAGRIDVIEWCHECKBOXCELL_valueChanged = 0x02; private const byte DATAGRIDVIEWCHECKBOXCELL_checked = 0x10; private const byte DATAGRIDVIEWCHECKBOXCELL_indeterminate = 0x20; private const byte DATAGRIDVIEWCHECKBOXCELL_margin = 2; // horizontal and vertical margins for preferred sizes private byte flags; // see DATAGRIDVIEWCHECKBOXCELL_ consts above private static bool mouseInContentBounds = false; private static Type defaultCheckStateType = typeof(System.Windows.Forms.CheckState); private static Type defaultBooleanType = typeof(System.Boolean); private static Type cellType = typeof(DataGridViewCheckBoxCell); /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.DataGridViewCheckBoxCell"]/*' /> public DataGridViewCheckBoxCell() : this(false /*threeState*/) { } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.DataGridViewCheckBoxCell2"]/*' /> public DataGridViewCheckBoxCell(bool threeState) { if (threeState) { this.flags = DATAGRIDVIEWCHECKBOXCELL_threeState; } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.IDataGridViewEditingCell.EditingCellFormattedValue"]/*' /> public virtual object EditingCellFormattedValue { get { return GetEditingCellFormattedValue(DataGridViewDataErrorContexts.Formatting); } set { if (this.FormattedValueType == null) { throw new ArgumentException(SR.GetString(SR.DataGridViewCell_FormattedValueTypeNull)); } if (value == null || !this.FormattedValueType.IsAssignableFrom(value.GetType())) { // Assigned formatted value may not be of the good type, in cases where the app // is feeding wrong values to the cell in virtual / databound mode. throw new ArgumentException(SR.GetString(SR.DataGridViewCheckBoxCell_InvalidValueType)); } if (value is System.Windows.Forms.CheckState) { if (((System.Windows.Forms.CheckState)value) == System.Windows.Forms.CheckState.Checked) { this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_checked; this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); } else if (((System.Windows.Forms.CheckState)value) == System.Windows.Forms.CheckState.Indeterminate) { this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_indeterminate; this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); } else { this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); } } else if (value is System.Boolean) { if ((bool)value) { this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_checked; } else { this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_checked); } this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_indeterminate); } else { throw new ArgumentException(SR.GetString(SR.DataGridViewCheckBoxCell_InvalidValueType)); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.IDataGridViewEditingCell.EditingCellValueChanged"]/*' /> public virtual bool EditingCellValueChanged { get { return ((this.flags & DATAGRIDVIEWCHECKBOXCELL_valueChanged) != 0x00); } set { if (value) { this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_valueChanged; } else { this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_valueChanged); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.IDataGridViewEditingCell.GetEditingCellFormattedValue"]/*' /> public virtual object GetEditingCellFormattedValue(DataGridViewDataErrorContexts context) { if (this.FormattedValueType == null) { throw new InvalidOperationException(SR.GetString(SR.DataGridViewCell_FormattedValueTypeNull)); } if (this.FormattedValueType.IsAssignableFrom(defaultCheckStateType)) { if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00) { if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { return SR.GetString(SR.DataGridViewCheckBoxCell_ClipboardChecked); } return System.Windows.Forms.CheckState.Checked; } else if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_indeterminate) != 0x00) { if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { return SR.GetString(SR.DataGridViewCheckBoxCell_ClipboardIndeterminate); } return System.Windows.Forms.CheckState.Indeterminate; } else { if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { return SR.GetString(SR.DataGridViewCheckBoxCell_ClipboardUnchecked); } return System.Windows.Forms.CheckState.Unchecked; } } else if (this.FormattedValueType.IsAssignableFrom(defaultBooleanType)) { bool ret = (bool)((this.flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00); if ((context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { return SR.GetString(ret ? SR.DataGridViewCheckBoxCell_ClipboardTrue : SR.DataGridViewCheckBoxCell_ClipboardFalse); } return ret; } else { return null; } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.IDataGridViewEditingCell.PrepareEditingCellForEdit"]/*' /> public virtual void PrepareEditingCellForEdit(bool selectAll) { } private ButtonState ButtonState { get { bool found; int buttonState = this.Properties.GetInteger(PropButtonCellState, out found); if (found) { return (ButtonState)buttonState; } return ButtonState.Normal; } set { // ButtonState.Pushed is used for mouse interaction // ButtonState.Checked is used for keyboard interaction Debug.Assert((value & ~(ButtonState.Normal | ButtonState.Pushed | ButtonState.Checked)) == 0); if (this.ButtonState != value) { this.Properties.SetInteger(PropButtonCellState, (int)value); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.EditType"]/*' /> public override Type EditType { get { // Check boxes can't switch to edit mode // This cell type must implement the IEditingCell interface return null; } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.FalseValue"]/*' /> [DefaultValue(null)] public object FalseValue { get { return this.Properties.GetObject(PropFalseValue); } set { if (value != null || this.Properties.ContainsObject(PropFalseValue)) { this.Properties.SetObject(PropFalseValue, value); if (this.DataGridView != null) { if (this.RowIndex != -1) { this.DataGridView.InvalidateCell(this); } else { this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); } } } } } internal object FalseValueInternal { set { if (value != null || this.Properties.ContainsObject(PropFalseValue)) { this.Properties.SetObject(PropFalseValue, value); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.FlatStyle"]/*' /> [DefaultValue(FlatStyle.Standard)] public FlatStyle FlatStyle { get { bool found; int flatStyle = this.Properties.GetInteger(PropFlatStyle, out found); if (found) { return (FlatStyle)flatStyle; } return FlatStyle.Standard; } set { // Sequential enum. Valid values are 0x0 to 0x3 if (!ClientUtils.IsEnumValid(value, (int)value, (int)FlatStyle.Flat, (int)FlatStyle.System)) { throw new InvalidEnumArgumentException("value", (int)value, typeof(FlatStyle)); } if (value != this.FlatStyle) { this.Properties.SetInteger(PropFlatStyle, (int)value); OnCommonChange(); } } } internal FlatStyle FlatStyleInternal { set { Debug.Assert(value >= FlatStyle.Flat && value <= FlatStyle.System); if (value != this.FlatStyle) { this.Properties.SetInteger(PropFlatStyle, (int)value); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.FormattedValueType"]/*' /> public override Type FormattedValueType { get { if (this.ThreeState) { return defaultCheckStateType; } else { return defaultBooleanType; } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.IndeterminateValue"]/*' /> [DefaultValue(null)] public object IndeterminateValue { get { return this.Properties.GetObject(PropIndeterminateValue); } set { if (value != null || this.Properties.ContainsObject(PropIndeterminateValue)) { this.Properties.SetObject(PropIndeterminateValue, value); if (this.DataGridView != null) { if (this.RowIndex != -1) { this.DataGridView.InvalidateCell(this); } else { this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); } } } } } internal object IndeterminateValueInternal { set { if (value != null || this.Properties.ContainsObject(PropIndeterminateValue)) { this.Properties.SetObject(PropIndeterminateValue, value); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.ThreeState"]/*' /> [DefaultValue(false)] public bool ThreeState { get { return ((this.flags & DATAGRIDVIEWCHECKBOXCELL_threeState) != 0x00); } set { if (this.ThreeState != value) { this.ThreeStateInternal = value; if (this.DataGridView != null) { if (this.RowIndex != -1) { this.DataGridView.InvalidateCell(this); } else { this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); } } } } } internal bool ThreeStateInternal { set { if (this.ThreeState != value) { if (value) { this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_threeState; } else { this.flags = (byte)(this.flags & ~DATAGRIDVIEWCHECKBOXCELL_threeState); } } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.TrueValue"]/*' /> [DefaultValue(null)] public object TrueValue { get { return this.Properties.GetObject(PropTrueValue); } set { if (value != null || this.Properties.ContainsObject(PropTrueValue)) { this.Properties.SetObject(PropTrueValue, value); if (this.DataGridView != null) { if (this.RowIndex != -1) { this.DataGridView.InvalidateCell(this); } else { this.DataGridView.InvalidateColumnInternal(this.ColumnIndex); } } } } } internal object TrueValueInternal { set { if (value != null || this.Properties.ContainsObject(PropTrueValue)) { this.Properties.SetObject(PropTrueValue, value); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.ValueType"]/*' /> public override Type ValueType { get { Type valueType = base.ValueType; if (valueType != null) { return valueType; } if (this.ThreeState) { return defaultCheckStateType; } else { return defaultBooleanType; } } set { base.ValueType = value; this.ThreeState = (value != null && defaultCheckStateType.IsAssignableFrom(value)); } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.Clone"]/*' /> public override object Clone() { DataGridViewCheckBoxCell dataGridViewCell; Type thisType = this.GetType(); if (thisType == cellType) //performance improvement { dataGridViewCell = new DataGridViewCheckBoxCell(); } else { // SECREVIEW : Late-binding does not represent a security thread, see bug#411899 for more info.. // dataGridViewCell = (DataGridViewCheckBoxCell)System.Activator.CreateInstance(thisType); } base.CloneInternal(dataGridViewCell); dataGridViewCell.ThreeStateInternal = this.ThreeState; dataGridViewCell.TrueValueInternal = this.TrueValue; dataGridViewCell.FalseValueInternal = this.FalseValue; dataGridViewCell.IndeterminateValueInternal = this.IndeterminateValue; dataGridViewCell.FlatStyleInternal = this.FlatStyle; return dataGridViewCell; } private bool CommonContentClickUnsharesRow(DataGridViewCellEventArgs e) { Point ptCurrentCell = this.DataGridView.CurrentCellAddress; return ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == e.RowIndex && this.DataGridView.IsCurrentCellInEditMode; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.ContentClickUnsharesRow"]/*' /> protected override bool ContentClickUnsharesRow(DataGridViewCellEventArgs e) { return CommonContentClickUnsharesRow(e); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.ContentDoubleClickUnsharesRow"]/*' /> protected override bool ContentDoubleClickUnsharesRow(DataGridViewCellEventArgs e) { return CommonContentClickUnsharesRow(e); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.CreateAccessibilityInstance"]/*' /> protected override AccessibleObject CreateAccessibilityInstance() { return new DataGridViewCheckBoxCellAccessibleObject(this); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.GetContentBounds"]/*' /> protected override Rectangle GetContentBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex) { if (cellStyle == null) { throw new ArgumentNullException("cellStyle"); } if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null) { return Rectangle.Empty; } DataGridViewAdvancedBorderStyle dgvabsEffective; DataGridViewElementStates cellState; Rectangle cellBounds; ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); Rectangle checkBoxBounds = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, null /*formattedValue*/, // checkBoxBounds is independent of formattedValue null /*errorText*/, // checkBoxBounds is independent of errorText cellStyle, dgvabsEffective, DataGridViewPaintParts.ContentForeground, true /*computeContentBounds*/, false /*computeErrorIconBounds*/, false /*paint*/); #if DEBUG object value = GetValue(rowIndex); Rectangle checkBoxBoundsDebug = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, GetEditedFormattedValue(value, rowIndex, ref cellStyle, DataGridViewDataErrorContexts.Formatting), GetErrorText(rowIndex), cellStyle, dgvabsEffective, DataGridViewPaintParts.ContentForeground, true /*computeContentBounds*/, false /*computeErrorIconBounds*/, false /*paint*/); Debug.Assert(checkBoxBoundsDebug.Equals(checkBoxBounds)); #endif return checkBoxBounds; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.GetErrorIconBounds"]/*' /> protected override Rectangle GetErrorIconBounds(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex) { if (cellStyle == null) { throw new ArgumentNullException("cellStyle"); } if (this.DataGridView == null || rowIndex < 0 || this.OwningColumn == null || !this.DataGridView.ShowCellErrors || String.IsNullOrEmpty(GetErrorText(rowIndex))) { return Rectangle.Empty; } Point ptCurrentCell = this.DataGridView.CurrentCellAddress; if (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex && this.DataGridView.IsCurrentCellInEditMode) { // PaintPrivate does not paint the error icon if this is the current cell. // So don't set the ErrorIconBounds either. return Rectangle.Empty; } DataGridViewAdvancedBorderStyle dgvabsEffective; DataGridViewElementStates cellState; Rectangle cellBounds; ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); Rectangle errorIconBounds = PaintPrivate(graphics, cellBounds, cellBounds, rowIndex, cellState, null /*formattedValue*/, // errorIconBounds is independent of formattedValue GetErrorText(rowIndex), cellStyle, dgvabsEffective, DataGridViewPaintParts.ContentForeground, false /*computeContentBounds*/, true /*computeErrorIconBound*/, false /*paint*/); return errorIconBounds; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.GetFormattedValue"]/*' /> protected override object GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context) { if (value != null) { if (this.ThreeState) { if (value.Equals(this.TrueValue) || (value is int && (int)value == (int)CheckState.Checked)) { value = CheckState.Checked; } else if (value.Equals(this.FalseValue) || (value is int && (int)value == (int)CheckState.Unchecked)) { value = CheckState.Unchecked; } else if (value.Equals(this.IndeterminateValue) || (value is int && (int)value == (int)CheckState.Indeterminate)) { value = CheckState.Indeterminate; } /* Commenting out because of bug VSWhidbey 300778 else if (this.DataGridView != null && this.FormattedValueType != null && !(value is System.DBNull) && !this.FormattedValueType.IsAssignableFrom(value.GetType())) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( new FormatException(SR.GetString(SR.DataGridViewCheckBoxCell_InvalidValueType)), this.ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; } } */ } else { if (value.Equals(this.TrueValue) || (value is int && (int)value != 0)) { value = true; } else if (value.Equals(this.FalseValue) || (value is int && (int)value == 0)) { value = false; } /* Commenting out because of bug VSWhidbey 300778 else if (this.DataGridView != null && this.FormattedValueType != null && !(value is System.DBNull) && !this.FormattedValueType.IsAssignableFrom(value.GetType())) { DataGridViewDataErrorEventArgs dgvdee = new DataGridViewDataErrorEventArgs( new FormatException(SR.GetString(SR.DataGridViewCheckBoxCell_InvalidValueType)), this.ColumnIndex, rowIndex, context); RaiseDataError(dgvdee); if (dgvdee.ThrowException) { throw dgvdee.Exception; } } */ } } object ret = base.GetFormattedValue(value, rowIndex, ref cellStyle, valueTypeConverter, formattedValueTypeConverter, context); if (ret != null && (context & DataGridViewDataErrorContexts.ClipboardContent) != 0) { if (ret is bool) { bool retBool = (bool) ret; if (retBool) { return SR.GetString(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); } else { return SR.GetString(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); } } else if (ret is CheckState) { CheckState retCheckState = (CheckState) ret; if (retCheckState == CheckState.Checked) { return SR.GetString(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardChecked : SR.DataGridViewCheckBoxCell_ClipboardTrue); } else if (retCheckState == CheckState.Unchecked) { return SR.GetString(this.ThreeState ? SR.DataGridViewCheckBoxCell_ClipboardUnchecked : SR.DataGridViewCheckBoxCell_ClipboardFalse); } else { Debug.Assert(retCheckState == CheckState.Indeterminate); return SR.GetString(SR.DataGridViewCheckBoxCell_ClipboardIndeterminate); } } } return ret; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.GetPreferredSize"]/*' /> protected override Size GetPreferredSize(Graphics graphics, DataGridViewCellStyle cellStyle, int rowIndex, Size constraintSize) { if (this.DataGridView == null) { return new Size(-1, -1); } if (cellStyle == null) { throw new ArgumentNullException("cellStyle"); } DataGridViewFreeDimension freeDimension = DataGridViewCell.GetFreeDimensionFromConstraint(constraintSize); Rectangle borderWidthsRect = this.StdBorderWidths; int borderAndPaddingWidths = borderWidthsRect.Left + borderWidthsRect.Width + cellStyle.Padding.Horizontal; int borderAndPaddingHeights = borderWidthsRect.Top + borderWidthsRect.Height + cellStyle.Padding.Vertical; Size preferredSize; if (this.DataGridView.ApplyVisualStylesToInnerCells) { // Assuming here that all checkbox states use the same size. We should take the largest of the state specific sizes. Size checkBoxSize = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal); switch (this.FlatStyle) { case FlatStyle.Standard: case FlatStyle.System: break; case FlatStyle.Flat: checkBoxSize.Width -= 3; checkBoxSize.Height -= 3; break; case FlatStyle.Popup: checkBoxSize.Width -= 2; checkBoxSize.Height -= 2; break; } switch (freeDimension) { case DataGridViewFreeDimension.Width: { preferredSize = new Size(checkBoxSize.Width + borderAndPaddingWidths + 2 * DATAGRIDVIEWCHECKBOXCELL_margin, 0); break; } case DataGridViewFreeDimension.Height: { preferredSize = new Size(0, checkBoxSize.Height + borderAndPaddingHeights + 2 * DATAGRIDVIEWCHECKBOXCELL_margin); break; } default: { preferredSize = new Size(checkBoxSize.Width + borderAndPaddingWidths + 2 * DATAGRIDVIEWCHECKBOXCELL_margin, checkBoxSize.Height + borderAndPaddingHeights + 2 * DATAGRIDVIEWCHECKBOXCELL_margin); break; } } } else { int checkBoxSize; switch (this.FlatStyle) { case FlatStyle.Flat: checkBoxSize = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal).Width - 3; break; case FlatStyle.Popup: checkBoxSize = CheckBoxRenderer.GetGlyphSize(graphics, CheckBoxState.UncheckedNormal).Width - 2; break; default: // FlatStyle.Standard || FlatStyle.System checkBoxSize = SystemInformation.Border3DSize.Width * 2 + 9 + 2 * DATAGRIDVIEWCHECKBOXCELL_margin; break; } switch (freeDimension) { case DataGridViewFreeDimension.Width: { preferredSize = new Size(checkBoxSize + borderAndPaddingWidths, 0); break; } case DataGridViewFreeDimension.Height: { preferredSize = new Size(0, checkBoxSize + borderAndPaddingHeights); break; } default: { preferredSize = new Size(checkBoxSize + borderAndPaddingWidths, checkBoxSize + borderAndPaddingHeights); break; } } } // We should consider the border size when calculating the preferred size. DataGridViewAdvancedBorderStyle dgvabsEffective; DataGridViewElementStates cellState; Rectangle cellBounds; ComputeBorderStyleCellStateAndCellBounds(rowIndex, out dgvabsEffective, out cellState, out cellBounds); Rectangle borderWidths = BorderWidths(dgvabsEffective); preferredSize.Width += borderWidths.X; preferredSize.Height += borderWidths.Y; if (this.DataGridView.ShowCellErrors) { // Making sure that there is enough room for the potential error icon if (freeDimension != DataGridViewFreeDimension.Height) { preferredSize.Width = Math.Max(preferredSize.Width, borderAndPaddingWidths + DATAGRIDVIEWCELL_iconMarginWidth * 2 + iconsWidth); } if (freeDimension != DataGridViewFreeDimension.Width) { preferredSize.Height = Math.Max(preferredSize.Height, borderAndPaddingHeights + DATAGRIDVIEWCELL_iconMarginHeight * 2 + iconsHeight); } } return preferredSize; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.KeyDownUnsharesRow"]/*' /> protected override bool KeyDownUnsharesRow(KeyEventArgs e, int rowIndex) { return e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.KeyUpUnsharesRow"]/*' /> protected override bool KeyUpUnsharesRow(KeyEventArgs e, int rowIndex) { return e.KeyCode == Keys.Space; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.MouseDownUnsharesRow"]/*' /> protected override bool MouseDownUnsharesRow(DataGridViewCellMouseEventArgs e) { return e.Button == MouseButtons.Left; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.MouseEnterUnsharesRow"]/*' /> protected override bool MouseEnterUnsharesRow(int rowIndex) { return this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && rowIndex == this.DataGridView.MouseDownCellAddress.Y; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.MouseLeaveUnsharesRow"]/*' /> protected override bool MouseLeaveUnsharesRow(int rowIndex) { return (this.ButtonState & ButtonState.Pushed) != 0; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.MouseUpUnsharesRow"]/*' /> protected override bool MouseUpUnsharesRow(DataGridViewCellMouseEventArgs e) { return e.Button == MouseButtons.Left; } private void NotifyDataGridViewOfValueChange() { this.flags |= (byte)DATAGRIDVIEWCHECKBOXCELL_valueChanged; this.DataGridView.NotifyCurrentCellDirty(true); } private void OnCommonContentClick(DataGridViewCellEventArgs e) { if (this.DataGridView == null) { return; } Point ptCurrentCell = this.DataGridView.CurrentCellAddress; if (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == e.RowIndex && this.DataGridView.IsCurrentCellInEditMode) { if (SwitchFormattedValue()) { NotifyDataGridViewOfValueChange(); } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnContentClick"]/*' /> protected override void OnContentClick(DataGridViewCellEventArgs e) { OnCommonContentClick(e); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnContentDoubleClick"]/*' /> protected override void OnContentDoubleClick(DataGridViewCellEventArgs e) { OnCommonContentClick(e); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnKeyDown"]/*' /> protected override void OnKeyDown(KeyEventArgs e, int rowIndex) { if (this.DataGridView == null) { return; } if (e.KeyCode == Keys.Space && !e.Alt && !e.Control && !e.Shift) { UpdateButtonState(this.ButtonState | ButtonState.Checked, rowIndex); e.Handled = true; } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnKeyUp"]/*' /> protected override void OnKeyUp(KeyEventArgs e, int rowIndex) { if (this.DataGridView == null) { return; } if (e.KeyCode == Keys.Space) { UpdateButtonState(this.ButtonState & ~ButtonState.Checked, rowIndex); if (!e.Alt && !e.Control && !e.Shift) { RaiseCellClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); if (this.DataGridView != null && this.ColumnIndex < this.DataGridView.Columns.Count && rowIndex < this.DataGridView.Rows.Count) { RaiseCellContentClick(new DataGridViewCellEventArgs(this.ColumnIndex, rowIndex)); } e.Handled = true; } NotifyMASSClient(new Point(this.ColumnIndex, rowIndex)); } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnLeave"]/*' /> protected override void OnLeave(int rowIndex, bool throughMouseClick) { if (this.DataGridView == null) { return; } if (this.ButtonState != ButtonState.Normal) { Debug.Assert(this.RowIndex >= 0); // Cell is not in a shared row. UpdateButtonState(ButtonState.Normal, rowIndex); } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnMouseDown"]/*' /> protected override void OnMouseDown(DataGridViewCellMouseEventArgs e) { if (this.DataGridView == null) { return; } if (e.Button == MouseButtons.Left && mouseInContentBounds) { Debug.Assert(this.DataGridView.CellMouseDownInContentBounds); UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex); } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnMouseLeave"]/*' /> protected override void OnMouseLeave(int rowIndex) { if (this.DataGridView == null) { return; } if (mouseInContentBounds) { mouseInContentBounds = false; if (this.ColumnIndex >= 0 && rowIndex >= 0 && (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup)) { this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); } } if ((this.ButtonState & ButtonState.Pushed) != 0 && this.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && rowIndex == this.DataGridView.MouseDownCellAddress.Y) { UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, rowIndex); } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnMouseMove"]/*' /> protected override void OnMouseMove(DataGridViewCellMouseEventArgs e) { if (this.DataGridView == null) { return; } bool oldMouseInContentBounds = mouseInContentBounds; mouseInContentBounds = GetContentBounds(e.RowIndex).Contains(e.X, e.Y); if (oldMouseInContentBounds != mouseInContentBounds) { if (this.DataGridView.ApplyVisualStylesToInnerCells || this.FlatStyle == FlatStyle.Flat || this.FlatStyle == FlatStyle.Popup) { this.DataGridView.InvalidateCell(this.ColumnIndex, e.RowIndex); } if (e.ColumnIndex == this.DataGridView.MouseDownCellAddress.X && e.RowIndex == this.DataGridView.MouseDownCellAddress.Y && Control.MouseButtons == MouseButtons.Left) { if ((this.ButtonState & ButtonState.Pushed) == 0 && mouseInContentBounds && this.DataGridView.CellMouseDownInContentBounds) { UpdateButtonState(this.ButtonState | ButtonState.Pushed, e.RowIndex); } else if ((this.ButtonState & ButtonState.Pushed) != 0 && !mouseInContentBounds) { UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex); } } } base.OnMouseMove(e); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.OnMouseUp"]/*' /> protected override void OnMouseUp(DataGridViewCellMouseEventArgs e) { if (this.DataGridView == null) { return; } if (e.Button == MouseButtons.Left) { UpdateButtonState(this.ButtonState & ~ButtonState.Pushed, e.RowIndex); NotifyMASSClient(new Point(e.ColumnIndex, e.RowIndex)); } } private void NotifyMASSClient(Point position) { Debug.Assert((position.X >= 0) && (position.X < this.DataGridView.Columns.Count)); Debug.Assert((position.Y >= 0) && (position.Y < this.DataGridView.Rows.Count)); int visibleRowIndex = this.DataGridView.Rows.GetRowCount(DataGridViewElementStates.Visible, 0, position.Y); int visibleColumnIndex = this.DataGridView.Columns.ColumnIndexToActualDisplayIndex(position.X, DataGridViewElementStates.Visible); int topHeaderRowIncrement = this.DataGridView.ColumnHeadersVisible ? 1 : 0; int rowHeaderIncrement = this.DataGridView.RowHeadersVisible ? 1 : 0; int objectID = visibleRowIndex + topHeaderRowIncrement // + 1 because the top header row acc obj is at index 0 + 1; // + 1 because objectID's need to be positive and non-zero int childID = visibleColumnIndex + rowHeaderIncrement; // + 1 because the column header cell is at index 0 in top header row acc obj // same thing for the row header cell in the data grid view row acc obj (this.DataGridView.AccessibilityObject as Control.ControlAccessibleObject).NotifyClients(AccessibleEvents.StateChange, objectID, childID); } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.Paint"]/*' /> protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (cellStyle == null) { throw new ArgumentNullException("cellStyle"); } PaintPrivate(graphics, clipBounds, cellBounds, rowIndex, elementState, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts, false /*computeContentBounds*/, false /*computeErrorIconBounds*/, true /*paint*/); } // PaintPrivate is used in three places that need to duplicate the paint code: // 1. DataGridViewCell::Paint method // 2. DataGridViewCell::GetContentBounds // 3. DataGridViewCell::GetErrorIconBounds // // if computeContentBounds is true then PaintPrivate returns the contentBounds // else if computeErrorIconBounds is true then PaintPrivate returns the errorIconBounds // else it returns Rectangle.Empty; private Rectangle PaintPrivate(Graphics g, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts, bool computeContentBounds, bool computeErrorIconBounds, bool paint) { // Parameter checking. // One bit and one bit only should be turned on Debug.Assert(paint || computeContentBounds || computeErrorIconBounds); Debug.Assert(!paint || !computeContentBounds || !computeErrorIconBounds); Debug.Assert(!computeContentBounds || !computeErrorIconBounds || !paint); Debug.Assert(!computeErrorIconBounds || !paint || !computeContentBounds); Debug.Assert(cellStyle != null); Rectangle resultBounds; if (paint && DataGridViewCell.PaintBorder(paintParts)) { PaintBorder(g, clipBounds, cellBounds, cellStyle, advancedBorderStyle); } Rectangle valBounds = cellBounds; Rectangle borderWidths = BorderWidths(advancedBorderStyle); valBounds.Offset(borderWidths.X, borderWidths.Y); valBounds.Width -= borderWidths.Right; valBounds.Height -= borderWidths.Bottom; bool cellSelected = (elementState & DataGridViewElementStates.Selected) != 0; bool drawAsMixedCheckBox = false, drawErrorText = true; CheckState checkState; ButtonState bs; Point ptCurrentCell = this.DataGridView.CurrentCellAddress; if (ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex && this.DataGridView.IsCurrentCellInEditMode) { drawErrorText = false; } if (formattedValue != null && formattedValue is CheckState) { checkState = (CheckState)formattedValue; bs = (checkState == CheckState.Unchecked) ? ButtonState.Normal : ButtonState.Checked; drawAsMixedCheckBox = (checkState == CheckState.Indeterminate); } else if (formattedValue != null && formattedValue is bool) { if ((bool)formattedValue) { checkState = CheckState.Checked; bs = ButtonState.Checked; } else { checkState = CheckState.Unchecked; bs = ButtonState.Normal; } } else { // The provided formatted value has a wrong type. We raised a DataError event while formatting. bs = ButtonState.Normal; // Default rendering of the checkbox with wrong formatted value type. checkState = CheckState.Unchecked; } if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { bs |= ButtonState.Pushed; } SolidBrush br = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); if (paint && DataGridViewCell.PaintBackground(paintParts) && br.Color.A == 255) { g.FillRectangle(br, valBounds); } if (cellStyle.Padding != Padding.Empty) { if (this.DataGridView.RightToLeftInternal) { valBounds.Offset(cellStyle.Padding.Right, cellStyle.Padding.Top); } else { valBounds.Offset(cellStyle.Padding.Left, cellStyle.Padding.Top); } valBounds.Width -= cellStyle.Padding.Horizontal; valBounds.Height -= cellStyle.Padding.Vertical; } if (paint && DataGridViewCell.PaintFocus(paintParts) && this.DataGridView.ShowFocusCues && this.DataGridView.Focused && ptCurrentCell.X == this.ColumnIndex && ptCurrentCell.Y == rowIndex) { // Draw focus rectangle ControlPaint.DrawFocusRectangle(g, valBounds, Color.Empty, br.Color); } Rectangle errorBounds = valBounds; valBounds.Inflate(-DATAGRIDVIEWCHECKBOXCELL_margin, -DATAGRIDVIEWCHECKBOXCELL_margin); Size checkBoxSize; CheckBoxState themeCheckBoxState = CheckBoxState.UncheckedNormal; if (this.DataGridView.ApplyVisualStylesToInnerCells) { themeCheckBoxState = CheckBoxRenderer.ConvertFromButtonState(bs, drawAsMixedCheckBox, this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && mouseInContentBounds); checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, themeCheckBoxState); switch (this.FlatStyle) { case FlatStyle.Standard: case FlatStyle.System: break; case FlatStyle.Flat: checkBoxSize.Width -= 3; checkBoxSize.Height -= 3; break; case FlatStyle.Popup: checkBoxSize.Width -= 2; checkBoxSize.Height -= 2; break; } } else { switch (this.FlatStyle) { case FlatStyle.Flat: checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal); checkBoxSize.Width -= 3; checkBoxSize.Height -= 3; break; case FlatStyle.Popup: checkBoxSize = CheckBoxRenderer.GetGlyphSize(g, CheckBoxState.UncheckedNormal); checkBoxSize.Width -= 2; checkBoxSize.Height -= 2; break; default: // FlatStyle.Standard || FlatStyle.System checkBoxSize = new Size(SystemInformation.Border3DSize.Width * 2 + 9, SystemInformation.Border3DSize.Width * 2 + 9); break; } } if (valBounds.Width >= checkBoxSize.Width && valBounds.Height >= checkBoxSize.Height && (paint || computeContentBounds)) { int checkBoxX = 0, checkBoxY = 0; if ((!this.DataGridView.RightToLeftInternal && (cellStyle.Alignment & anyRight) != 0) || (this.DataGridView.RightToLeftInternal && (cellStyle.Alignment & anyLeft) != 0)) { checkBoxX = valBounds.Right - checkBoxSize.Width; } else if ((cellStyle.Alignment & anyCenter) != 0) { checkBoxX = valBounds.Left + (valBounds.Width - checkBoxSize.Width) / 2; } else { checkBoxX = valBounds.Left; } if ((cellStyle.Alignment & anyBottom) != 0) { checkBoxY = valBounds.Bottom - checkBoxSize.Height; } else if ((cellStyle.Alignment & anyMiddle) != 0) { checkBoxY = valBounds.Top + (valBounds.Height - checkBoxSize.Height) / 2; } else { checkBoxY = valBounds.Top; } if (this.DataGridView.ApplyVisualStylesToInnerCells && this.FlatStyle != FlatStyle.Flat && this.FlatStyle != FlatStyle.Popup) { if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { DataGridViewCheckBoxCellRenderer.DrawCheckBox(g, new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height), (int) themeCheckBoxState); } resultBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height); } else { if (this.FlatStyle == FlatStyle.System || this.FlatStyle == FlatStyle.Standard) { if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { if (drawAsMixedCheckBox) { ControlPaint.DrawMixedCheckBox(g, checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height, bs); } else { ControlPaint.DrawCheckBox(g, checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height, bs); } } resultBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height); } else if (this.FlatStyle == FlatStyle.Flat) { // CheckBox::Paint will only paint the check box differently when in FlatStyle.Flat // this code is copied from CheckBox::DrawCheckFlat. it was a lot of trouble making this function static Rectangle checkBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width, checkBoxSize.Height); SolidBrush foreBrush = null; SolidBrush backBrush = null; Color highlight = Color.Empty; if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { foreBrush = this.DataGridView.GetCachedBrush(cellSelected ? cellStyle.SelectionForeColor : cellStyle.ForeColor); backBrush = this.DataGridView.GetCachedBrush((DataGridViewCell.PaintSelectionBackground(paintParts) && cellSelected) ? cellStyle.SelectionBackColor : cellStyle.BackColor); highlight = ControlPaint.LightLight(backBrush.Color); if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && mouseInContentBounds) { const float lowlight = .1f; float adjust = 1 - lowlight; if (highlight.GetBrightness() < .5) { adjust = 1 + lowlight * 2; } highlight = Color.FromArgb(ButtonInternal.ButtonBaseAdapter.ColorOptions.Adjust255(adjust, highlight.R), ButtonInternal.ButtonBaseAdapter.ColorOptions.Adjust255(adjust, highlight.G), ButtonInternal.ButtonBaseAdapter.ColorOptions.Adjust255(adjust, highlight.B)); } highlight = g.GetNearestColor(highlight); using (Pen pen = new Pen(foreBrush.Color)) { g.DrawLine(pen, checkBounds.Left, checkBounds.Top, checkBounds.Right-1, checkBounds.Top); g.DrawLine(pen, checkBounds.Left, checkBounds.Top, checkBounds.Left, checkBounds.Bottom-1); } } checkBounds.Inflate(-1, -1); checkBounds.Width++; checkBounds.Height++; if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { if (checkState == CheckState.Indeterminate) { ButtonInternal.ButtonBaseAdapter.DrawDitheredFill(g, backBrush.Color, highlight, checkBounds); } else { using (SolidBrush highBrush = new SolidBrush(highlight)) { g.FillRectangle(highBrush, checkBounds); } } // draw the check box if (checkState != CheckState.Unchecked) { Rectangle fullSize = new Rectangle(checkBoxX-1, checkBoxY-1, checkBoxSize.Width+3, checkBoxSize.Height+3); fullSize.Width++; fullSize.Height++; if (checkImage == null || checkImage.Width != fullSize.Width || checkImage.Height != fullSize.Height) { if (checkImage != null) { checkImage.Dispose(); checkImage = null; } // We draw the checkmark slightly off center to eliminate 3-D border artifacts, // and compensate below NativeMethods.RECT rcCheck = NativeMethods.RECT.FromXYWH(0, 0, fullSize.Width, fullSize.Height); Bitmap bitmap = new Bitmap(fullSize.Width, fullSize.Height); using (Graphics offscreen = Graphics.FromImage(bitmap)) { offscreen.Clear(Color.Transparent); IntPtr dc = offscreen.GetHdc(); try { SafeNativeMethods.DrawFrameControl(new HandleRef(offscreen, dc), ref rcCheck, NativeMethods.DFC_MENU, NativeMethods.DFCS_MENUCHECK); } finally { offscreen.ReleaseHdcInternal(dc); } } bitmap.MakeTransparent(); checkImage = bitmap; } fullSize.Y--; ControlPaint.DrawImageColorized(g, checkImage, fullSize, checkState == CheckState.Indeterminate ? ControlPaint.LightLight(foreBrush.Color) : foreBrush.Color); } } resultBounds = checkBounds; } else { Debug.Assert(this.FlatStyle == FlatStyle.Popup); Rectangle checkBounds = new Rectangle(checkBoxX, checkBoxY, checkBoxSize.Width - 1, checkBoxSize.Height - 1); // The CheckBoxAdapter code moves the check box down about 3 pixels so we have to take that into account checkBounds.Y -= 3; if ((this.ButtonState & (ButtonState.Pushed | ButtonState.Checked)) != 0) { // paint down ButtonBaseAdapter.LayoutOptions options = ButtonInternal.CheckBoxPopupAdapter.PaintPopupLayout(g, true /*show3D*/, checkBoxSize.Width, checkBounds, Padding.Empty, false, cellStyle.Font, String.Empty, this.DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), this.DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, this.DataGridView.Enabled).Calculate(); CheckBoxBaseAdapter.DrawCheckBackground(this.DataGridView.Enabled, checkState, g, layout.checkBounds, colors.windowText, colors.buttonFace, true /*disabledColors*/, colors); CheckBoxBaseAdapter.DrawPopupBorder(g, layout.checkBounds, colors); CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, this.DataGridView.Enabled, checkState, g, layout, colors, colors.windowText, colors.buttonFace, true /*disabledColors*/); } resultBounds = layout.checkBounds; } else if (this.DataGridView.MouseEnteredCellAddress.Y == rowIndex && this.DataGridView.MouseEnteredCellAddress.X == this.ColumnIndex && mouseInContentBounds) { // paint over ButtonBaseAdapter.LayoutOptions options = ButtonInternal.CheckBoxPopupAdapter.PaintPopupLayout(g, true /*show3D*/, checkBoxSize.Width, checkBounds, Padding.Empty, false, cellStyle.Font, String.Empty, this.DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), this.DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, this.DataGridView.Enabled).Calculate(); CheckBoxBaseAdapter.DrawCheckBackground(this.DataGridView.Enabled, checkState, g, layout.checkBounds, colors.windowText, colors.options.highContrast ? colors.buttonFace : colors.highlight, true /*disabledColors*/, colors); CheckBoxBaseAdapter.DrawPopupBorder(g, layout.checkBounds, colors); CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, this.DataGridView.Enabled, checkState, g, layout, colors, colors.windowText, colors.highlight, true /*disabledColors*/); } resultBounds = layout.checkBounds; } else { // paint up ButtonBaseAdapter.LayoutOptions options = ButtonInternal.CheckBoxPopupAdapter.PaintPopupLayout(g, false /*show3D*/, checkBoxSize.Width, checkBounds, Padding.Empty, false, cellStyle.Font, String.Empty, this.DataGridView.Enabled, DataGridViewUtilities.ComputeDrawingContentAlignmentForCellStyleAlignment(cellStyle.Alignment), this.DataGridView.RightToLeft); options.everettButtonCompat = false; ButtonBaseAdapter.LayoutData layout = options.Layout(); if (paint && DataGridViewCell.PaintContentForeground(paintParts)) { ButtonBaseAdapter.ColorData colors = ButtonBaseAdapter.PaintPopupRender(g, cellStyle.ForeColor, cellStyle.BackColor, this.DataGridView.Enabled).Calculate(); CheckBoxBaseAdapter.DrawCheckBackground(this.DataGridView.Enabled, checkState, g, layout.checkBounds, colors.windowText, colors.options.highContrast ? colors.buttonFace : colors.highlight, true /*disabledColors*/, colors); ButtonBaseAdapter.DrawFlatBorder(g, layout.checkBounds, colors.buttonShadow); CheckBoxBaseAdapter.DrawCheckOnly(checkBoxSize.Width, checkState == CheckState.Checked || checkState == CheckState.Indeterminate, this.DataGridView.Enabled, checkState, g, layout, colors, colors.windowText, colors.highlight, true /*disabledColors*/); } resultBounds = layout.checkBounds; } } } } else if (computeErrorIconBounds) { if (!String.IsNullOrEmpty(errorText)) { resultBounds = ComputeErrorIconBounds(errorBounds); } else { resultBounds = Rectangle.Empty; } } else { Debug.Assert(valBounds.Width < checkBoxSize.Width || valBounds.Height < checkBoxSize.Height, "the bounds are empty"); resultBounds = Rectangle.Empty; } if (paint && DataGridViewCell.PaintErrorIcon(paintParts) && drawErrorText && this.DataGridView.ShowCellErrors) { PaintErrorIcon(g, cellStyle, rowIndex, cellBounds, errorBounds, errorText); } return resultBounds; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.ParseFormattedValue"]/*' /> public override object ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter) { Debug.Assert(formattedValue == null || this.FormattedValueType == null || this.FormattedValueType.IsAssignableFrom(formattedValue.GetType())); if (formattedValue != null) { if (formattedValue is bool) { if ((bool) formattedValue) { if (this.TrueValue != null) { return this.TrueValue; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) { return true; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Checked; } } else { if (this.FalseValue != null) { return this.FalseValue; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) { return false; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Unchecked; } } } else if (formattedValue is CheckState) { switch ((CheckState) formattedValue) { case CheckState.Checked: if (this.TrueValue != null) { return this.TrueValue; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) { return true; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Checked; } break; case CheckState.Unchecked: if (this.FalseValue != null) { return this.FalseValue; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultBooleanType)) { return false; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Unchecked; } break; case CheckState.Indeterminate: if (this.IndeterminateValue != null) { return this.IndeterminateValue; } else if (this.ValueType != null && this.ValueType.IsAssignableFrom(defaultCheckStateType)) { return CheckState.Indeterminate; } /* case where this.ValueType.IsAssignableFrom(defaultBooleanType) is treated in base.ParseFormattedValue */ break; } } } return base.ParseFormattedValue(formattedValue, cellStyle, formattedValueTypeConverter, valueTypeConverter); } [ SuppressMessage("Microsoft.Performance", "CA1808:AvoidCallsThatBoxValueTypes") // no much choice here. ] private bool SwitchFormattedValue() { if (this.FormattedValueType == null) { return false; } IDataGridViewEditingCell editingCell = (IDataGridViewEditingCell)this; if (this.FormattedValueType.IsAssignableFrom(typeof(System.Windows.Forms.CheckState))) { if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_checked) != 0x00) { editingCell.EditingCellFormattedValue = System.Windows.Forms.CheckState.Indeterminate; } else if ((this.flags & DATAGRIDVIEWCHECKBOXCELL_indeterminate) != 0x00) { editingCell.EditingCellFormattedValue = System.Windows.Forms.CheckState.Unchecked; } else { editingCell.EditingCellFormattedValue = System.Windows.Forms.CheckState.Checked; } } else if (this.FormattedValueType.IsAssignableFrom(defaultBooleanType)) { editingCell.EditingCellFormattedValue = !((bool)editingCell.GetEditingCellFormattedValue(DataGridViewDataErrorContexts.Formatting)); } return true; } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCell.ToString"]/*' /> /// <devdoc> /// <para> /// Gets the row Index and column Index of the cell. /// </para> /// </devdoc> public override string ToString() { return "DataGridViewCheckBoxCell { ColumnIndex=" + this.ColumnIndex.ToString(CultureInfo.CurrentCulture) + ", RowIndex=" + this.RowIndex.ToString(CultureInfo.CurrentCulture) + " }"; } private void UpdateButtonState(ButtonState newButtonState, int rowIndex) { this.ButtonState = newButtonState; this.DataGridView.InvalidateCell(this.ColumnIndex, rowIndex); } private class DataGridViewCheckBoxCellRenderer { static VisualStyleRenderer visualStyleRenderer; private DataGridViewCheckBoxCellRenderer() { } public static VisualStyleRenderer CheckBoxRenderer { get { if (visualStyleRenderer == null) { visualStyleRenderer = new VisualStyleRenderer(CheckBoxElement); } return visualStyleRenderer; } } public static void DrawCheckBox(Graphics g, Rectangle bounds, int state) { CheckBoxRenderer.SetParameters(CheckBoxElement.ClassName, CheckBoxElement.Part, (int) state); CheckBoxRenderer.DrawBackground(g, bounds, Rectangle.Truncate(g.ClipBounds)); } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCellAccessibleObject"]/*' /> protected class DataGridViewCheckBoxCellAccessibleObject : DataGridViewCellAccessibleObject { /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCellAccessibleObject.DataGridViewCheckBoxCellAccessibleObject"]/*' /> public DataGridViewCheckBoxCellAccessibleObject(DataGridViewCell owner) : base (owner) { } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCellAccessibleObject.State"]/*' /> public override AccessibleStates State { get { if (((DataGridViewCheckBoxCell)Owner).EditedFormattedValue is CheckState) { CheckState state = (CheckState)(((DataGridViewCheckBoxCell)Owner).EditedFormattedValue); switch (state) { case CheckState.Checked: return AccessibleStates.Checked | base.State; case CheckState.Indeterminate: return AccessibleStates.Indeterminate | base.State; } } else if (((DataGridViewCheckBoxCell)Owner).EditedFormattedValue is Boolean) { Boolean state = (Boolean)(((DataGridViewCheckBoxCell)Owner).EditedFormattedValue); if (state) { return AccessibleStates.Checked | base.State; } } return base.State; } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCellAccessibleObject.DefaultAction"]/*' /> public override string DefaultAction { get { if (!this.Owner.ReadOnly) { // determine if we switch to Checked/Unchecked value // vsw 533813. bool switchToCheckedState = true; object formattedValue = this.Owner.FormattedValue; if (formattedValue is System.Windows.Forms.CheckState) { switchToCheckedState = ((CheckState) formattedValue) == CheckState.Unchecked; } else if (formattedValue is bool) { switchToCheckedState = !((bool) formattedValue); } if (switchToCheckedState) { return SR.GetString(SR.DataGridView_AccCheckBoxCellDefaultActionCheck); } else { return SR.GetString(SR.DataGridView_AccCheckBoxCellDefaultActionUncheck); } } else { return String.Empty; } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCellAccessibleObject.DoDefaultAction"]/*' /> [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.UnmanagedCode)] public override void DoDefaultAction() { DataGridViewCheckBoxCell dataGridViewCell = (DataGridViewCheckBoxCell) this.Owner; DataGridView dataGridView = dataGridViewCell.DataGridView; if (dataGridView != null && dataGridViewCell.RowIndex == -1) { throw new InvalidOperationException(SR.GetString(SR.DataGridView_InvalidOperationOnSharedCell)); } if (!dataGridViewCell.ReadOnly && dataGridViewCell.OwningColumn != null && dataGridViewCell.OwningRow != null) { dataGridView.CurrentCell = dataGridViewCell; bool endEditMode = false; if (!dataGridView.IsCurrentCellInEditMode) { endEditMode = true; dataGridView.BeginEdit(false /*selectAll*/); } if (dataGridView.IsCurrentCellInEditMode) { if (dataGridViewCell.SwitchFormattedValue()) { dataGridViewCell.NotifyDataGridViewOfValueChange(); dataGridView.InvalidateCell(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex); // notify MSAA clients that the default action changed DataGridViewCheckBoxCell checkBoxCell = Owner as DataGridViewCheckBoxCell; if (checkBoxCell != null) { checkBoxCell.NotifyMASSClient(new Point(dataGridViewCell.ColumnIndex, dataGridViewCell.RowIndex)); } } if (endEditMode) { dataGridView.EndEdit(); } } } } /// <include file='doc\DataGridViewCheckBoxCell.uex' path='docs/doc[@for="DataGridViewCheckBoxCellAccessibleObject.GetChildCount"]/*' /> public override int GetChildCount() { return 0; } } } }
// 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.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.Contracts; using System.Runtime.InteropServices; namespace System.Runtime.InteropServices.WindowsRuntime { /// <summary> /// This is a constant map aimed to efficiently support a Split operation (map decomposition). /// A Split operation returns two non-overlapping, non-empty views of the existing map (or both /// values are set to NULL). The two views returned should contain roughly the same number of elements. /// This map is backed by a sorted array. Thus, split operations are O(1) and enumerations are fast; /// however, look-up in the map are O(log n). /// </summary> /// <typeparam name="TKey">Type of objects that act as keys.</typeparam> /// <typeparam name="TValue">Type of objects that act as entries / values.</typeparam> [Serializable] [DebuggerDisplay("Count = {Count}")] internal sealed class ConstantSplittableMap<TKey, TValue> : IMapView<TKey, TValue> { private class KeyValuePairComparator : IComparer<KeyValuePair<TKey, TValue>> { private static readonly IComparer<TKey> keyComparator = Comparer<TKey>.Default; public Int32 Compare(KeyValuePair<TKey, TValue> x, KeyValuePair<TKey, TValue> y) { return keyComparator.Compare(x.Key, y.Key); } } // private class KeyValuePairComparator private static readonly KeyValuePairComparator keyValuePairComparator = new KeyValuePairComparator(); private readonly KeyValuePair<TKey, TValue>[] items; private readonly int firstItemIndex; private readonly int lastItemIndex; internal ConstantSplittableMap(IReadOnlyDictionary<TKey, TValue> data) { if (data == null) throw new ArgumentNullException(nameof(data)); Contract.EndContractBlock(); firstItemIndex = 0; lastItemIndex = data.Count - 1; items = CreateKeyValueArray(data.Count, data.GetEnumerator()); } private ConstantSplittableMap(KeyValuePair<TKey, TValue>[] items, Int32 firstItemIndex, Int32 lastItemIndex) { this.items = items; this.firstItemIndex = firstItemIndex; this.lastItemIndex = lastItemIndex; } private KeyValuePair<TKey, TValue>[] CreateKeyValueArray(Int32 count, IEnumerator<KeyValuePair<TKey, TValue>> data) { KeyValuePair<TKey, TValue>[] kvArray = new KeyValuePair<TKey, TValue>[count]; Int32 i = 0; while (data.MoveNext()) kvArray[i++] = data.Current; Array.Sort(kvArray, keyValuePairComparator); return kvArray; } public int Count { get { return lastItemIndex - firstItemIndex + 1; } } // [CLSCompliant(false)] public UInt32 Size { get { return (UInt32)(lastItemIndex - firstItemIndex + 1); } } public TValue Lookup(TKey key) { TValue value; bool found = TryGetValue(key, out value); if (!found) { Exception e = new KeyNotFoundException(Environment.GetResourceString("Arg_KeyNotFound")); e.SetErrorCode(__HResults.E_BOUNDS); throw e; } return value; } public bool HasKey(TKey key) { TValue value; bool hasKey = TryGetValue(key, out value); return hasKey; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<IKeyValuePair<TKey, TValue>>)this).GetEnumerator(); } public IIterator<IKeyValuePair<TKey, TValue>> First() { return new EnumeratorToIteratorAdapter<IKeyValuePair<TKey, TValue>>(GetEnumerator()); } public IEnumerator<IKeyValuePair<TKey, TValue>> GetEnumerator() { return new IKeyValuePairEnumerator(items, firstItemIndex, lastItemIndex); } public void Split(out IMapView<TKey, TValue> firstPartition, out IMapView<TKey, TValue> secondPartition) { if (Count < 2) { firstPartition = null; secondPartition = null; return; } int pivot = (Int32)(((Int64)firstItemIndex + (Int64)lastItemIndex) / (Int64)2); firstPartition = new ConstantSplittableMap<TKey, TValue>(items, firstItemIndex, pivot); secondPartition = new ConstantSplittableMap<TKey, TValue>(items, pivot + 1, lastItemIndex); } #region IReadOnlyDictionary members public bool TryGetValue(TKey key, out TValue value) { KeyValuePair<TKey, TValue> searchKey = new KeyValuePair<TKey, TValue>(key, default(TValue)); int index = Array.BinarySearch(items, firstItemIndex, Count, searchKey, keyValuePairComparator); if (index < 0) { value = default(TValue); return false; } value = items[index].Value; return true; } #endregion IReadOnlyDictionary members #region IKeyValuePair Enumerator [Serializable] internal struct IKeyValuePairEnumerator : IEnumerator<IKeyValuePair<TKey, TValue>> { private KeyValuePair<TKey, TValue>[] _array; private int _start; private int _end; private int _current; internal IKeyValuePairEnumerator(KeyValuePair<TKey, TValue>[] items, int first, int end) { Contract.Requires(items != null); Contract.Requires(first >= 0); Contract.Requires(end >= 0); Contract.Requires(first < items.Length); Contract.Requires(end < items.Length); _array = items; _start = first; _end = end; _current = _start - 1; } public bool MoveNext() { if (_current < _end) { _current++; return true; } return false; } public IKeyValuePair<TKey, TValue> Current { get { if (_current < _start) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumNotStarted)); if (_current > _end) throw new InvalidOperationException(Environment.GetResourceString(ResId.InvalidOperation_EnumEnded)); return new CLRIKeyValuePairImpl<TKey, TValue>(ref _array[_current]); } } Object IEnumerator.Current { get { return Current; } } void IEnumerator.Reset() { _current = _start - 1; } public void Dispose() { } } #endregion IKeyValuePair Enumerator } // internal ConstantSplittableMap<TKey, TValue> } // namespace System.Runtime.InteropServices.WindowsRuntime
using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; using Baseline; using Marten.Schema; using Marten.Testing.Documents; using Marten.Testing.Harness; using Shouldly; using Weasel.Postgresql.Tables; using Xunit; namespace Marten.Testing.Acceptance { [Collection("acceptance")] public class computed_indexes: OneOffConfigurationsContext { [Fact] public void example() { #region sample_using-a-simple-calculated-index var store = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); _.DatabaseSchemaName = "examples"; // This creates _.Schema.For<User>().Index(x => x.UserName); }); using (var session = store.QuerySession()) { // Postgresql will be able to use the computed // index generated from above var somebody = session .Query<User>() .FirstOrDefault(x => x.UserName == "somebody"); } #endregion sample_using-a-simple-calculated-index store.Dispose(); } [Fact] public async Task smoke_test() { StoreOptions(_ => _.Schema.For<Target>().Index(x => x.Number)); var data = Target.GenerateRandomData(100).ToArray(); await theStore.BulkInsertAsync(data.ToArray()); var table = await theStore.Tenancy.Default.ExistingTableFor(typeof(Target)); table.HasIndex("mt_doc_target_idx_number").ShouldBeTrue(); using var session = theStore.QuerySession(); var cmd = session.Query<Target>().Where(x => x.Number == 3) .ToCommand(); session.Query<Target>().Where(x => x.Number == data.First().Number) .Select(x => x.Id).ToList().ShouldContain(data.First().Id); } [Fact] public void specify_a_deep_index() { #region sample_deep-calculated-index var store = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); _.Schema.For<Target>().Index(x => x.Inner.Color); }); #endregion sample_deep-calculated-index } [Fact] public void specify_a_different_mechanism_to_customize_the_index() { #region sample_customizing-calculated-index var store = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); // The second, optional argument to Index() // allows you to customize the calculated index _.Schema.For<Target>().Index(x => x.Number, x => { // Change the index method to "brin" x.Method = IndexMethod.brin; // Force the index to be generated with casing rules x.Casing = ComputedIndex.Casings.Lower; // Override the index name if you want x.Name = "mt_my_name"; // Toggle whether or not the index is concurrent // Default is false x.IsConcurrent = true; // Toggle whether or not the index is a UNIQUE // index x.IsUnique = true; // Toggle whether index value will be constrained unique in scope of whole document table (Global) // or in a scope of a single tenant (PerTenant) // Default is Global x.TenancyScope = Schema.Indexing.Unique.TenancyScope.PerTenant; // Partial index by supplying a condition x.Predicate = "(data ->> 'Number')::int > 10"; }); // For B-tree indexes, it's also possible to change // the sort order from the default of "ascending" _.Schema.For<User>().Index(x => x.LastName, x => { // Change the index method to "brin" x.SortOrder = SortOrder.Desc; }); }); #endregion sample_customizing-calculated-index } [Fact] public async Task create_multi_property_index() { StoreOptions(_ => { var columns = new Expression<Func<Target, object>>[] { x => x.UserId, x => x.Flag }; _.Schema.For<Target>().Index(columns); }); var data = Target.GenerateRandomData(100).ToArray(); await theStore.BulkInsertAsync(data.ToArray()); var table = await theStore.Tenancy.Default.ExistingTableFor(typeof(Target)); var index = table.IndexFor("mt_doc_target_idx_user_idflag").As<ActualIndex>(); index.DDL.ShouldBe("CREATE INDEX mt_doc_target_idx_user_idflag ON acceptance.mt_doc_target USING btree ((((data ->> 'UserId'::text))::uuid), (((data ->> 'Flag'::text))::boolean));"); } [Fact] public async Task create_multi_property_string_index_with_casing() { StoreOptions(_ => { var columns = new Expression<Func<Target, object>>[] { x => x.String, x => x.StringField }; _.Schema.For<Target>().Index(columns, c => c.Casing = ComputedIndex.Casings.Upper); }); var data = Target.GenerateRandomData(100).ToArray(); await theStore.BulkInsertAsync(data.ToArray()); var table = await theStore.Tenancy.Default.ExistingTableFor(typeof(Target)); var index = table.IndexFor("mt_doc_target_idx_stringstring_field").ShouldBeOfType<ActualIndex>(); index.DDL.ShouldBe("CREATE INDEX mt_doc_target_idx_stringstring_field ON acceptance.mt_doc_target USING btree (upper((data ->> 'String'::text)), upper((data ->> 'StringField'::text)));"); } [Fact] public void creating_index_using_date_should_work() { StoreOptions(_ => { _.Schema.For<Target>().Index(x => x.Date); }); var data = Target.GenerateRandomData(100).ToArray(); theStore.BulkInsert(data.ToArray()); } [Fact] public async Task create_index_with_custom_name() { StoreOptions(_ => _.Schema.For<Target>().Index(x => x.String, x => { x.Name = "mt_banana_index_created_by_nigel"; })); var testString = "MiXeD cAsE sTrInG"; using (var session = theStore.LightweightSession()) { var item = Target.GenerateRandomData(1).First(); item.String = testString; session.Store(item); await session.SaveChangesAsync(); } (await theStore.Tenancy.Default.ExistingTableFor(typeof(Target))) .HasIndex("mt_banana_index_created_by_nigel"); } [Fact] public async Task patch_if_missing() { using (var store1 = SeparateStore()) { store1.Advanced.Clean.CompletelyRemoveAll(); store1.Tenancy.Default.EnsureStorageExists(typeof(Target)); } using (var store2 = DocumentStore.For(_ => { _.Connection(ConnectionSource.ConnectionString); _.Schema.For<Target>().Index(x => x.Number); })) { var patch = await store2.Schema.CreateMigration(); patch.UpdateSql.ShouldContain( "mt_doc_target_idx_number", Case.Insensitive); } } public computed_indexes() : base("acceptance") { } } }
using System; using Microsoft.Data.Entity; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Metadata; using Microsoft.Data.Entity.Migrations; using SoloProject.Models; namespace SoloProject.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "7.0.0-rc1-16348") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasAnnotation("Relational:Name", "RoleNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasAnnotation("Relational:TableName", "AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasAnnotation("Relational:TableName", "AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasAnnotation("Relational:TableName", "AspNetUserRoles"); }); modelBuilder.Entity("SoloProject.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasAnnotation("Relational:Name", "EmailIndex"); b.HasIndex("NormalizedUserName") .HasAnnotation("Relational:Name", "UserNameIndex"); b.HasAnnotation("Relational:TableName", "AspNetUsers"); }); modelBuilder.Entity("SoloProject.Models.Comment", b => { b.Property<int>("CommentId") .ValueGeneratedOnAdd(); b.Property<string>("CommentBody"); b.Property<string>("Name"); b.Property<int>("PostId"); b.Property<string>("UserId"); b.HasKey("CommentId"); b.HasAnnotation("Relational:TableName", "Comments"); }); modelBuilder.Entity("SoloProject.Models.Post", b => { b.Property<int>("PostId") .ValueGeneratedOnAdd(); b.Property<string>("Content"); b.Property<string>("Name"); b.Property<string>("UserId"); b.HasKey("PostId"); b.HasAnnotation("Relational:TableName", "Posts"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserClaim<string>", b => { b.HasOne("SoloProject.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserLogin<string>", b => { b.HasOne("SoloProject.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("Microsoft.AspNet.Identity.EntityFramework.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNet.Identity.EntityFramework.IdentityRole") .WithMany() .HasForeignKey("RoleId"); b.HasOne("SoloProject.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("SoloProject.Models.Comment", b => { b.HasOne("SoloProject.Models.Post") .WithMany() .HasForeignKey("PostId"); b.HasOne("SoloProject.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("SoloProject.Models.Post", b => { b.HasOne("SoloProject.Models.ApplicationUser") .WithMany() .HasForeignKey("UserId"); }); } } }
//using System; using System; using System.Collections; using System.IO; using System.Runtime.CompilerServices; using System.Threading; using Tamir.SharpSsh.java; using Tamir.SharpSsh.java.lang; using Tamir.SharpSsh.java.net; namespace Tamir.SharpSsh.jsch { public class Session : JavaRunnable { private static String version = "SharpSSH-" + SshBase.Version.ToString() + "-JSCH-0.1.28"; // http://ietf.org/internet-drafts/draft-ietf-secsh-assignednumbers-01.txt internal const int SSH_MSG_DISCONNECT = 1; internal const int SSH_MSG_IGNORE = 2; internal const int SSH_MSG_UNIMPLEMENTED = 3; internal const int SSH_MSG_DEBUG = 4; internal const int SSH_MSG_SERVICE_REQUEST = 5; internal const int SSH_MSG_SERVICE_ACCEPT = 6; internal const int SSH_MSG_KEXINIT = 20; internal const int SSH_MSG_NEWKEYS = 21; internal const int SSH_MSG_KEXDH_INIT = 30; internal const int SSH_MSG_KEXDH_REPLY = 31; internal const int SSH_MSG_KEX_DH_GEX_GROUP = 31; internal const int SSH_MSG_KEX_DH_GEX_INIT = 32; internal const int SSH_MSG_KEX_DH_GEX_REPLY = 33; internal const int SSH_MSG_KEX_DH_GEX_REQUEST = 34; internal const int SSH_MSG_USERAUTH_REQUEST = 50; internal const int SSH_MSG_USERAUTH_FAILURE = 51; internal const int SSH_MSG_USERAUTH_SUCCESS = 52; internal const int SSH_MSG_USERAUTH_BANNER = 53; internal const int SSH_MSG_USERAUTH_INFO_REQUEST = 60; internal const int SSH_MSG_USERAUTH_INFO_RESPONSE = 61; internal const int SSH_MSG_USERAUTH_PK_OK = 60; internal const int SSH_MSG_GLOBAL_REQUEST = 80; internal const int SSH_MSG_REQUEST_SUCCESS = 81; internal const int SSH_MSG_REQUEST_FAILURE = 82; internal const int SSH_MSG_CHANNEL_OPEN = 90; internal const int SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91; internal const int SSH_MSG_CHANNEL_OPEN_FAILURE = 92; internal const int SSH_MSG_CHANNEL_WINDOW_ADJUST = 93; internal const int SSH_MSG_CHANNEL_DATA = 94; internal const int SSH_MSG_CHANNEL_EXTENDED_DATA = 95; internal const int SSH_MSG_CHANNEL_EOF = 96; internal const int SSH_MSG_CHANNEL_CLOSE = 97; internal const int SSH_MSG_CHANNEL_REQUEST = 98; internal const int SSH_MSG_CHANNEL_SUCCESS = 99; internal const int SSH_MSG_CHANNEL_FAILURE = 100; private byte[] V_S; // server version private byte[] V_C = ("SSH-2.0-" + version).GetBytes(); // client version private byte[] I_C; // the payload of the client's SSH_MSG_KEXINIT private byte[] I_S; // the payload of the server's SSH_MSG_KEXINIT // private byte[] K_S; // the host key private byte[] session_id; private byte[] IVc2s; private byte[] IVs2c; private byte[] Ec2s; private byte[] Es2c; private byte[] MACc2s; private byte[] MACs2c; private int seqi = 0; private int seqo = 0; private Cipher s2ccipher; private Cipher c2scipher; private MAC s2cmac; private MAC c2smac; private byte[] mac_buf; private Compression deflater; private Compression inflater; private IO io; private Socket socket; private int timeout = 0; private bool _isConnected = false; private bool isAuthed = false; private JavaThread connectThread = null; internal bool x11_forwarding = false; internal Stream In = null; internal Stream Out = null; internal static Random random; internal Buffer buf; internal Packet packet; internal SocketFactory socket_factory = null; private Hashtable config = null; private IProxy proxy = null; private UserInfo userinfo; internal String host = "127.0.0.1"; internal int port = 22; internal String username = null; internal String password = null; internal JSch jsch; internal Session(JSch jsch) { ; this.jsch = jsch; buf = new Buffer(); packet = new Packet(buf); } public void connect() { connect(timeout); } public void connect(int connectTimeout) { if (_isConnected) { throw new JSchException("session is already connected"); } io = new IO(); if (random == null) { try { var c = Type.GetType(getConfig("random")); random = (Random)Activator.CreateInstance(c); } catch (Exception e) { Console.Error.WriteLine("connect: random " + e); } } Packet.setRandom(random); try { int i, j; // int pad = 0; if (proxy == null) { proxy = jsch.getProxy(host); if (proxy != null) { lock (proxy) { proxy.Close(); } } } if (proxy == null) { Stream In; Stream Out; if (socket_factory == null) { socket = Util.createSocket(host, port, connectTimeout); In = socket.getInputStream(); Out = socket.getOutputStream(); } else { socket = socket_factory.createSocket(host, port); In = socket_factory.getInputStream(socket); Out = socket_factory.getOutputStream(socket); } //if(timeout>0){ socket.setSoTimeout(timeout); } socket.setTcpNoDelay(true); io.setInputStream(In); io.setOutputStream(Out); } else { lock (proxy) { proxy.Connect(socket_factory, host, port, connectTimeout); io.setInputStream(proxy.InputStream); io.setOutputStream(proxy.OutputStream); socket = proxy.Socket; } } if (connectTimeout > 0 && socket != null) { socket.setSoTimeout(connectTimeout); } _isConnected = true; while (true) { i = 0; j = 0; while (i < buf.buffer.Length) { j = io.getByte(); if (j < 0) break; buf.buffer[i] = (byte)j; i++; if (j == 10) break; } if (j < 0) { throw new JSchException("connection is closed by foreign host"); } if (buf.buffer[i - 1] == 10) { // 0x0a i--; if (buf.buffer[i - 1] == 13) { // 0x0d i--; } } if (i > 4 && (i != buf.buffer.Length) && (buf.buffer[0] != 'S' || buf.buffer[1] != 'S' || buf.buffer[2] != 'H' || buf.buffer[3] != '-')) { //System.err.println(new String(buf.buffer, 0, i); continue; } if (i == buf.buffer.Length || i < 7 || // SSH-1.99 or SSH-2.0 (buf.buffer[4] == '1' && buf.buffer[6] != '9') // SSH-1.5 ) { throw new JSchException("invalid server's version String"); } break; } V_S = new byte[i]; Array.Copy(buf.buffer, 0, V_S, 0, i); { // Some Cisco devices will miss to read '\n' if it is sent separately. byte[] foo = new byte[V_C.Length + 1]; Array.Copy(V_C, 0, foo, 0, V_C.Length); foo[foo.Length - 1] = (byte)'\n'; io.put(foo, 0, foo.Length); } buf = read(buf); //System.Console.WriteLine("read: 20 ? "+buf.buffer[5]); if (buf.buffer[5] != SSH_MSG_KEXINIT) { throw new JSchException("invalid protocol: " + buf.buffer[5]); } KeyExchange kex = receive_kexinit(buf); while (true) { buf = read(buf); if (kex.getState() == buf.buffer[5]) { bool result = kex.next(buf); if (!result) { //System.Console.WriteLine("verify: "+result); in_kex = false; throw new JSchException("verify: " + result); } } else { in_kex = false; throw new JSchException("invalid protocol(kex): " + buf.buffer[5]); } if (kex.getState() == KeyExchange.STATE_END) { break; } } try { checkHost(host, kex); } catch (JSchException ee) { in_kex = false; throw ee; } send_newkeys(); // receive SSH_MSG_NEWKEYS(21) buf = read(buf); //System.Console.WriteLine("read: 21 ? "+buf.buffer[5]); if (buf.buffer[5] == SSH_MSG_NEWKEYS) { receive_newkeys(buf, kex); } else { in_kex = false; throw new JSchException("invalid protocol(newkyes): " + buf.buffer[5]); } bool auth = false; bool auth_cancel = false; UserAuthNone usn = new UserAuthNone(userinfo); auth = usn.start(this); String methods = null; if (!auth) { methods = usn.getMethods(); if (methods != null) { methods = methods.ToLower(); } else { // methods: publickey,password,keyboard-interactive methods = "publickey,password,keyboard-interactive"; } } while (true) { while (!auth && methods != null && methods.Length > 0) { UserAuth us = null; if (methods.StartsWith("publickey")) { lock (jsch.identities) { if (jsch.identities.Count > 0) { us = new UserAuthPublicKey(userinfo); } } } else if (methods.StartsWith("keyboard-interactive")) { if (userinfo is UIKeyboardInteractive) { us = new UserAuthKeyboardInteractive(userinfo); } } else if (methods.StartsWith("password")) { us = new UserAuthPassword(userinfo); } if (us != null) { try { auth = us.start(this); auth_cancel = false; } catch (JSchAuthCancelException) { auth_cancel = true; } catch (JSchPartialAuthException ee) { methods = ee.getMethods(); auth_cancel = false; continue; } catch (Exception ee) { Console.WriteLine("ee: " + ee); } } if (!auth) { int comma = methods.IndexOf(","); if (comma == -1) break; methods = methods.Substring(comma + 1); } } break; } if (connectTimeout > 0 || timeout > 0) { socket.setSoTimeout(timeout); } if (auth) { isAuthed = true; connectThread = new JavaThread(this); connectThread.Name("Connect thread " + host + " session"); connectThread.Start(); return; } if (auth_cancel) throw new JSchException("Auth cancel"); throw new JSchException("Auth fail"); } catch (Exception e) { in_kex = false; if (_isConnected) { try { packet.reset(); buf.putByte((byte)SSH_MSG_DISCONNECT); buf.putInt(3); buf.putString(new JavaString(e.ToString()).GetBytes()); buf.putString(new JavaString("en").GetBytes()); write(packet); disconnect(); } catch (Exception) { } } _isConnected = false; if (e is JSchException) throw (JSchException)e; throw new JSchException("Session.connect: " + e); } } private KeyExchange receive_kexinit(Buffer buf) { int j = buf.getInt(); if (j != buf.getLength()) { // packet was compressed and buf.getByte(); // j is the size of deflated packet. I_S = new byte[buf.index - 5]; } else { I_S = new byte[j - 1 - buf.getByte()]; } Array.Copy(buf.buffer, buf.s, I_S, 0, I_S.Length); send_kexinit(); String[] guess = KeyExchange.guess(I_S, I_C); if (guess == null) { throw new JSchException("Algorithm negotiation fail"); } if (!isAuthed && (guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS].Equals("none") || (guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC].Equals("none")))) { throw new JSchException("NONE Cipher should not be chosen before authentification is successed."); } KeyExchange kex = null; try { var c = Type.GetType(getConfig(guess[KeyExchange.PROPOSAL_KEX_ALGS])); kex = (KeyExchange)Activator.CreateInstance(c); } catch (Exception e) { Console.Error.WriteLine("kex: " + e); } kex._guess = guess; kex.init(this, V_S, V_C, I_S, I_C); return kex; } private bool in_kex = false; public void rekey() { send_kexinit(); } private void send_kexinit() { if (in_kex) return; in_kex = true; packet.reset(); buf.putByte((byte)SSH_MSG_KEXINIT); lock (random) { random.fill(buf.buffer, buf.index, 16); buf.skip(16); } buf.putString(getConfig("kex").GetBytes()); buf.putString(getConfig("server_host_key").GetBytes()); buf.putString(getConfig("cipher.c2s").GetBytes()); buf.putString(getConfig("cipher.s2c").GetBytes()); buf.putString(getConfig("mac.c2s").GetBytes()); buf.putString(getConfig("mac.s2c").GetBytes()); buf.putString(getConfig("compression.c2s").GetBytes()); buf.putString(getConfig("compression.s2c").GetBytes()); buf.putString(getConfig("lang.c2s").GetBytes()); buf.putString(getConfig("lang.s2c").GetBytes()); buf.putByte((byte)0); buf.putInt(0); buf.setOffSet(5); I_C = new byte[buf.getLength()]; buf.getByte(I_C); write(packet); } private void send_newkeys() { // send SSH_MSG_NEWKEYS(21) packet.reset(); buf.putByte((byte)SSH_MSG_NEWKEYS); write(packet); } private void checkHost(String host, KeyExchange kex) { String shkc = getConfig("StrictHostKeyChecking"); byte[] K_S = kex.getHostKey(); String key_type = kex.getKeyType(); String key_fprint = kex.getFingerPrint(); hostkey = new HostKey(host, K_S); HostKeyRepository hkr = jsch.getHostKeyRepository(); int i = 0; lock (hkr) { i = hkr.check(host, K_S); } bool insert = false; if ((shkc.Equals("ask") || shkc.Equals("yes")) && i == HostKeyRepository.CHANGED) { String file = null; lock (hkr) { file = hkr.getKnownHostsRepositoryID(); } if (file == null) { file = "known_hosts"; } String message = "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!\n" + "IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!\n" + "Someone could be eavesdropping on you right now (man-in-the-middle attack)!\n" + "It is also possible that the " + key_type + " host key has just been changed.\n" + "The fingerprint for the " + key_type + " key sent by the remote host is\n" + key_fprint + ".\n" + "Please contact your system administrator.\n" + "Add correct host key in " + file + " to get rid of this message."; bool b = false; if (shkc.Equals("ask") && userinfo != null) { b = userinfo.promptYesNo(message + "\nDo you want to delete the old key and insert the new key?"); } if (!b) { throw new JSchException("HostKey has been changed for host '" + host + "', new fingerprint is '" + key_fprint + "'"); } else { lock (hkr) { hkr.remove(host, (key_type.Equals("DSA") ? "ssh-dss" : "ssh-rsa"), null); insert = true; } } } if ((shkc.Equals("ask") || shkc.Equals("yes")) && (i != HostKeyRepository.OK) && !insert) { if (shkc.Equals("yes")) { throw new JSchException("reject HostKey: " + host); } if (userinfo != null) { bool foo = userinfo.promptYesNo( "The authenticity of host '" + host + "' can't be established.\n" + key_type + " key fingerprint is " + key_fprint + ".\n" + "Are you sure you want to continue connecting?" ); if (!foo) { throw new JSchException("reject HostKey: " + host); } insert = true; } else { if (i == HostKeyRepository.NOT_INCLUDED) throw new JSchException("UnknownHostKey: " + host + ". " + key_type + " key fingerprint is " + key_fprint); else throw new JSchException("HostKey has been changed: " + host); } } if (shkc.Equals("no") && HostKeyRepository.NOT_INCLUDED == i) { insert = true; } if (insert) { lock (hkr) { hkr.add(host, K_S, userinfo); } } } public Channel openChannel(String type) { if (!_isConnected) { throw new JSchException("session is down"); } try { Channel channel = Channel.getChannel(type); addChannel(channel); channel.init(); return channel; } catch (Exception e) { Console.WriteLine(e); } return null; } // encode will bin invoked in write with synchronization. public void encode(Packet packet) { if (deflater != null) { packet.buffer.index = deflater.compress(packet.buffer.buffer, 5, packet.buffer.index); } if (c2scipher != null) { packet.padding(c2scipher.getIVSize()); int pad = packet.buffer.buffer[4]; lock (random) { random.fill(packet.buffer.buffer, packet.buffer.index - pad, pad); } } else { packet.padding(8); } byte[] mac = null; if (c2smac != null) { c2smac.update(seqo); c2smac.update(packet.buffer.buffer, 0, packet.buffer.index); mac = c2smac.doFinal(); } if (c2scipher != null) { byte[] buf = packet.buffer.buffer; c2scipher.update(buf, 0, packet.buffer.index, buf, 0); } if (mac != null) { packet.buffer.putByte(mac); } } private int[] uncompress_len = new int[1]; private int cipher_size = 8; public Buffer read(Buffer buf) { int j = 0; while (true) { buf.reset(); io.getByte(buf.buffer, buf.index, cipher_size); buf.index += cipher_size; if (s2ccipher != null) { s2ccipher.update(buf.buffer, 0, cipher_size, buf.buffer, 0); } j = Util.ToInt32(buf.buffer, 0); j = j - 4 - cipher_size + 8; if (j < 0 || (buf.index + j) > buf.buffer.Length) { throw new IOException("invalid data"); } if (j > 0) { io.getByte(buf.buffer, buf.index, j); buf.index += (j); if (s2ccipher != null) { s2ccipher.update(buf.buffer, cipher_size, j, buf.buffer, cipher_size); } } if (s2cmac != null) { s2cmac.update(seqi); s2cmac.update(buf.buffer, 0, buf.index); byte[] result = s2cmac.doFinal(); io.getByte(mac_buf, 0, mac_buf.Length); if (result.Length != mac_buf.Length) throw new IOException("MAC Error"); for (int i = 0; i < result.Length; i++) { if (result[i] != mac_buf[i]) { throw new IOException("MAC Error"); } } } seqi++; if (inflater != null) { //inflater.uncompress(buf); int pad = buf.buffer[4]; uncompress_len[0] = buf.index - 5 - pad; byte[] foo = inflater.uncompress(buf.buffer, 5, uncompress_len); if (foo != null) { buf.buffer = foo; buf.index = 5 + uncompress_len[0]; } else { Console.Error.WriteLine("fail in inflater"); break; } } int type = buf.buffer[5] & 0xff; //System.Console.WriteLine("read: "+type); if (type == SSH_MSG_DISCONNECT) { buf.rewind(); buf.getInt(); buf.getShort(); int reason_code = buf.getInt(); byte[] description = buf.getString(); byte[] language_tag = buf.getString(); /* System.Console.Error.WriteLine("SSH_MSG_DISCONNECT:"+ " "+reason_code+ " "+new String(description)+ " "+new String(language_tag)); */ throw new JSchException("SSH_MSG_DISCONNECT:" + " " + reason_code + " " + new JavaString(description) + " " + new JavaString(language_tag)); //break; } else if (type == SSH_MSG_IGNORE) { } else if (type == SSH_MSG_DEBUG) { buf.rewind(); buf.getInt(); buf.getShort(); } else if (type == SSH_MSG_CHANNEL_WINDOW_ADJUST) { buf.rewind(); buf.getInt(); buf.getShort(); Channel c = Channel.getChannel(buf.getInt(), this); if (c == null) { } else { c.addRemoteWindowSize(buf.getInt()); } } else { break; } } buf.rewind(); return buf; } internal byte[] getSessionId() { return session_id; } private void receive_newkeys(Buffer buf, KeyExchange kex) { updateKeys(kex); in_kex = false; } private void updateKeys(KeyExchange kex) { byte[] K = kex.getK(); byte[] H = kex.getH(); HASH hash = kex.getHash(); String[] guess = kex._guess; if (session_id == null) { session_id = new byte[H.Length]; Array.Copy(H, 0, session_id, 0, H.Length); } /* Initial IV client to server: HASH (K || H || "A" || session_id) Initial IV server to client: HASH (K || H || "B" || session_id) Encryption key client to server: HASH (K || H || "C" || session_id) Encryption key server to client: HASH (K || H || "D" || session_id) Integrity key client to server: HASH (K || H || "E" || session_id) Integrity key server to client: HASH (K || H || "F" || session_id) */ buf.reset(); buf.putMPInt(K); buf.putByte(H); buf.putByte((byte)0x41); buf.putByte(session_id); hash.update(buf.buffer, 0, buf.index); IVc2s = hash.digest(); int j = buf.index - session_id.Length - 1; buf.buffer[j]++; hash.update(buf.buffer, 0, buf.index); IVs2c = hash.digest(); buf.buffer[j]++; hash.update(buf.buffer, 0, buf.index); Ec2s = hash.digest(); buf.buffer[j]++; hash.update(buf.buffer, 0, buf.index); Es2c = hash.digest(); buf.buffer[j]++; hash.update(buf.buffer, 0, buf.index); MACc2s = hash.digest(); buf.buffer[j]++; hash.update(buf.buffer, 0, buf.index); MACs2c = hash.digest(); try { var c = Type.GetType(getConfig(guess[KeyExchange.PROPOSAL_ENC_ALGS_STOC])); s2ccipher = (Cipher)(Activator.CreateInstance(c)); while (s2ccipher.getBlockSize() > Es2c.Length) { buf.reset(); buf.putMPInt(K); buf.putByte(H); buf.putByte(Es2c); hash.update(buf.buffer, 0, buf.index); byte[] foo = hash.digest(); byte[] bar = new byte[Es2c.Length + foo.Length]; Array.Copy(Es2c, 0, bar, 0, Es2c.Length); Array.Copy(foo, 0, bar, Es2c.Length, foo.Length); Es2c = bar; } s2ccipher.init(Cipher.DECRYPT_MODE, Es2c, IVs2c); cipher_size = s2ccipher.getIVSize(); c = Type.GetType(getConfig(guess[KeyExchange.PROPOSAL_MAC_ALGS_STOC])); s2cmac = (MAC)(Activator.CreateInstance(c)); s2cmac.init(MACs2c); mac_buf = new byte[s2cmac.getBlockSize()]; c = Type.GetType(getConfig(guess[KeyExchange.PROPOSAL_ENC_ALGS_CTOS])); c2scipher = (Cipher)(Activator.CreateInstance(c)); while (c2scipher.getBlockSize() > Ec2s.Length) { buf.reset(); buf.putMPInt(K); buf.putByte(H); buf.putByte(Ec2s); hash.update(buf.buffer, 0, buf.index); byte[] foo = hash.digest(); byte[] bar = new byte[Ec2s.Length + foo.Length]; Array.Copy(Ec2s, 0, bar, 0, Ec2s.Length); Array.Copy(foo, 0, bar, Ec2s.Length, foo.Length); Ec2s = bar; } c2scipher.init(Cipher.ENCRYPT_MODE, Ec2s, IVc2s); c = Type.GetType(getConfig(guess[KeyExchange.PROPOSAL_MAC_ALGS_CTOS])); c2smac = (MAC)(Activator.CreateInstance(c)); c2smac.init(MACc2s); if (!guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS].Equals("none")) { String foo = getConfig(guess[KeyExchange.PROPOSAL_COMP_ALGS_CTOS]); if (foo != null) { try { c = Type.GetType(foo); deflater = (Compression)(Activator.CreateInstance(c)); int level = 6; try { level = Int32.Parse(getConfig("compression_level")); } catch (Exception) { } deflater.init(Compression.DEFLATER, level); } catch (Exception) { Console.Error.WriteLine(foo + " isn't accessible."); } } } else { if (deflater != null) { deflater = null; } } if (!guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC].Equals("none")) { String foo = getConfig(guess[KeyExchange.PROPOSAL_COMP_ALGS_STOC]); if (foo != null) { try { c = Type.GetType(foo); inflater = (Compression)(Activator.CreateInstance(c)); inflater.init(Compression.INFLATER, 0); } catch (Exception) { Console.Error.WriteLine(foo + " isn't accessible."); } } } else { if (inflater != null) { inflater = null; } } } catch (Exception e) { Console.Error.WriteLine("updatekeys: " + e); } } public void write(Packet packet, Channel c, int length) { while (true) { if (in_kex) { try { Thread.Sleep(10); } catch (ThreadInterruptedException) { } continue; } lock (c) { if (c.rwsize >= length) { c.rwsize -= length; break; } } if (c._close || !c.isConnected()) { throw new IOException("channel is broken"); } bool sendit = false; int s = 0; byte command = 0; int recipient = -1; lock (c) { if (c.rwsize > 0) { int len = c.rwsize; if (len > length) { len = length; } if (len != length) { s = packet.shift(len, (c2smac != null ? c2smac.getBlockSize() : 0)); } command = packet.buffer.buffer[5]; recipient = c.getRecipient(); length -= len; c.rwsize -= len; sendit = true; } } if (sendit) { _write(packet); if (length == 0) { return; } packet.unshift(command, recipient, s, length); lock (c) { if (c.rwsize >= length) { c.rwsize -= length; break; } } } try { Thread.Sleep(100); } catch (ThreadInterruptedException) { } } _write(packet); } public void write(Packet packet) { while (in_kex) { byte command = packet.buffer.buffer[5]; if (command == SSH_MSG_KEXINIT || command == SSH_MSG_NEWKEYS || command == SSH_MSG_KEXDH_INIT || command == SSH_MSG_KEXDH_REPLY || command == SSH_MSG_DISCONNECT || command == SSH_MSG_KEX_DH_GEX_GROUP || command == SSH_MSG_KEX_DH_GEX_INIT || command == SSH_MSG_KEX_DH_GEX_REPLY || command == SSH_MSG_KEX_DH_GEX_REQUEST) { break; } try { Thread.Sleep(10); } catch (ThreadInterruptedException) { } } _write(packet); } [MethodImpl(MethodImplOptions.Synchronized)] private void _write(Packet packet) { encode(packet); if (io != null) { io.put(packet); seqo++; } } private JavaRunnable thread; public void run() { thread = this; byte[] foo; Buffer buf = new Buffer(); Packet packet = new Packet(buf); int i = 0; Channel channel; int[] start = new int[1]; int[] length = new int[1]; KeyExchange kex = null; try { while (_isConnected && thread != null) { buf = read(buf); int msgType = buf.buffer[5] & 0xff; if (kex != null && kex.getState() == msgType) { bool result = kex.next(buf); if (!result) { throw new JSchException("verify: " + result); } continue; } switch (msgType) { case SSH_MSG_KEXINIT: //System.Console.WriteLine("KEXINIT"); kex = receive_kexinit(buf); break; case SSH_MSG_NEWKEYS: //System.Console.WriteLine("NEWKEYS"); send_newkeys(); receive_newkeys(buf, kex); kex = null; break; case SSH_MSG_CHANNEL_DATA: buf.getInt(); buf.getByte(); buf.getByte(); i = buf.getInt(); channel = Channel.getChannel(i, this); foo = buf.getString(start, length); if (channel == null) { break; } try { channel.write(foo, start[0], length[0]); } catch (Exception) { //System.Console.WriteLine(e); try { channel.disconnect(); } catch (Exception) { } break; } int len = length[0]; channel.setLocalWindowSize(channel.lwsize - len); if (channel.lwsize < channel.lwsize_max / 2) { packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST); buf.putInt(channel.getRecipient()); buf.putInt(channel.lwsize_max - channel.lwsize); write(packet); channel.setLocalWindowSize(channel.lwsize_max); } break; case SSH_MSG_CHANNEL_EXTENDED_DATA: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); buf.getInt(); // data_type_code == 1 foo = buf.getString(start, length); //System.Console.WriteLine("stderr: "+new String(foo,start[0],length[0])); if (channel == null) { break; } //channel.write(foo, start[0], length[0]); channel.write_ext(foo, start[0], length[0]); len = length[0]; channel.setLocalWindowSize(channel.lwsize - len); if (channel.lwsize < channel.lwsize_max / 2) { packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_WINDOW_ADJUST); buf.putInt(channel.getRecipient()); buf.putInt(channel.lwsize_max - channel.lwsize); write(packet); channel.setLocalWindowSize(channel.lwsize_max); } break; case SSH_MSG_CHANNEL_WINDOW_ADJUST: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel == null) { break; } channel.addRemoteWindowSize(buf.getInt()); break; case SSH_MSG_CHANNEL_EOF: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel != null) { //channel._eof_remote=true; //channel.eof(); channel.eof_remote(); } /* packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_EOF); buf.putInt(channel.getRecipient()); write(packet); */ break; case SSH_MSG_CHANNEL_CLOSE: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel != null) { // channel.close(); channel.disconnect(); } /* if(Channel.pool.Count==0){ thread=null; } */ break; case SSH_MSG_CHANNEL_OPEN_CONFIRMATION: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel == null) { //break; } channel.setRecipient(buf.getInt()); channel.setRemoteWindowSize(buf.getInt()); channel.setRemotePacketSize(buf.getInt()); break; case SSH_MSG_CHANNEL_OPEN_FAILURE: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel == null) { //break; } int reason_code = buf.getInt(); //foo=buf.getString(); // additional textual information //foo=buf.getString(); // language tag channel.exitstatus = reason_code; channel._close = true; channel._eof_remote = true; channel.setRecipient(0); break; case SSH_MSG_CHANNEL_REQUEST: buf.getInt(); buf.getShort(); i = buf.getInt(); foo = buf.getString(); bool reply = (buf.getByte() != 0); channel = Channel.getChannel(i, this); if (channel != null) { byte reply_type = (byte)SSH_MSG_CHANNEL_FAILURE; if ((new JavaString(foo)).Equals("exit-status")) { i = buf.getInt(); // exit-status channel.setExitStatus(i); // System.Console.WriteLine("exit-stauts: "+i); // channel.close(); reply_type = (byte)SSH_MSG_CHANNEL_SUCCESS; } if (reply) { packet.reset(); buf.putByte(reply_type); buf.putInt(channel.getRecipient()); write(packet); } } else { } break; case SSH_MSG_CHANNEL_OPEN: buf.getInt(); buf.getShort(); foo = buf.getString(); JavaString ctyp = new JavaString(foo); //System.Console.WriteLine("type="+ctyp); if (!new JavaString("forwarded-tcpip").Equals(ctyp) && !(new JavaString("x11").Equals(ctyp) && x11_forwarding)) { Console.WriteLine("Session.run: CHANNEL OPEN " + ctyp); throw new IOException("Session.run: CHANNEL OPEN " + ctyp); } else { channel = Channel.getChannel(ctyp); addChannel(channel); channel.getData(buf); channel.init(); packet.reset(); buf.putByte((byte)SSH_MSG_CHANNEL_OPEN_CONFIRMATION); buf.putInt(channel.getRecipient()); buf.putInt(channel.id); buf.putInt(channel.lwsize); buf.putInt(channel.lmpsize); write(packet); JavaThread tmp = new JavaThread(channel); tmp.Name("Channel " + ctyp + " " + host); tmp.Start(); break; } case SSH_MSG_CHANNEL_SUCCESS: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel == null) { break; } channel.reply = 1; break; case SSH_MSG_CHANNEL_FAILURE: buf.getInt(); buf.getShort(); i = buf.getInt(); channel = Channel.getChannel(i, this); if (channel == null) { break; } channel.reply = 0; break; case SSH_MSG_GLOBAL_REQUEST: buf.getInt(); buf.getShort(); foo = buf.getString(); // request name reply = (buf.getByte() != 0); if (reply) { packet.reset(); buf.putByte((byte)SSH_MSG_REQUEST_FAILURE); write(packet); } break; case SSH_MSG_REQUEST_FAILURE: case SSH_MSG_REQUEST_SUCCESS: JavaThread t = grr.getThread(); if (t != null) { grr.setReply(msgType == SSH_MSG_REQUEST_SUCCESS ? 1 : 0); t.Interrupt(); } break; default: Console.WriteLine("Session.run: unsupported type " + msgType); throw new IOException("Unknown SSH message type " + msgType); } } } catch (Exception) { //System.Console.WriteLine("# Session.run"); //e.printStackTrace(); } try { disconnect(); } catch (NullReferenceException) { //System.Console.WriteLine("@1"); //e.printStackTrace(); } catch (Exception) { //System.Console.WriteLine("@2"); //e.printStackTrace(); } _isConnected = false; } /* public void finalize() throws Throwable{ disconnect(); jsch=null; } */ public void disconnect() { if (!_isConnected) return; //System.Console.WriteLine(this+": disconnect"); //Thread.dumpStack(); /* for(int i=0; i<Channel.pool.Count; i++){ try{ Channel c=((Channel)(Channel.pool[i])); if(c.session==this) c.eof(); } catch(System.Exception e){ } } */ Channel.disconnect(this); _isConnected = false; PortWatcher.delPort(this); ChannelForwardedTCPIP.delPort(this); lock (connectThread) { connectThread.Interrupt(); connectThread = null; } thread = null; try { if (io != null) { if (io.ins != null) io.ins.Close(); if (io.outs != null) io.outs.Close(); if (io.outs_ext != null) io.outs_ext.Close(); } if (proxy == null) { if (socket != null) socket.Close(); } else { lock (proxy) { proxy.Close(); } proxy = null; } } catch (Exception) { // e.printStackTrace(); } io = null; socket = null; // lock(jsch.pool){ // jsch.pool.removeElement(this); // } jsch.removeSession(this); //System.gc(); } public void setPortForwardingL(int lport, JavaString host, int rport) { setPortForwardingL("127.0.0.1", lport, host, rport); } public void setPortForwardingL(JavaString boundaddress, int lport, JavaString host, int rport) { setPortForwardingL(boundaddress, lport, host, rport, null); } public void setPortForwardingL(JavaString boundaddress, int lport, JavaString host, int rport, ServerSocketFactory ssf) { PortWatcher pw = PortWatcher.addPort(this, boundaddress, lport, host, rport, ssf); JavaThread tmp = new JavaThread(pw); tmp.Name("PortWatcher Thread for " + host); tmp.Start(); } public void delPortForwardingL(int lport) { delPortForwardingL("127.0.0.1", lport); } public void delPortForwardingL(JavaString boundaddress, int lport) { PortWatcher.delPort(this, boundaddress, lport); } public String[] getPortForwardingL() { return PortWatcher.getPortForwarding(this); } public void setPortForwardingR(int rport, JavaString host, int lport) { setPortForwardingR(rport, host, lport, (SocketFactory)null); } public void setPortForwardingR(int rport, JavaString host, int lport, SocketFactory sf) { ChannelForwardedTCPIP.addPort(this, rport, host, lport, sf); setPortForwarding(rport); } public void setPortForwardingR(int rport, JavaString daemon) { setPortForwardingR(rport, daemon, null); } public void setPortForwardingR(int rport, JavaString daemon, Object[] arg) { ChannelForwardedTCPIP.addPort(this, rport, daemon, arg); setPortForwarding(rport); } private class GlobalRequestReply { private JavaThread thread = null; private int reply = -1; internal void setThread(JavaThread thread) { this.thread = thread; this.reply = -1; } internal JavaThread getThread() { return thread; } internal void setReply(int reply) { this.reply = reply; } internal int getReply() { return this.reply; } } private GlobalRequestReply grr = new GlobalRequestReply(); private void setPortForwarding(int rport) { lock (grr) { Buffer buf = new Buffer(100); // ?? Packet packet = new Packet(buf); try { // byte SSH_MSG_GLOBAL_REQUEST 80 // String "tcpip-forward" // bool want_reply // String address_to_bind // uint32 port number to bind packet.reset(); buf.putByte((byte)SSH_MSG_GLOBAL_REQUEST); buf.putString(new JavaString("tcpip-forward").GetBytes()); // buf.putByte((byte)0); buf.putByte((byte)1); buf.putString(new JavaString("0.0.0.0").GetBytes()); buf.putInt(rport); write(packet); } catch (Exception e) { throw new JSchException(e.ToString()); } grr.setThread(new JavaThread(Thread.CurrentThread)); try { Thread.Sleep(10000); } catch (Exception) { } int reply = grr.getReply(); grr.setThread(null); if (reply == 0) { throw new JSchException("remote port forwarding failed for listen port " + rport); } } } public void delPortForwardingR(int rport) { ChannelForwardedTCPIP.delPort(this, rport); } internal void addChannel(Channel channel) { channel.session = this; } public JavaString getConfig(object name) { Object foo = null; if (config != null) { foo = config[name]; if (foo is JavaString) return (JavaString)foo; if (foo is string) return (string)foo; } foo = jsch.getConfig(name.ToString()); if (foo is string) return (string)foo; if (foo is JavaString) return (JavaString)foo; return null; } // public Channel getChannel(){ return channel; } public void setProxy(IProxy proxy) { this.proxy = proxy; } public void setHost(JavaString host) { this.host = host; } public void setPort(int port) { this.port = port; } internal void setUserName(JavaString foo) { this.username = foo; } public void setPassword(JavaString foo) { this.password = foo; } public void setUserInfo(UserInfo userinfo) { this.userinfo = userinfo; } public void setInputStream(Stream In) { this.In = In; } public void setOutputStream(Stream Out) { this.Out = Out; } public void setX11Host(JavaString host) { ChannelX11.setHost(host); } public void setX11Port(int port) { ChannelX11.setPort(port); } public void setX11Cookie(JavaString cookie) { ChannelX11.setCookie(cookie); } public void setConfig(Hashtable foo) { this.config = foo; } public void setSocketFactory(SocketFactory foo) { socket_factory = foo; } public bool isConnected() { return _isConnected; } public int getTimeout() { return timeout; } public void setTimeout(int foo) { if (socket == null) { if (foo < 0) { throw new JSchException("invalid timeout value"); } this.timeout = foo; return; } try { socket.setSoTimeout(foo); timeout = foo; } catch (Exception e) { throw new JSchException(e.ToString()); } } public JavaString getServerVersion() { return new JavaString(V_S); } public JavaString getClientVersion() { return new JavaString(V_C); } public void setClientVersion(JavaString cv) { V_C = cv.GetBytes(); } public void sendIgnore() { Buffer buf = new Buffer(); Packet packet = new Packet(buf); packet.reset(); buf.putByte((byte)SSH_MSG_IGNORE); write(packet); } private static byte[] keepalivemsg = "[email protected]".GetBytes(); public void sendKeepAliveMsg() { Buffer buf = new Buffer(); Packet packet = new Packet(buf); packet.reset(); buf.putByte((byte)SSH_MSG_GLOBAL_REQUEST); buf.putString(keepalivemsg); buf.putByte((byte)1); write(packet); } private HostKey hostkey = null; public HostKey getHostKey() { return hostkey; } public String getHost() { return host; } public String getUserName() { return username; } public int getPort() { return port; } public String getMac() { String mac = ""; if (s2cmac != null) mac = s2cmac.getName(); return mac; } public String getCipher() { String cipher = ""; if (s2ccipher != null) cipher = s2ccipher.ToString(); return cipher; } public int BufferLength { get { return this.buf.buffer.Length; } } public IProxy GetProxy() { return this.proxy; } } }
// TODO: Create banner using System; using System.IO; using System.Collections.Generic; using System.Threading; using System.Text; using System.Net; using System.Net.Sockets; using OpenSim.Framework; using log4net; namespace OpenSim.Region.Physics.RemotePhysicsPlugin { public class RemotePhysicsTCPPacketManager : IDisposable, IRemotePhysicsPacketManager { /// <summary> /// The logger that will be used for the packet manager. /// </summary> internal static readonly ILog m_log = LogManager.GetLogger( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// This is the tag that will be used to deonte log messages from /// this class /// </summary> internal static readonly string LogHeader = "[REMOTE PHYSICS MESSENGER]"; /// <summary> /// The queue of packets that have been received. /// </summary> protected Queue<byte[]> m_incomingPackets; /// <summary> /// The queue of packets that are ready to be sent. /// </summary> protected Queue<byte[]> m_outgoingPackets; /// <summary> /// Indicates whether this packet manager should use its own internal /// thread for updating. /// </summary> protected bool m_useInternalThread; /// <summary> /// The internal thread used for updating this packet manager /// (if it is enabled). /// </summary> protected Thread m_updateThread; /// <summary> /// The maximum message size that this packet manager will process. /// </summary> protected readonly int m_receiveBufferLength = 65536; /// <summary> /// The buffer used for receiving packets from the remote engine. /// </summary> protected byte[] m_readBuffer; /// <summary> /// Buffer used to store messages whose parts oveflow the read buffer. /// <summary> protected byte[] m_overflowBuffer; /// <summary> /// The index of the m_overflowBuffer to which new data should be /// written. /// </summary> protected int m_overflowWritePosition = 0; /// <summary> /// The lock used to ensure that the outgoing packet queue is /// thread-safe. /// </summary> protected Mutex m_outgoingMutex; /// <summary> /// The lock used to ensure that the incoming packet queue is /// thread-safe. /// </summary> protected Mutex m_incomingMutex; /// <summary> /// The network socket used to communicate with the remote physics /// engine. /// </summary> protected Socket m_remoteSocket; /// <summary> /// Synchronization event used to ensure that the packet manager's /// thread does not proceed until connection is complete. /// </summary> protected ManualResetEvent connectDone; /// <summary> /// Indicates whether the internal update thread should /// (if one is being used). /// </summary> protected bool m_stopUpdates = false; /// <summary> /// Flag used to ensure that packets are received in order. /// </summary> protected bool m_receiveReady = true; /// <summary> /// Flag used to ensure that packets are sent in order. /// </summary> protected bool m_sendReady = true; /// <summary> /// The expected size of a packet header. Used to extract headers out /// of the incoming data stream. /// </summary> protected uint m_headerSize; /// <summary> /// The default packet header size used, if none is specified. /// </summary> protected static readonly uint m_defaultHeaderSize = 24; /// <summary> /// The byte offset at which the packet contains the length field. /// Used to determine incoming packet size. /// </summary> protected uint m_packetLengthOffset; /// <summary> /// The default offset location at which the packet length field /// resides in bytes. /// </summary> protected static readonly uint m_defaultPacketLengthOffset = 8; /// <summary> /// The maximum number of outgoing packets that should be processed in /// one update. /// </summary> protected static int m_maxOutgoingPackets = 50; /// <summary> /// Flag indicating whether the manager has successfully connected to /// the remote physics engine. /// </summary> protected bool m_isConnected = false; /// <summary> /// Mutex object for ensuring that the connected flag is accessed in /// thread-safe manner. /// </summary> protected Object m_connectedLock = new Object(); /// <summary> /// Constructor of the TCP packet manager. /// </summary> /// <param name="config">The configuration which is used to /// initialize the packet manager</param> public RemotePhysicsTCPPacketManager(RemotePhysicsConfiguration config) { IPAddress remoteAddress; IPEndPoint remoteEP; // Create the incoming/outgoing packet threads and locks m_incomingPackets = new Queue<byte[]>(); m_outgoingPackets = new Queue<byte[]>(); m_outgoingMutex = new Mutex(); m_incomingMutex = new Mutex(); // Configure the connection point using the configuration address // and port remoteAddress = IPAddress.Parse(config.RemoteAddress); remoteEP = new IPEndPoint(remoteAddress, config.RemotePort); // Create the socket that will allow for communication with the // remote physics engine m_remoteSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Initialize the synchronization event used to block this // thread during the connection process connectDone = new ManualResetEvent(false); // Start the connection to the remote physics engine m_remoteSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), m_remoteSocket); // Block the thread until the connection is complete connectDone.WaitOne(); // Initialize the buffer that will be used for reading messages // from the remote physics engine m_readBuffer = new byte[m_receiveBufferLength]; // Initialize the buffer that will be used to hold messages whose // data overflow the read buffer m_overflowBuffer = new byte[m_receiveBufferLength]; // Check to see if the configuration states that this packet // manager should use its own internal thread m_useInternalThread = config.PacketManagerInternalThread; if (m_useInternalThread) { // Create thread that will send and receive messages from the // remote server m_updateThread = new Thread(new ThreadStart(RunUpdate)); m_updateThread.Start(); } // Initialize the header length and packet length offset to // their defaults m_headerSize = m_defaultHeaderSize; m_packetLengthOffset = m_defaultPacketLengthOffset; } /// <summary> /// Constructor of the TCP packet manager. /// </summary> /// <param name="remoteAddress">The address of the remote physics /// engine server</param> /// <param name="remotePort">The port used to communicate with the /// remote physics engine</param> /// <param name="useInternalThread">Indicates whether the packet /// manager should use its own update thread</param> public RemotePhysicsTCPPacketManager(string remoteAddress, int remotePort, bool useInternalThread) { IPAddress engineAddress; IPEndPoint remoteEP; // Create the incoming/outgoing packet threads and locks m_incomingPackets = new Queue<byte[]>(); m_outgoingPackets = new Queue<byte[]>(); // Configure the connection point using the configuration address // and port engineAddress = IPAddress.Parse(remoteAddress); remoteEP = new IPEndPoint(engineAddress, remotePort); // Create the socket that will allow for communication with the // remote physics engine m_remoteSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Initialize the synchronization event used to block this thread // during the connection process connectDone = new ManualResetEvent(false); // Start the connection to the remote physics engine m_remoteSocket.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), m_remoteSocket); // Block the thread until the connection is complete connectDone.WaitOne(); // Initialize the buffer that will be used for reading messages // from the remote physics engine m_readBuffer = new byte[m_receiveBufferLength]; // Initialize the buffer that will be used to hold messages whose // data overflow the read buffer m_overflowBuffer = new byte[m_receiveBufferLength]; // Check to see if the configuration states that this packet // manager should use its own internal thread m_useInternalThread = useInternalThread; if (m_useInternalThread) { // Create thread that will send and receive messages from the // remote server m_updateThread = new Thread(new ThreadStart(RunUpdate)); } // Initialize the header length and packet length offset to // their defaults m_headerSize = m_defaultHeaderSize; m_packetLengthOffset = m_defaultPacketLengthOffset; } /// <summary> /// Releases resources and closes threads. /// </summary> public void Dispose() { bool isConnected; lock (m_connectedLock) { isConnected = m_isConnected; // Indicate that this manager should no longer be connected m_isConnected = false; } // Close the update thread, if one is being used if (m_useInternalThread && m_updateThread != null) { // Indicate that update thread should be stopped StopUpdates(); // Wait half a second for the thread to finish executing m_updateThread.Join(500); } // Check to see if the packet manager still has a connection to // the remote physics engine if (isConnected) { // Close the socket m_remoteSocket.Shutdown(SocketShutdown.Both); m_remoteSocket.Close(); } // Indicate that the manager should no longer be connected // to the remote physics engine in a thread-safe manner lock (m_connectedLock) { m_isConnected = false; } } /// <summary> /// Initialize basic information about packets that will be handled by /// the packet manager. /// </summary> /// <param name="headerSize">The size of a packet header in bytes. /// Must be non-zero</param> /// <param name="packetLengthOffset">The offset in the header /// (in bytes) at which the length of the packet resides. /// </param> public void InitializePacketParameters(uint headerSize, uint packetLengthOffset) { // Initialize the header length and packet length offset m_headerSize = headerSize; m_packetLengthOffset = packetLengthOffset; } /// <summary> /// Callback used to finish the connection process to the remote /// physics engine. /// </summary> /// <param name="remoteSocketObject">The socket object used to /// connect with the remote physics engine</param> protected void ConnectCallback(IAsyncResult remoteSocketObject) { Socket remoteSocket; bool connected; // Start off assuming that the connection operation succeeds in a // thread-safe manner lock (m_connectedLock) { m_isConnected = true; } // Obtain the socket object used to connect to the remote // physics engine remoteSocket = (Socket)remoteSocketObject.AsyncState; // Attempt to complete the connection operation try { // Signal that the connection process is complete remoteSocket.EndConnect(remoteSocketObject); } catch (SocketException socketExcpetion) { // Inform the user that the plugin has failed to connect to // the remote physics engine m_log.ErrorFormat("Unable to connect to " + "remote physics engine."); // Indicate that the connection attempt failed lock (m_connectedLock) { m_isConnected = false; } } // Check to see if the connection was successful lock (m_connectedLock) { connected = m_isConnected; } if (connected) { // Log the connection event m_log.InfoFormat("{0}: Connected to remote physics engine " + "at {1}", LogHeader, remoteSocket.RemoteEndPoint.ToString()); } // Unblock the execution of the packet manager's thread connectDone.Set(); } /// <summary> /// Callback used to finish a send operation to the remote /// physics engine. /// </summary> /// <param name="remoteSocketObject">The socket object used to /// connect with the remote physics engine</param> protected void SendCallback(IAsyncResult remoteSocketObject) { Socket remoteSocket; int bytesSent; // Obtain the socket object used to connect to the remote // physics engine remoteSocket = (Socket)remoteSocketObject.AsyncState; try { // Signal that the send operation is complete bytesSent = remoteSocket.EndSend(remoteSocketObject); } catch (SocketException socketExcpetion) { // Inform the user that the plugin has failed to connect to // the remote physics engine m_log.ErrorFormat("Unable to connect to " + "remote physics engine."); // Indicate that the connection attempt failed lock (m_connectedLock) { m_isConnected = false; } } // Indicate that the manager is ready to send the next packet m_sendReady = true; } /// <summary> /// Callback used to finish a receive operation from the remote /// physics engine. /// </summary> /// <param name="asyncResult">The socket object used to connect with /// the remote physics engine</param> protected void ReceiveCallback(IAsyncResult asyncResult) { Socket client; int bytesRead; byte[] newPacket; int packetCount; uint msgLen; byte[] tempBuf; bool connected; int readPos; bool doneReading; // Check to see if the manager is no longer connected, in a // thread-safe manner lock (m_connectedLock) { connected = m_isConnected; } // If the manager is not connected, exit out if (!connected) return; // Obtain the socket object used to connect to the remote // physics engine client = (Socket)asyncResult.AsyncState; bytesRead = 0; try { // Signal that the receive operation is complete and figure out // how many bytes were read bytesRead = client.EndReceive(asyncResult); } catch (SocketException socketExcpetion) { // Inform the user that the plugin has failed to connect to // the remote physics engine m_log.ErrorFormat("Unable to connect to " + "remote physics engine."); // Indicate that the connection attempt failed lock (m_connectedLock) { m_isConnected = false; } } // Acess the incoming stream and packet queue in a thread-safe // manner m_incomingMutex.WaitOne(); // Check to see if there is any data in the overflow readPos = 0; if (m_overflowWritePosition > 0) { // Check to see if there isn't enough data in the overflow // buffer for a header if (m_overflowWritePosition < m_headerSize) { // Copy enough data from the read buffer to form a header // in the overflow buffer Buffer.BlockCopy(m_readBuffer, (int) readPos, m_overflowBuffer, m_overflowWritePosition, (int) (m_headerSize - m_overflowWritePosition)); // Update the read position of the read buffer and write // position of overflow buffer readPos += (int) (m_headerSize - m_overflowWritePosition); m_overflowWritePosition += (int) (m_headerSize - m_overflowWritePosition); } // Check the length of packet stored in the overflow buffer msgLen = 0; msgLen = (uint) IPAddress.NetworkToHostOrder( BitConverter.ToInt32(m_overflowBuffer, (int) m_packetLengthOffset)); // Check to see if there is enough data now to read in the // rest of the message if (m_overflowWritePosition + bytesRead >= msgLen) { // Create a byte array to hold the new packet's data newPacket = new byte[msgLen]; // Copy the bytes from the overflow into the packet Buffer.BlockCopy(m_overflowBuffer, 0, newPacket, 0, m_overflowWritePosition); // Now copy the remainder of the message from the read // buffer Buffer.BlockCopy(m_readBuffer, (int) readPos, newPacket, (int) m_overflowWritePosition, (int) (msgLen - m_overflowWritePosition)); // Update the read position of the read buffer to account // for the bytes that were read above readPos += (int) (msgLen - m_overflowWritePosition); // Indicate that the overflow buffer is cleared m_overflowWritePosition = 0; } } // Check to see if enough bytes were read to process a header doneReading = false; while ((bytesRead - readPos) >= m_headerSize && !doneReading) { // Read in the length of the current packet // Make sure to convert the field to host byte order msgLen = 0; msgLen = (uint) IPAddress.NetworkToHostOrder( BitConverter.ToInt32(m_readBuffer, (int) (m_packetLengthOffset + readPos))); // Check to see if there is enough data in the read buffer // to process the entire message if ((bytesRead - readPos) >= msgLen) { // Create a byte array to hold the new packet's data newPacket = new byte[msgLen]; // Copy the bytes for the packet into the new byte array Buffer.BlockCopy(m_readBuffer, (int) readPos, newPacket, 0, (int) msgLen); // Queue up the new packet into the packet queue, such // that it can be consumed by the plugin m_incomingPackets.Enqueue(newPacket); // Move up the read position, now that message has been // processed readPos += (int) msgLen; } else { // Check to see if all the new data has not been consumed // Note that the read position is 0 indexed if ((bytesRead - readPos) > 0) { // Store the remaining data in the overflow buffer Buffer.BlockCopy(m_readBuffer, (int) readPos, m_overflowBuffer, m_overflowWritePosition, (int) (bytesRead - readPos)); // Update the amount of data stored in the overflow // buffer m_overflowWritePosition += (int) (bytesRead - readPos); } doneReading = true; } } // Check to see if all the new data has not been consumed and that // reading has not yet finished // Note that the read position is 0 indexed if ((bytesRead - readPos) > 0 && !doneReading) { // Store the remaining data in the overflow buffer Buffer.BlockCopy(m_readBuffer, (int) readPos, m_overflowBuffer, m_overflowWritePosition, (int) (bytesRead - readPos)); // Update the amount of data stored in the overflow buffer m_overflowWritePosition += (int) (bytesRead - readPos); } // Now that the data has been processed, release the lock on the // data m_incomingMutex.ReleaseMutex(); // Indicate that the manager is ready to receive the next packet m_receiveReady = true; } /// <summary> /// Sends a packet to the remote physics engine. /// </summary> /// <param name="packet">The byte array to be sent as a packet</param> public void SendPacket(byte[] packet) { // Enqueue the packet into the outgoing queue in a thread-safe // manner, so that it can be sent in subsequent updates m_outgoingMutex.WaitOne(); m_outgoingPackets.Enqueue(packet); m_outgoingMutex.ReleaseMutex(); } /// <summary> /// Fetch the next received packet. /// </summary> /// <returns>The next packet in the incoming packet. Null if there are /// no incoming packets</returns> public byte[] GetIncomingPacket() { byte[] incomingPacket; // Dequeue a packet from the incoming packet queue and return it // in a thread-safe manner incomingPacket = null; m_incomingMutex.WaitOne(); if (m_incomingPackets.Count > 0) incomingPacket = m_incomingPackets.Dequeue(); m_incomingMutex.ReleaseMutex(); // Return the fetched packet (even if it is null) return incomingPacket; } /// <summary> /// Indicates whether there are any packets that have been received. /// </summary> /// <returns>True if there are unprocessed packets that have been /// received; false if not</returns> public bool HasIncomingPacket() { // Check to see if the incoming packet queue has any packets // waiting to be read return (m_incomingPackets.Count > 0); } /// <summary> /// Regularly runs the update method for this messenger /// </summary> public void RunUpdate() { // Run the update until the stop flag indicates otherwise while (!m_stopUpdates) { Update(); // Sleep the thread to ensure that it doesn't hog resources // (maintain an update rate of apporximately 30 updates per // second) Thread.Sleep(30); } } /// <summary> /// The main update method for the packet manager. Called by the /// internal thread if one is used, and called by the owner of this /// manager if an internal thread is not used. /// </summary> public void Update() { byte[] curPacket; // Check to see if the packet manager has not successfully connected // to the remote physics engine if (!m_isConnected) { // No further operations can be performed, because there is // no connection to the remote physics engine return; } // Keep sending until there are no more messages to send or enough // of them have been sent in this cycle curPacket = null; int packetSentCount = 0; while (m_outgoingPackets.Count > 0 && packetSentCount < m_maxOutgoingPackets) { // Indicate that the manager has already started sending data, // and must wait before starting any additional send // operations beyond this one m_sendReady = false; // Retrieve the next packet in the queue in a thread-safe manner m_outgoingMutex.WaitOne(); curPacket = m_outgoingPackets.Dequeue(); m_outgoingMutex.ReleaseMutex(); try { // Start the non-blocking send operation for the dequeued // outgoing packet m_remoteSocket.BeginSend(curPacket, 0, curPacket.Length, 0, new AsyncCallback(SendCallback), m_remoteSocket); } catch (SocketException socketExcpetion) { // Inform the user that the plugin has failed to connect to // the remote physics engine m_log.ErrorFormat("Unable to connect to " + "remote physics engine."); // Indicate that the connection attempt failed lock (m_connectedLock) { m_isConnected = false; } } // Update the number of sent packets packetSentCount++; } // Check to see if the manager is ready to receive more data if (m_receiveReady) { // Indicate that the manager has already started receiving data, // and must wait before starting any additional recieve // operations beyond this one m_receiveReady = false; try { // Begin a receive operation; the operation will be // completed in the callback that is passed in m_remoteSocket.BeginReceive(m_readBuffer, 0, m_readBuffer.Length, 0, new AsyncCallback(ReceiveCallback), m_remoteSocket); } catch (SocketException socketExcpetion) { // Inform the user that the plugin has failed to connect to // the remote physics engine m_log.ErrorFormat("Unable to connect to " + "remote physics engine."); // Indicate that the connection attempt failed lock (m_connectedLock) { m_isConnected = false; } } } } /// <summary> /// Stops the update thread, if one is being by the messenger. /// </summary> protected void StopUpdates() { // Set the flag indicating that the update thread should stop m_stopUpdates = true; } } }
using System; using System.Drawing; using System.Xml; using System.Xml.Serialization; using System.Collections; using System.Reflection; using System.IO; using System.Diagnostics; using System.Xml.Schema; namespace Netron.Lithium { /// <summary> /// Assists the serialization of the diagram /// </summary> public class GraphSerializer { #region Fields /// <summary> /// the key/value pairs of to-be stored xml entries /// </summary> private Hashtable keyList = new Hashtable(); /// <summary> /// the control this serializer is attached to /// </summary> private LithiumControl site; #endregion #region Constructor /// <summary> /// Default ctor /// </summary> /// <param name="control"></param> public GraphSerializer(LithiumControl control) { site = control; } #endregion #region Methods /// <summary> /// Serializes the given graph to xml /// </summary> public void Serialize(XmlWriter writer) { GraphType graph = new GraphType(); GraphAbstract g = site.graphAbstract; //here you can serialize whatever global pros graph.Description = g.Description; graph.ID = "id1"; foreach ( ShapeBase s in g.Shapes ) { graph.Nodes.Add(SerializeNode(s)); } foreach(Connection c in g.Connections) { graph.Edges.Add(SerializeEdge(c)); } // serialize XmlSerializer ser = new XmlSerializer(typeof(GraphType)); ser.Serialize(writer,graph); } /// <summary> /// Deserializes the graph's xml /// </summary> /// <returns></returns> public GraphAbstract Deserialize(XmlReader reader) { XmlSerializer ser = new XmlSerializer(typeof(GraphType)); GraphType gtype = ser.Deserialize(reader) as GraphType; return Deserialize(gtype); } /// <summary> /// Deserializes the graphtype /// </summary> /// <param name="g">the graphtype which acts as an intermediate storage between XML and the GraphAbstract /// </param> /// <returns></returns> private GraphAbstract Deserialize(GraphType g) { GraphAbstract abs = new GraphAbstract(); abs.Description = g.Description; ShapeBase shape = null, from = null, to = null; NodeType node; DataType dt; Connection con; ParentChildCollection pcs = new ParentChildCollection(); //temporary store for parent-child relations #region Load the nodes for(int k =0; k<g.Nodes.Count;k++) //loop over all serialized nodes { try { #region find out which type of shape needs to be instantiated node = g.Nodes[k] as NodeType; Type shapeType = Type.GetType(node.Type); if (shapeType != null) { object[] args = {this.site}; shape = Activator.CreateInstance(shapeType, args) as ShapeBase; } #endregion #region use the attribs again to reconstruct the props for(int m=0; m<node.Items.Count;m++) //loop over the serialized data { dt = node.Items[m] as DataType; if(dt.Key=="ParentNode") { //forget the parenting, it's done in a separate loop to be sure all shapes are loaded if(dt.Text.Count>0) //could be if the shape is the root pcs.Add(new ParentChild(shape, dt.Text[0].ToString())); else { shape.IsRoot = true; abs.Root = shape; } continue; } foreach (PropertyInfo pi in shape.GetType().GetProperties()) { if (Attribute.IsDefined(pi, typeof(GraphDataAttribute))) { if(pi.Name==dt.Key) { if(pi.GetIndexParameters().Length==0) { if(pi.PropertyType.Equals(typeof(int))) pi.SetValue(shape,Convert.ToInt32(dt.Text[0]),null); else if(pi.PropertyType.Equals(typeof(Color))) //Color is stored as an integer pi.SetValue(shape,Color.FromArgb(int.Parse(dt.Text[0].ToString())),null); else if(pi.PropertyType.Equals(typeof(string))) pi.SetValue(shape,(string)(dt.Text[0]),null); else if(pi.PropertyType.Equals(typeof(bool))) pi.SetValue(shape,Convert.ToBoolean(dt.Text[0]),null); else if(pi.PropertyType.Equals(typeof(Guid))) pi.SetValue(shape,new Guid((string) dt.Text[0]),null); } else pi.SetValue(shape,dt.Text,null); break; } } } } #endregion shape.Font = site.Font; shape.Fit(); abs.Shapes.Add(shape); } catch(Exception exc) { Trace.WriteLine(exc.Message); continue; } }//loop over nodes #endregion //now for the edges; //every node has precisely one parent and one connection to it, unless it's the root for(int n=0; n<pcs.Count; n++) { from = pcs[n].ChildShape; to = abs.Shapes[pcs[n].Parent]; con = new Connection(from, to ); abs.Connections.Add(con); con.site = site; if(pcs[n].ChildShape.visible) con.visible = true; from.connection = con; //a lot of crossing...to make life easy really from.parentNode =to; to.childNodes.Add(from); } return abs; } /// <summary> /// Serializes the given shape to xml /// </summary> /// <param name="s"></param> /// <returns></returns> private NodeType SerializeNode(ShapeBase s) { Hashtable attributes = GraphDataAttribute.GetValuesOfTaggedFields(s); NodeType node = new NodeType(); //node.ID = FormatID(s); //node.Items.Add(DataTypeFromEntity(s)); if(typeof(OvalShape).IsInstanceOfType(s)) node.Type = "Netron.Lithium.OvalShape"; else if(typeof(SimpleRectangle).IsInstanceOfType(s)) node.Type = "Netron.Lithium.SimpleRectangle"; else if(typeof(TextLabel).IsInstanceOfType(s)) node.Type = "Netron.Lithium.TextLabel"; foreach(DataType data in DataTypesFromAttributes(attributes)) { node.Items.Add(data); } return node; } /// <summary> /// Serializes a diagram edge /// </summary> /// <param name="c"></param> /// <returns></returns> private EdgeType SerializeEdge(Connection c) { Hashtable attributes = GraphDataAttribute.GetValuesOfTaggedFields(c); EdgeType edge = new EdgeType(); //edge.Source = c.From.Text; //edge.Target = c.To.Text; edge.From = c.From.UID.ToString(); edge.To = c.To.UID.ToString(); //since there is only one type of edge we don't need the next one //edge.Data.Add(DataTypeFromEntity(c)); foreach(DataType dt in DataTypesFromAttributes(attributes)) { edge.Data.Add(dt); } return edge; } /// <summary> /// Returns the UID in string format of the given entity /// </summary> /// <param name="e">an Entity object</param> /// <returns>the UID as string</returns> private string FormatID(Entity e) { if(e==null) return string.Empty; else return string.Format("e{0}",e.UID.ToString()); } /// <summary> /// Converts the set of key/Values to a DataType array /// </summary> /// <param name="attributes">an Hastable of key/value pairs</param> /// <returns>An array of DataTypes </returns> private DataType[] DataTypesFromAttributes(Hashtable attributes) { DataType[] dts = new DataType[attributes.Count]; int i = 0; foreach ( DictionaryEntry de in attributes ) { dts[i] = new DataType(); dts[i].Key = de.Key.ToString(); if (de.Value != null) { //the color is a bit different if(typeof(Color).IsInstanceOfType(de.Value)) { int val = ((Color) de.Value).ToArgb(); dts[i].Text.Add(val.ToString()); } else if(typeof(ShapeBase).IsInstanceOfType(de.Value)) { dts[i].Text.Add((de.Value as ShapeBase).UID.ToString()); } else if(typeof(Guid).IsInstanceOfType(de.Value)) { dts[i].Text.Add(((Guid) de.Value ).ToString()); } else dts[i].Text.Add(de.Value.ToString()); } if ( !keyList.Contains(de.Key.ToString())) keyList.Add(de.Key.ToString(),de.Value); ++i; } return dts; } /// <summary> /// Returns qualified type name of o /// </summary> /// <param name="o"></param> /// <returns></returns> private string GetTypeQualifiedName(Object o) { if (o==null) throw new ArgumentNullException("o"); return this.GetTypeQualifiedName(o.GetType()); } /// <summary> /// Creates the name of a type qualified by the display name of its assembly. /// </summary> /// <param name="t"></param> /// <returns></returns> private string GetTypeQualifiedName(Type t) { return Assembly.CreateQualifiedName( t.Assembly.FullName, t.FullName ); } private Type ToType(string text) { return Type.GetType(text,true); } private bool ToBool(string text) { return bool.Parse(text); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Net.Test.Common; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.NetworkInformation.Tests { public class PingTest { private class FinalizingPing : Ping { public static volatile bool WasFinalized; public static void CreateAndRelease() { new FinalizingPing(); } protected override void Dispose(bool disposing) { if (!disposing) { WasFinalized = true; } base.Dispose(disposing); } } [Fact] public async Task SendPingAsync_InvalidArgs() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); Ping p = new Ping(); // Null address Assert.Throws<ArgumentNullException>("address", () => { p.SendPingAsync((IPAddress)null); }); Assert.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.SendPingAsync((string)null); }); Assert.Throws<ArgumentNullException>("address", () => { p.SendAsync((IPAddress)null, null); }); Assert.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.SendAsync((string)null, null); }); Assert.Throws<ArgumentNullException>("address", () => { p.Send((IPAddress)null); }); Assert.Throws<ArgumentNullException>("hostNameOrAddress", () => { p.Send((string)null); }); // Invalid address Assert.Throws<ArgumentException>("address", () => { p.SendPingAsync(IPAddress.Any); }); Assert.Throws<ArgumentException>("address", () => { p.SendPingAsync(IPAddress.IPv6Any); }); Assert.Throws<ArgumentException>("address", () => { p.SendAsync(IPAddress.Any, null); }); Assert.Throws<ArgumentException>("address", () => { p.SendAsync(IPAddress.IPv6Any, null); }); Assert.Throws<ArgumentException>("address", () => { p.Send(IPAddress.Any); }); Assert.Throws<ArgumentException>("address", () => { p.Send(IPAddress.IPv6Any); }); // Negative timeout Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(localIpAddress, -1); }); Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendPingAsync(TestSettings.LocalHost, -1); }); Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(localIpAddress, -1, null); }); Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.SendAsync(TestSettings.LocalHost, -1, null); }); Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.Send(localIpAddress, -1); }); Assert.Throws<ArgumentOutOfRangeException>("timeout", () => { p.Send(TestSettings.LocalHost, -1); }); // Null byte[] Assert.Throws<ArgumentNullException>("buffer", () => { p.SendPingAsync(localIpAddress, 0, null); }); Assert.Throws<ArgumentNullException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 0, null); }); Assert.Throws<ArgumentNullException>("buffer", () => { p.SendAsync(localIpAddress, 0, null, null); }); Assert.Throws<ArgumentNullException>("buffer", () => { p.SendAsync(TestSettings.LocalHost, 0, null, null); }); Assert.Throws<ArgumentNullException>("buffer", () => { p.Send(localIpAddress, 0, null); }); Assert.Throws<ArgumentNullException>("buffer", () => { p.Send(TestSettings.LocalHost, 0, null); }); // Too large byte[] Assert.Throws<ArgumentException>("buffer", () => { p.SendPingAsync(localIpAddress, 1, new byte[65501]); }); Assert.Throws<ArgumentException>("buffer", () => { p.SendPingAsync(TestSettings.LocalHost, 1, new byte[65501]); }); Assert.Throws<ArgumentException>("buffer", () => { p.SendAsync(localIpAddress, 1, new byte[65501], null); }); Assert.Throws<ArgumentException>("buffer", () => { p.SendAsync(TestSettings.LocalHost, 1, new byte[65501], null); }); Assert.Throws<ArgumentException>("buffer", () => { p.Send(localIpAddress, 1, new byte[65501]); }); Assert.Throws<ArgumentException>("buffer", () => { p.Send(TestSettings.LocalHost, 1, new byte[65501]); }); } [Fact] public async Task SendPingAsyncWithIPAddress() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); }); } [Fact] public async Task SendPingAsyncWithIPAddress_AddressAsString() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress.ToString()), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); }); } [Fact] public async Task SendPingAsyncWithIPAddressAndTimeout() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); }); } [PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer() { byte[] buffer = TestSettings.PayloadAsBytes; IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); Assert.Equal(buffer, pingReply.Buffer); }); } [PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithIPAddressAndTimeoutAndBuffer_Unix() { byte[] buffer = TestSettings.PayloadAsBytes; IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. if (Capability.CanUseRawSockets(localIpAddress.AddressFamily)) { Assert.Equal(buffer, pingReply.Buffer); } else { Assert.Equal(Array.Empty<byte>(), pingReply.Buffer); } }); } [PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); var options = new PingOptions(); byte[] buffer = TestSettings.PayloadAsBytes; await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, options), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); Assert.Equal(buffer, pingReply.Buffer); Assert.InRange(pingReply.RoundtripTime, 0, long.MaxValue); }); } [PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithIPAddressAndTimeoutAndBufferAndPingOptions_Unix() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); byte[] buffer = TestSettings.PayloadAsBytes; await SendBatchPingAsync( (ping) => ping.SendPingAsync(localIpAddress, TestSettings.PingTimeout, buffer, new PingOptions()), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. if (Capability.CanUseRawSockets(localIpAddress.AddressFamily)) { Assert.Equal(buffer, pingReply.Buffer); } else { Assert.Equal(Array.Empty<byte>(), pingReply.Buffer); } }); } [Fact] public async Task SendPingAsyncWithHost() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(TestSettings.LocalHost), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); }); } [Fact] public async Task SendPingAsyncWithHostAndTimeout() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); await SendBatchPingAsync( (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); }); } [PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithHostAndTimeoutAndBuffer() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); byte[] buffer = TestSettings.PayloadAsBytes; await SendBatchPingAsync( (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); Assert.Equal(buffer, pingReply.Buffer); }); } [PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithHostAndTimeoutAndBuffer_Unix() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); byte[] buffer = TestSettings.PayloadAsBytes; await SendBatchPingAsync( (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. if (Capability.CanUseRawSockets(localIpAddress.AddressFamily)) { Assert.Equal(buffer, pingReply.Buffer); } else { Assert.Equal(Array.Empty<byte>(), pingReply.Buffer); } }); } [PlatformSpecific(TestPlatforms.Windows)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithHostAndTimeoutAndBufferAndPingOptions() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); byte[] buffer = TestSettings.PayloadAsBytes; await SendBatchPingAsync( (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); Assert.Equal(buffer, pingReply.Buffer); }); } [PlatformSpecific(TestPlatforms.AnyUnix)] // On Unix, Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. [Fact] public async Task SendPingAsyncWithHostAndTimeoutAndBufferAndPingOptions_Unix() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); byte[] buffer = TestSettings.PayloadAsBytes; await SendBatchPingAsync( (ping) => ping.SendPingAsync(TestSettings.LocalHost, TestSettings.PingTimeout, buffer, new PingOptions()), (pingReply) => { Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); // Non-root pings cannot send arbitrary data in the buffer, and do not receive it back in the PingReply. if (Capability.CanUseRawSockets(localIpAddress.AddressFamily)) { Assert.Equal(buffer, pingReply.Buffer); } else { Assert.Equal(Array.Empty<byte>(), pingReply.Buffer); } }); } [Fact] public static async Task SendPings_ReuseInstance_Hostname() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); using (Ping p = new Ping()) { for (int i = 0; i < 3; i++) { PingReply pingReply = await p.SendPingAsync(TestSettings.LocalHost); Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); } } } [Fact] public static async Task Sends_ReuseInstance_Hostname() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); using (Ping p = new Ping()) { for (int i = 0; i < 3; i++) { PingReply pingReply = p.Send(TestSettings.LocalHost); Assert.Equal(IPStatus.Success, pingReply.Status); Assert.True(pingReply.Address.Equals(localIpAddress)); } } } [Fact] public static async Task SendAsyncs_ReuseInstance_Hostname() { IPAddress localIpAddress = await TestSettings.GetLocalIPAddress(); using (Ping p = new Ping()) { TaskCompletionSource<bool> tcs = null; PingCompletedEventArgs ea = null; p.PingCompleted += (s, e) => { ea = e; tcs.TrySetResult(true); }; Action reset = () => { ea = null; tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously); }; // Several normal iterations for (int i = 0; i < 3; i++) { reset(); p.SendAsync(TestSettings.LocalHost, null); await tcs.Task; Assert.NotNull(ea); Assert.Equal(IPStatus.Success, ea.Reply.Status); Assert.True(ea.Reply.Address.Equals(localIpAddress)); } // Several canceled iterations for (int i = 0; i < 3; i++) { reset(); p.SendAsync(TestSettings.LocalHost, null); p.SendAsyncCancel(); // will block until operation can be started again } await tcs.Task; Assert.True(ea.Cancelled ^ (ea.Error != null) ^ (ea.Reply != null)); } } [Fact] public static async Task Ping_DisposeAfterSend_Success() { Ping p = new Ping(); await p.SendPingAsync(TestSettings.LocalHost); p.Dispose(); } [Fact] public static void Ping_DisposeMultipletimes_Success() { Ping p = new Ping(); p.Dispose(); p.Dispose(); } [Fact] public static void Ping_SendAfterDispose_ThrowsSynchronously() { Ping p = new Ping(); p.Dispose(); Assert.Throws<ObjectDisposedException>(() => { p.SendPingAsync(TestSettings.LocalHost); }); } private static readonly int s_pingcount = 4; private static Task SendBatchPingAsync(Func<Ping, Task<PingReply>> sendPing, Action<PingReply> pingResultValidator) { // create several concurrent pings Task[] pingTasks = new Task[s_pingcount]; for (int i = 0; i < s_pingcount; i++) { pingTasks[i] = SendPingAsync(sendPing, pingResultValidator); } return Task.WhenAll(pingTasks); } private static async Task SendPingAsync(Func<Ping, Task<PingReply>> sendPing, Action<PingReply> pingResultValidator) { var pingResult = await sendPing(new Ping()); pingResultValidator(pingResult); } [Fact] public void CanBeFinalized() { FinalizingPing.CreateAndRelease(); GC.Collect(); GC.WaitForPendingFinalizers(); Assert.True(FinalizingPing.WasFinalized); } } }
// ========================================================== // FreeImage 3 .NET wrapper // Original FreeImage 3 functions and .NET compatible derived functions // // Design and implementation by // - Jean-Philippe Goerke ([email protected]) // - Carsten Klein ([email protected]) // // Contributors: // - David Boland ([email protected]) // // Main reference : MSDN Knowlede Base // // This file is part of FreeImage 3 // // COVERED CODE IS PROVIDED UNDER THIS LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTY // OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES // THAT THE COVERED CODE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE // OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED // CODE IS WITH YOU. SHOULD ANY COVERED CODE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT // THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY // SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL // PART OF THIS LICENSE. NO USE OF ANY COVERED CODE IS AUTHORIZED HEREUNDER EXCEPT UNDER // THIS DISCLAIMER. // // Use at your own risk! // ========================================================== // ========================================================== // CVS // $Revision: 1.7 $ // $Date: 2009/02/27 16:34:59 $ // $Id: ImageMetadata.cs,v 1.7 2009/02/27 16:34:59 cklein05 Exp $ // ========================================================== using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Diagnostics; namespace FreeImageAPI.Metadata { /// <summary> /// Class handling metadata of a FreeImage bitmap. /// </summary> public class ImageMetadata : IEnumerable, IComparable, IComparable<ImageMetadata> { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly List<MetadataModel> data; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private readonly FIBITMAP dib; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private bool hideEmptyModels; /// <summary> /// Initializes a new instance based on the specified <see cref="FIBITMAP"/>, /// showing all known models. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> public ImageMetadata(FIBITMAP dib) : this(dib, false) { } /// <summary> /// Initializes a new instance based on the specified <see cref="FIBITMAP"/>, /// showing or hiding empry models. /// </summary> /// <param name="dib">Handle to a FreeImage bitmap.</param> /// <param name="hideEmptyModels">When <b>true</b>, empty metadata models /// will be hidden until a tag to this model is added.</param> public ImageMetadata(FIBITMAP dib, bool hideEmptyModels) { if (dib.IsNull) throw new ArgumentNullException("dib"); data = new List<MetadataModel>(FreeImage.FREE_IMAGE_MDMODELS.Length); this.dib = dib; this.hideEmptyModels = hideEmptyModels; data.Add(new MDM_ANIMATION(dib)); data.Add(new MDM_COMMENTS(dib)); data.Add(new MDM_CUSTOM(dib)); data.Add(new MDM_EXIF_EXIF(dib)); data.Add(new MDM_EXIF_GPS(dib)); data.Add(new MDM_INTEROP(dib)); data.Add(new MDM_EXIF_MAIN(dib)); data.Add(new MDM_MAKERNOTE(dib)); data.Add(new MDM_GEOTIFF(dib)); data.Add(new MDM_IPTC(dib)); data.Add(new MDM_NODATA(dib)); data.Add(new MDM_XMP(dib)); } /// <summary> /// Gets or sets the <see cref="MetadataModel"/> of the specified type. /// <para>In case the getter returns <c>null</c> the model is not contained /// by the list.</para> /// <para><c>null</c> can be used calling the setter to destroy the model.</para> /// </summary> /// <param name="model">Type of the model.</param> /// <returns>The <see cref="FreeImageAPI.Metadata.MetadataModel"/> object of the specified type.</returns> public MetadataModel this[FREE_IMAGE_MDMODEL model] { get { for (int i = 0; i < data.Count; i++) { if (data[i].Model == model) { if (!data[i].Exists && hideEmptyModels) { return null; } return data[i]; } } return null; } } /// <summary> /// Gets or sets the <see cref="FreeImageAPI.Metadata.MetadataModel"/> at the specified index. /// <para>In case the getter returns <c>null</c> the model is not contained /// by the list.</para> /// <para><c>null</c> can be used calling the setter to destroy the model.</para> /// </summary> /// <param name="index">Index of the <see cref="FreeImageAPI.Metadata.MetadataModel"/> within /// this instance.</param> /// <returns>The <see cref="FreeImageAPI.Metadata.MetadataModel"/> /// object at the specified index.</returns> public MetadataModel this[int index] { get { if (index < 0 || index >= data.Count) { throw new ArgumentOutOfRangeException("index"); } return (hideEmptyModels && !data[index].Exists) ? null : data[index]; } } /// <summary> /// Returns a list of all visible /// <see cref="FreeImageAPI.Metadata.MetadataModel">MetadataModels</see>. /// </summary> public List<MetadataModel> List { get { if (hideEmptyModels) { List<MetadataModel> result = new List<MetadataModel>(); for (int i = 0; i < data.Count; i++) { if (data[i].Exists) { result.Add(data[i]); } } return result; } else { return data; } } } /// <summary> /// Adds new tag to the bitmap or updates its value in case it already exists. /// <see cref="FreeImageAPI.Metadata.MetadataTag.Key"/> will be used as key. /// </summary> /// <param name="tag">The tag to add or update.</param> /// <returns>Returns true on success, false on failure.</returns> /// <exception cref="ArgumentNullException"> /// <paramref name="tag"/> is null.</exception> public bool AddTag(MetadataTag tag) { for (int i = 0; i < data.Count; i++) { if (tag.Model == data[i].Model) { return data[i].AddTag(tag); } } return false; } /// <summary> /// Returns the number of visible /// <see cref="FreeImageAPI.Metadata.MetadataModel">MetadataModels</see>. /// </summary> public int Count { get { if (hideEmptyModels) { int count = 0; for (int i = 0; i < data.Count; i++) { if (data[i].Exists) { count++; } } return count; } else { return data.Count; } } } /// <summary> /// Gets or sets whether empty /// <see cref="FreeImageAPI.Metadata.MetadataModel">MetadataModels</see> are hidden. /// </summary> public bool HideEmptyModels { get { return hideEmptyModels; } set { hideEmptyModels = value; } } /// <summary> /// Retrieves an object that can iterate through the individual /// <see cref="FreeImageAPI.Metadata.MetadataModel">MetadataModels</see> /// in this <see cref="ImageMetadata"/>. /// </summary> /// <returns>An <see cref="IEnumerator"/> for this <see cref="ImageMetadata"/>.</returns> public IEnumerator GetEnumerator() { if (hideEmptyModels) { List<MetadataModel> tempList = new List<MetadataModel>(data.Count); for (int i = 0; i < data.Count; i++) { if (data[i].Exists) { tempList.Add(data[i]); } } return tempList.GetEnumerator(); } else { return data.GetEnumerator(); } } /// <summary> /// Compares this instance with a specified <see cref="Object"/>. /// </summary> /// <param name="obj">An object to compare with this instance.</param> /// <returns>A 32-bit signed integer indicating the lexical relationship between the two comparands.</returns> /// <exception cref="ArgumentException"><paramref name="obj"/> is not a <see cref="ImageMetadata"/>.</exception> public int CompareTo(object obj) { if (obj == null) { return 1; } if (!(obj is ImageMetadata)) { throw new ArgumentException("obj"); } return CompareTo((ImageMetadata)obj); } /// <summary> /// Compares this instance with a specified <see cref="ImageMetadata"/> object. /// </summary> /// <param name="other">A <see cref="ImageMetadata"/> to compare.</param> /// <returns>A signed number indicating the relative values of this instance /// and <paramref name="other"/>.</returns> public int CompareTo(ImageMetadata other) { return this.dib.CompareTo(other.dib); } } }
using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Linq; namespace DotNetShipping.ShippingProviders { /// <summary> /// </summary> public class USPSInternationalProvider : AbstractShippingProvider { private const string PRODUCTION_URL = "http://production.shippingapis.com/ShippingAPI.dll"; private readonly string _service; private readonly string _userId; private readonly Dictionary<string, string> _serviceCodes = new Dictionary<string, string> { {"Priority Mail Express International","Priority Mail Express International"}, {"Priority Mail International","Priority Mail International"}, {"Global Express Guaranteed (GXG)","Global Express Guaranteed (GXG)"}, {"Global Express Guaranteed Document","Global Express Guaranteed Document"}, {"Global Express Guaranteed Non-Document Rectangular","Global Express Guaranteed Non-Document Rectangular"}, {"Global Express Guaranteed Non-Document Non-Rectangular","Global Express Guaranteed Non-Document Non-Rectangular"}, {"Priority Mail International Flat Rate Envelope","Priority Mail International Flat Rate Envelope"}, {"Priority Mail International Medium Flat Rate Box","Priority Mail International Medium Flat Rate Box"}, {"Priority Mail Express International Flat Rate Envelope","Priority Mail Express International Flat Rate Envelope"}, {"Priority Mail International Large Flat Rate Box","Priority Mail International Large Flat Rate Box"}, {"USPS GXG Envelopes","USPS GXG Envelopes"}, {"First-Class Mail International Letter","First-Class Mail International Letter"}, {"First-Class Mail International Large Envelope","First-Class Mail International Large Envelope"}, {"First-Class Package International Service","First-Class Package International Service"}, {"Priority Mail International Small Flat Rate Box","Priority Mail International Small Flat Rate Box"}, {"Priority Mail Express International Legal Flat Rate Envelope","Priority Mail Express International Legal Flat Rate Envelope"}, {"Priority Mail International Gift Card Flat Rate Envelope","Priority Mail International Gift Card Flat Rate Envelope"}, {"Priority Mail International Window Flat Rate Envelope","Priority Mail International Window Flat Rate Envelope"}, {"Priority Mail International Small Flat Rate Envelope","Priority Mail International Small Flat Rate Envelope"}, {"First-Class Mail International Postcard","First-Class Mail International Postcard"}, {"Priority Mail International Legal Flat Rate Envelope","Priority Mail International Legal Flat Rate Envelope"}, {"Priority Mail International Padded Flat Rate Envelope","Priority Mail International Padded Flat Rate Envelope"}, {"Priority Mail International DVD Flat Rate priced box","Priority Mail International DVD Flat Rate priced box"}, {"Priority Mail International Large Video Flat Rate priced box","Priority Mail International Large Video Flat Rate priced box"}, {"Priority Mail Express International Flat Rate Boxes","Priority Mail Express International Flat Rate Boxes"}, {"Priority Mail Express International Padded Flat Rate Envelope","Priority Mail Express International Padded Flat Rate Envelope"} }; public USPSInternationalProvider() { Name = "USPS"; _userId = ConfigurationManager.AppSettings["USPSUserId"]; _service = "ALL"; } /// <summary> /// </summary> /// <param name="userId"></param> public USPSInternationalProvider(string userId) { Name = "USPS"; _userId = userId; _service = "ALL"; } /// <summary> /// </summary> /// <param name="userId"></param> public USPSInternationalProvider(string userId, string service) { Name = "USPS"; _userId = userId; _service = service; } public bool Commercial { get; set; } /// <summary> /// Returns the supported service codes /// </summary> /// <returns></returns> public IDictionary<string, string> GetServiceCodes() { if (_serviceCodes != null && _serviceCodes.Count > 0) { var serviceCodes = new Dictionary<string, string>(); foreach (var serviceCodeKey in _serviceCodes.Keys) { var serviceCode = _serviceCodes[serviceCodeKey]; serviceCodes.Add(serviceCodeKey, serviceCode); } return serviceCodes; } return null; } public override void GetRates() { var sb = new StringBuilder(); var settings = new XmlWriterSettings(); settings.Indent = false; settings.OmitXmlDeclaration = true; settings.NewLineHandling = NewLineHandling.None; using (var writer = XmlWriter.Create(sb, settings)) { writer.WriteStartElement("IntlRateV2Request"); writer.WriteAttributeString("USERID", _userId); writer.WriteElementString("Revision", "2"); var i = 0; foreach (var package in Shipment.Packages) { //<Package ID="2ND"> // <Pounds>0</Pounds> // <Ounces>3</Ounces> // <MailType>Envelope</MailType> // <ValueOfContents>750</ValueOfContents> // <Country>Algeria</Country> // <Container></Container> // <Size>REGULAR</Size> // <Width></Width> // <Length></Length> // <Height></Height> // <Girth></Girth> // <CommercialFlag>N</CommercialFlag> //</Package> writer.WriteStartElement("Package"); writer.WriteAttributeString("ID", i.ToString()); writer.WriteElementString("Pounds", package.PoundsAndOunces.Pounds.ToString()); writer.WriteElementString("Ounces", package.PoundsAndOunces.Ounces.ToString()); writer.WriteElementString("MailType", "Package"); writer.WriteElementString("ValueOfContents", package.InsuredValue < 0 ? package.InsuredValue.ToString() : "100"); //todo: figure out best way to come up with insured value writer.WriteElementString("Country", Shipment.DestinationAddress.GetCountryName()); writer.WriteElementString("Container", "RECTANGULAR"); writer.WriteElementString("Size", "REGULAR"); writer.WriteElementString("Width", package.RoundedWidth.ToString()); writer.WriteElementString("Length", package.RoundedLength.ToString()); writer.WriteElementString("Height", package.RoundedHeight.ToString()); writer.WriteElementString("Girth", package.CalculatedGirth.ToString()); writer.WriteElementString("OriginZip", Shipment.OriginAddress.PostalCode); writer.WriteElementString("CommercialFlag", Commercial ? "Y" : "N"); //TODO: Figure out DIM Weights //writer.WriteElementString("Size", package.IsOversize ? "LARGE" : "REGULAR"); //writer.WriteElementString("Length", package.RoundedLength.ToString()); //writer.WriteElementString("Width", package.RoundedWidth.ToString()); //writer.WriteElementString("Height", package.RoundedHeight.ToString()); //writer.WriteElementString("Girth", package.CalculatedGirth.ToString()); i++; writer.WriteEndElement(); } writer.WriteEndElement(); writer.Flush(); } try { var url = string.Concat(PRODUCTION_URL, "?API=IntlRateV2&XML=", sb.ToString()); var webClient = new WebClient(); var response = webClient.DownloadString(url); ParseResult(response); } catch (Exception ex) { Debug.WriteLine(ex); } } public bool IsDomesticUSPSAvailable() { return Shipment.OriginAddress.IsUnitedStatesAddress() && Shipment.DestinationAddress.IsUnitedStatesAddress(); } private void ParseResult(string response) { var document = XDocument.Load(new StringReader(response)); var rates = document.Descendants("Service").GroupBy(item => (string) item.Element("SvcDescription")).Select(g => new {Name = g.Key, TotalCharges = g.Sum(x => Decimal.Parse((string) x.Element("Postage")))}); if (_service == "ALL") { foreach (var r in rates) { var name = Regex.Replace(r.Name, "&lt.*gt;", ""); AddRate(name, string.Concat("USPS ", name), r.TotalCharges, DateTime.Now.AddDays(30)); } } else { foreach (var r in rates) { var name = Regex.Replace(r.Name, "&lt.*gt;", ""); if (_service == name) { AddRate(name, string.Concat("USPS ", name), r.TotalCharges, DateTime.Now.AddDays(30)); } } } //check for errors if (document.Descendants("Error").Any()) { var errors = from item in document.Descendants("Error") select new USPSError { Description = item.Element("Description").ToString(), Source = item.Element("Source").ToString(), HelpContext = item.Element("HelpContext").ToString(), HelpFile = item.Element("HelpFile").ToString(), Number = item.Element("Number").ToString() }; foreach (var err in errors) { AddError(err); } } } } }
using Microsoft.Azure.ApplicationInsights.Query.Models; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.ApplicationInsights.Query { public partial class MetricsExtensions { #region Metric Extensions /// <summary> /// Retrieve summary metric data /// </summary> /// <remarks> /// Gets summary metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> public static MetricsSummaryResult GetMetricSummary(this IMetrics operations, string appId, string metricId, string timespan = default(string), IList<string> aggregation = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string)) { return operations.GetMetricSummaryAsync(appId, metricId, timespan, aggregation, top, orderby, filter).GetAwaiter().GetResult(); } /// <summary> /// Retrieve summary metric data /// </summary> /// <remarks> /// Gets summary metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MetricsSummaryResult> GetMetricSummaryAsync(this IMetrics operations, string appId, string metricId, string timespan = default(string), IList<string> aggregation = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var result = await operations.GetMetricSummaryWithHttpMessagesAsync(appId, metricId, timespan, aggregation, top, orderby, filter, null, cancellationToken).ConfigureAwait(false)) { return result.Body; } } /// <summary> /// Retrieve metric data /// </summary> /// <remarks> /// Gets metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='interval'> /// The time interval to use when retrieving metric values. This is an /// ISO8601 duration. If interval is omitted, the metric value is /// aggregated across the entire timespan. If interval is supplied, the /// server may adjust the interval to a more appropriate size based on /// the timespan used for the query. In all cases, the actual interval /// used for the query is included in the response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='segment'> /// The name of the dimension to segment the metric values by. This /// dimension must be applicable to the metric you are retrieving. To /// segment by more than one dimension at a time, separate them with a /// comma (,). In this case, the metric data will be segmented in the /// order the dimensions are listed in the parameter. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> public static MetricsIntervaledResult GetIntervaledMetric(this IMetrics operations, string appId, string metricId, string timespan = default(string), System.TimeSpan? interval = default(System.TimeSpan?), IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string)) { return operations .GetIntervaledMetricAsync(appId, metricId, timespan, interval, aggregation, segment, top, orderby, filter) .GetAwaiter().GetResult(); } /// <summary> /// Retrieve metric data /// </summary> /// <remarks> /// Gets metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='interval'> /// The time interval to use when retrieving metric values. This is an /// ISO8601 duration. If interval is omitted, the metric value is /// aggregated across the entire timespan. If interval is supplied, the /// server may adjust the interval to a more appropriate size based on /// the timespan used for the query. In all cases, the actual interval /// used for the query is included in the response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='segment'> /// The name of the dimension to segment the metric values by. This /// dimension must be applicable to the metric you are retrieving. To /// segment by more than one dimension at a time, separate them with a /// comma (,). In this case, the metric data will be segmented in the /// order the dimensions are listed in the parameter. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MetricsIntervaledResult> GetIntervaledMetricAsync(this IMetrics operations, string appId, string metricId, string timespan = default(string), System.TimeSpan? interval = default(System.TimeSpan?), IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var result = await operations.GetIntervaledMetricWithHttpMessagesAsync(appId, metricId, timespan, interval, aggregation, segment, top, orderby, filter, null, cancellationToken).ConfigureAwait(false)) { return result.Body; } } /// <summary> /// Retrieve metric data /// </summary> /// <remarks> /// Gets metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='segment'> /// The name of the dimension to segment the metric values by. This /// dimension must be applicable to the metric you are retrieving. To /// segment by more than one dimension at a time, separate them with a /// comma (,). In this case, the metric data will be segmented in the /// order the dimensions are listed in the parameter. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> public static MetricsSegmentedResult GetSegmentedMetric(this IMetrics operations, string appId, string metricId, string timespan = default(string), IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string)) { return operations.GetSegmentedMetricAsync(appId, metricId, timespan, aggregation, segment, top, orderby, filter) .GetAwaiter().GetResult(); } /// <summary> /// Retrieve metric data /// </summary> /// <remarks> /// Gets metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='segment'> /// The name of the dimension to segment the metric values by. This /// dimension must be applicable to the metric you are retrieving. To /// segment by more than one dimension at a time, separate them with a /// comma (,). In this case, the metric data will be segmented in the /// order the dimensions are listed in the parameter. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MetricsSegmentedResult> GetSegmentedMetricAsync(this IMetrics operations, string appId, string metricId, string timespan = default(string), IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var result = await operations.GetSegmentedMetricWithHttpMessagesAsync(appId, metricId, timespan, aggregation, segment, top, orderby, filter, null, cancellationToken).ConfigureAwait(false)) { return result.Body; } } /// <summary> /// Retrieve metric data /// </summary> /// <remarks> /// Gets metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='interval'> /// The time interval to use when retrieving metric values. This is an /// ISO8601 duration. If interval is omitted, the metric value is /// aggregated across the entire timespan. If interval is supplied, the /// server may adjust the interval to a more appropriate size based on /// the timespan used for the query. In all cases, the actual interval /// used for the query is included in the response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='segment'> /// The name of the dimension to segment the metric values by. This /// dimension must be applicable to the metric you are retrieving. To /// segment by more than one dimension at a time, separate them with a /// comma (,). In this case, the metric data will be segmented in the /// order the dimensions are listed in the parameter. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> public static MetricsIntervaledSegmentedResult GetIntervaledSegmentedMetric( this IMetrics operations, string appId, string metricId, string timespan = default(string), System.TimeSpan? interval = default(System.TimeSpan?), IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string)) { return operations .GetIntervaledSegmentedMetricAsync(appId, metricId, timespan, interval, aggregation, segment, top, orderby, filter).GetAwaiter().GetResult(); } /// <summary> /// Retrieve metric data /// </summary> /// <remarks> /// Gets metric values for a single metric /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='appId'> /// ID of the application. This is Application ID from the API Access settings /// blade in the Azure portal. /// </param> /// <param name='metricId'> /// ID of the metric. This is either a standard AI metric, or an /// application-specific custom metric. Possible values include: /// 'requests/count', 'requests/duration', 'requests/failed', /// 'users/count', 'users/authenticated', 'pageViews/count', /// 'pageViews/duration', 'client/processingDuration', /// 'client/receiveDuration', 'client/networkDuration', /// 'client/sendDuration', 'client/totalDuration', /// 'dependencies/count', 'dependencies/failed', /// 'dependencies/duration', 'exceptions/count', 'exceptions/browser', /// 'exceptions/server', 'sessions/count', /// 'performanceCounters/requestExecutionTime', /// 'performanceCounters/requestsPerSecond', /// 'performanceCounters/requestsInQueue', /// 'performanceCounters/memoryAvailableBytes', /// 'performanceCounters/exceptionsPerSecond', /// 'performanceCounters/processCpuPercentage', /// 'performanceCounters/processIOBytesPerSecond', /// 'performanceCounters/processPrivateBytes', /// 'performanceCounters/processorCpuPercentage', /// 'availabilityResults/availabilityPercentage', /// 'availabilityResults/duration', 'billing/telemetryCount', /// 'customEvents/count' /// </param> /// <param name='timespan'> /// The timespan over which to retrieve metric values. This is an /// ISO8601 time period value. If timespan is omitted, a default time /// range of `PT12H` ("last 12 hours") is used. The actual timespan /// that is queried may be adjusted by the server based. In all cases, /// the actual time span used for the query is included in the /// response. /// </param> /// <param name='interval'> /// The time interval to use when retrieving metric values. This is an /// ISO8601 duration. If interval is omitted, the metric value is /// aggregated across the entire timespan. If interval is supplied, the /// server may adjust the interval to a more appropriate size based on /// the timespan used for the query. In all cases, the actual interval /// used for the query is included in the response. /// </param> /// <param name='aggregation'> /// The aggregation to use when computing the metric values. To /// retrieve more than one aggregation at a time, separate them with a /// comma. If no aggregation is specified, then the default aggregation /// for the metric is used. /// </param> /// <param name='segment'> /// The name of the dimension to segment the metric values by. This /// dimension must be applicable to the metric you are retrieving. To /// segment by more than one dimension at a time, separate them with a /// comma (,). In this case, the metric data will be segmented in the /// order the dimensions are listed in the parameter. /// </param> /// <param name='top'> /// The number of segments to return. This value is only valid when /// segment is specified. /// </param> /// <param name='orderby'> /// The aggregation function and direction to sort the segments by. /// This value is only valid when segment is specified. /// </param> /// <param name='filter'> /// An expression used to filter the results. This value should be a /// valid OData filter expression where the keys of each clause should /// be applicable dimensions for the metric you are retrieving. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<MetricsIntervaledSegmentedResult> GetIntervaledSegmentedMetricAsync( this IMetrics operations, string appId, string metricId, string timespan = default(string), System.TimeSpan? interval = default(System.TimeSpan?), IList<string> aggregation = default(IList<string>), IList<string> segment = default(IList<string>), int? top = default(int?), string orderby = default(string), string filter = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var result = await operations.GetIntervaledSegmentedMetricWithHttpMessagesAsync(appId, metricId, timespan, interval, aggregation, segment, top, orderby, filter, null, cancellationToken).ConfigureAwait(false)) { return result.Body; } } #endregion } }
#region Copyright // // Nini Configuration Project. // Copyright (C) 2006 Brent R. Matzelle. All rights reserved. // // This software is published under the terms of the MIT X11 license, a copy of // which has been included with this distribution in the LICENSE.txt file. // #endregion using System; using System.IO; using Nini.Config; using NUnit.Framework; namespace Nini.Test.Config { [TestFixture] public class IniConfigSourceTests { [Test] public void SetAndSave () { string filePath = "Test.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine ("; some comment"); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.WriteLine (""); // empty line writer.WriteLine ("; a comment"); writer.WriteLine (" cat = Muffy"); writer.Close (); IniConfigSource source = new IniConfigSource (filePath); IConfig config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); config.Set ("dog", "Spots"); config.Set ("cat", "Misha"); config.Set ("DoesNotExist", "SomeValue"); Assert.AreEqual ("Spots", config.Get ("dog")); Assert.AreEqual ("Misha", config.Get ("cat")); Assert.AreEqual ("SomeValue", config.Get ("DoesNotExist")); source.Save (); source = new IniConfigSource (filePath); config = source.Configs["new section"]; Assert.AreEqual ("Spots", config.Get ("dog")); Assert.AreEqual ("Misha", config.Get ("cat")); Assert.AreEqual ("SomeValue", config.Get ("DoesNotExist")); File.Delete (filePath); } [Test] public void MergeAndSave () { string fileName = "NiniConfig.ini"; StreamWriter fileWriter = new StreamWriter (fileName); fileWriter.WriteLine ("[Pets]"); fileWriter.WriteLine ("cat = Muffy"); // overwrite fileWriter.WriteLine ("dog = Rover"); // new fileWriter.WriteLine ("bird = Tweety"); fileWriter.Close (); StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine ("cat = Becky"); // overwrite writer.WriteLine ("lizard = Saurus"); // new writer.WriteLine ("[People]"); writer.WriteLine (" woman = Jane"); writer.WriteLine (" man = John"); IniConfigSource iniSource = new IniConfigSource (new StringReader (writer.ToString ())); IniConfigSource source = new IniConfigSource (fileName); source.Merge (iniSource); IConfig config = source.Configs["Pets"]; Assert.AreEqual (4, config.GetKeys ().Length); Assert.AreEqual ("Becky", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Saurus", config.Get ("lizard")); config = source.Configs["People"]; Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("Jane", config.Get ("woman")); Assert.AreEqual ("John", config.Get ("man")); config.Set ("woman", "Tara"); config.Set ("man", "Quentin"); source.Save (); source = new IniConfigSource (fileName); config = source.Configs["Pets"]; Assert.AreEqual (4, config.GetKeys ().Length); Assert.AreEqual ("Becky", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Saurus", config.Get ("lizard")); config = source.Configs["People"]; Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("Tara", config.Get ("woman")); Assert.AreEqual ("Quentin", config.Get ("man")); File.Delete (fileName); } [Test] public void SaveToNewPath () { string filePath = "Test.ini"; string newPath = "TestNew.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine ("; some comment"); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.WriteLine (" cat = Muffy"); writer.Close (); IniConfigSource source = new IniConfigSource (filePath); IConfig config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); source.Save (newPath); source = new IniConfigSource (newPath); config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); File.Delete (filePath); File.Delete (newPath); } [Test] public void SaveToWriter () { string newPath = "TestNew.ini"; StringWriter writer = new StringWriter (); writer.WriteLine ("; some comment"); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.WriteLine (" cat = Muffy"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); Assert.IsNull (source.SavePath); IConfig config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); StreamWriter textWriter = new StreamWriter (newPath); source.Save (textWriter); textWriter.Close (); // save to disk source = new IniConfigSource (newPath); Assert.AreEqual (newPath, source.SavePath); config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); File.Delete (newPath); } [Test] public void SaveAfterTextWriter () { string filePath = "Test.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.Close (); IniConfigSource source = new IniConfigSource (filePath); Assert.AreEqual (filePath, source.SavePath); StringWriter textWriter = new StringWriter (); source.Save (textWriter); Assert.IsNull (source.SavePath); File.Delete (filePath); } [Test] public void SaveNewSection () { string filePath = "Test.xml"; StringWriter writer = new StringWriter (); writer.WriteLine ("; some comment"); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.WriteLine (" cat = Muffy"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); IConfig config = source.AddConfig ("test"); Assert.IsNotNull (source.Configs["test"]); source.Save (filePath); source = new IniConfigSource (filePath); config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); Assert.IsNotNull (source.Configs["test"]); File.Delete (filePath); } [Test] public void RemoveConfigAndKeyFromFile () { string filePath = "Test.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine ("[test 1]"); writer.WriteLine (" dog = Rover"); writer.WriteLine ("[test 2]"); writer.WriteLine (" cat = Muffy"); writer.WriteLine (" lizard = Lizzy"); writer.Close (); IniConfigSource source = new IniConfigSource (filePath); Assert.IsNotNull (source.Configs["test 1"]); Assert.IsNotNull (source.Configs["test 2"]); Assert.IsNotNull (source.Configs["test 2"].Get ("cat")); source.Configs.Remove (source.Configs["test 1"]); source.Configs["test 2"].Remove ("cat"); source.AddConfig ("cause error"); source.Save (); source = new IniConfigSource (filePath); Assert.IsNull (source.Configs["test 1"]); Assert.IsNotNull (source.Configs["test 2"]); Assert.IsNull (source.Configs["test 2"].Get ("cat")); File.Delete (filePath); } [Test] public void ToStringTest () { StringWriter writer = new StringWriter (); writer.WriteLine ("[Test]"); writer.WriteLine (" cat = muffy"); writer.WriteLine (" dog = rover"); writer.WriteLine (" bird = tweety"); IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); string eol = Environment.NewLine; string compare = "[Test]" + eol + "cat = muffy" + eol + "dog = rover" + eol + "bird = tweety" + eol; Assert.AreEqual (compare, source.ToString ()); } [Test] public void EmptyConstructor () { string filePath = "EmptyConstructor.ini"; IniConfigSource source = new IniConfigSource (); IConfig config = source.AddConfig ("Pets"); config.Set ("cat", "Muffy"); config.Set ("dog", "Rover"); config.Set ("bird", "Tweety"); source.Save (filePath); Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("Muffy", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Tweety", config.Get ("bird")); source = new IniConfigSource (filePath); config = source.Configs["Pets"]; Assert.AreEqual (3, config.GetKeys ().Length); Assert.AreEqual ("Muffy", config.Get ("cat")); Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Tweety", config.Get ("bird")); File.Delete (filePath); } [Test] public void Reload () { string filePath = "Reload.ini"; // Create the original source file IniConfigSource source = new IniConfigSource (); IConfig petConfig = source.AddConfig ("Pets"); petConfig.Set ("cat", "Muffy"); petConfig.Set ("dog", "Rover"); IConfig weatherConfig = source.AddConfig ("Weather"); weatherConfig.Set ("skies", "cloudy"); weatherConfig.Set ("precipitation", "rain"); source.Save (filePath); Assert.AreEqual (2, petConfig.GetKeys ().Length); Assert.AreEqual ("Muffy", petConfig.Get ("cat")); Assert.AreEqual (2, source.Configs.Count); // Create another source file to set values and reload IniConfigSource newSource = new IniConfigSource (filePath); IConfig compareConfig = newSource.Configs["Pets"]; Assert.AreEqual (2, compareConfig.GetKeys ().Length); Assert.AreEqual ("Muffy", compareConfig.Get ("cat")); Assert.IsTrue (compareConfig == newSource.Configs["Pets"], "References before are not equal"); // Set the new values to source source.Configs["Pets"].Set ("cat", "Misha"); source.Configs["Pets"].Set ("lizard", "Lizzy"); source.Configs["Pets"].Set ("hampster", "Surly"); source.Configs["Pets"].Remove ("dog"); source.Configs.Remove (weatherConfig); source.Save (); // saves new value // Reload the new source and check for changes newSource.Reload (); Assert.IsTrue (compareConfig == newSource.Configs["Pets"], "References after are not equal"); Assert.AreEqual (1, newSource.Configs.Count); Assert.AreEqual (3, newSource.Configs["Pets"].GetKeys ().Length); Assert.AreEqual ("Lizzy", newSource.Configs["Pets"].Get ("lizard")); Assert.AreEqual ("Misha", newSource.Configs["Pets"].Get ("cat")); Assert.IsNull (newSource.Configs["Pets"].Get ("dog")); File.Delete (filePath); } [Test] public void FileClosedOnParseError () { string filePath = "Reload.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine (" no section = boom!"); writer.Close (); try { IniConfigSource source = new IniConfigSource (filePath); } catch { // The file was still opened on a parse error File.Delete (filePath); } } [Test] public void SaveToStream () { string filePath = "SaveToStream.ini"; FileStream stream = new FileStream (filePath, FileMode.Create); // Create a new document and save to stream IniConfigSource source = new IniConfigSource (); IConfig config = source.AddConfig ("Pets"); config.Set ("dog", "rover"); config.Set ("cat", "muffy"); source.Save (stream); stream.Close (); IniConfigSource newSource = new IniConfigSource (filePath); config = newSource.Configs["Pets"]; Assert.IsNotNull (config); Assert.AreEqual (2, config.GetKeys ().Length); Assert.AreEqual ("rover", config.GetString ("dog")); Assert.AreEqual ("muffy", config.GetString ("cat")); stream.Close (); File.Delete (filePath); } [Test] public void CaseInsensitive() { StringWriter writer = new StringWriter (); writer.WriteLine ("[Pets]"); writer.WriteLine ("cat = Becky"); // overwrite IniConfigSource source = new IniConfigSource (new StringReader (writer.ToString ())); source.CaseSensitive = false; Assert.AreEqual("Becky", source.Configs["Pets"].Get("CAT")); source.Configs["Pets"].Set("cAT", "New Name"); Assert.AreEqual("New Name", source.Configs["Pets"].Get("CAt")); source.Configs["Pets"].Remove("CAT"); Assert.IsNull(source.Configs["Pets"].Get("CaT")); } [Test] public void LoadPath () { string filePath = "Test.ini"; StreamWriter writer = new StreamWriter (filePath); writer.WriteLine ("; some comment"); writer.WriteLine ("[new section]"); writer.WriteLine (" dog = Rover"); writer.WriteLine (""); // empty line writer.WriteLine ("; a comment"); writer.WriteLine (" cat = Muffy"); writer.Close (); IniConfigSource source = new IniConfigSource (filePath); IConfig config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); config.Set ("dog", "Spots"); config.Set ("cat", "Misha"); config.Set ("DoesNotExist", "SomeValue"); source.Load (filePath); config = config = source.Configs["new section"]; Assert.AreEqual ("Rover", config.Get ("dog")); Assert.AreEqual ("Muffy", config.Get ("cat")); File.Delete (filePath); } } }
using System; using System.Globalization; /// <summary> /// String.System.IConvertible.ToUInt32(IFormatProvider provider) /// This method supports the .NET Framework infrastructure and is /// not intended to be used directly from your code. /// Converts the value of the current String object to a 32-bit unsigned integer. /// </summary> class IConvertibleToUInt32 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; public static int Main() { IConvertibleToUInt32 iege = new IConvertibleToUInt32(); TestLibrary.TestFramework.BeginTestCase("for method: String.System.IConvertible.ToUInt32(IFormatProvider)"); if (iege.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; retVal = NegTest2() && retVal; retVal = NegTest3() && retVal; return retVal; } #region Positive test scenarioes public bool PosTest1() { bool retVal = true; const string c_TEST_DESC = "PosTest1: Random numeric string"; const string c_TEST_ID = "P001"; string strSrc; IFormatProvider provider; UInt32 i; bool expectedValue = true; bool actualValue = false; i = (UInt32)(TestLibrary.Generator.GetInt64(-55) % (UInt32.MaxValue)); strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToUInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("001" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; const string c_TEST_DESC = "PosTest2: Positive sign"; const string c_TEST_ID = "P002"; string strSrc; IFormatProvider provider; NumberFormatInfo ni = new NumberFormatInfo(); UInt32 i; bool expectedValue = true; bool actualValue = false; i = (UInt32)(TestLibrary.Generator.GetInt64(-55) % (UInt32.MaxValue)); ni.PositiveSign = TestLibrary.Generator.GetString(-55, false, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); strSrc = ni.PositiveSign + i.ToString(); provider = (IFormatProvider)ni; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (i == ((IConvertible)strSrc).ToUInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("003" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("004" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; const string c_TEST_DESC = "PosTest3: string is UInt32.MaxValue"; const string c_TEST_ID = "P003"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = UInt32.MaxValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (UInt32.MaxValue == ((IConvertible)strSrc).ToUInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("005" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("006" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool PosTest4() { bool retVal = true; const string c_TEST_DESC = "PosTest4: string is UInt32.MinValue"; const string c_TEST_ID = "P004"; string strSrc; IFormatProvider provider; bool expectedValue = true; bool actualValue = false; strSrc = UInt32.MinValue.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { actualValue = (UInt32.MinValue == ((IConvertible)strSrc).ToUInt32(provider)); if (actualValue != expectedValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += GetDataString(strSrc, provider); TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, "Unexpected exception: " + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion // end for positive test scenarioes #region Negative test scenarios public bool NegTest1() { bool retVal = true; const string c_TEST_DESC = "NegTest1: The value of String object cannot be parsed"; const string c_TEST_ID = "N001"; string strSrc; IFormatProvider provider; strSrc = "p" + TestLibrary.Generator.GetString(-55, false, 9, c_MAX_STRING_LEN); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToUInt32(provider); TestLibrary.TestFramework.LogError("009" + "TestId-" + c_TEST_ID, "FormatException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (FormatException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("010" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest2() { bool retVal = true; const string c_TEST_DESC = "NegTest2: The value of String object is a number greater than MaxValue"; const string c_TEST_ID = "N002"; string strSrc; IFormatProvider provider; Int64 i; i = TestLibrary.Generator.GetInt64(-55) % UInt32.MaxValue + UInt32.MaxValue + 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToUInt32(provider); TestLibrary.TestFramework.LogError("011" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("012" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } public bool NegTest3() { bool retVal = true; const string c_TEST_DESC = "NegTest3: The value of String object is a number less than MinValue"; const string c_TEST_ID = "N003"; string strSrc; IFormatProvider provider; Int64 i; i = -1 * (TestLibrary.Generator.GetInt64(-55) % UInt32.MaxValue) + UInt32.MinValue - 1; strSrc = i.ToString(); provider = null; TestLibrary.TestFramework.BeginScenario(c_TEST_DESC); try { ((IConvertible)strSrc).ToUInt32(provider); TestLibrary.TestFramework.LogError("013" + "TestId-" + c_TEST_ID, "OverflowException is not thrown as expected" + GetDataString(strSrc, provider)); retVal = false; } catch (OverflowException) { } catch (Exception e) { TestLibrary.TestFramework.LogError("014" + "TestId-" + c_TEST_ID, "Unexpected exception:" + e + GetDataString(strSrc, provider)); retVal = false; } return retVal; } #endregion private string GetDataString(string strSrc, IFormatProvider provider) { string str1, str2, str; int len1; if (null == strSrc) { str1 = "null"; len1 = 0; } else { str1 = strSrc; len1 = strSrc.Length; } str2 = (null == provider) ? "null" : provider.ToString(); str = string.Format("\n[Source string value]\n \"{0}\"", str1); str += string.Format("\n[Length of source string]\n {0}", len1); str += string.Format("\n[Format provider string]\n {0}", str2); return str; } }
using System; using System.Diagnostics; using System.Runtime.InteropServices; using ESRI.ArcGIS.Geodatabase; using Miner.ComCategories; using Miner.Framework; namespace Miner.Interop { /// <summary> /// Base class for Relationship Auto Updaters. /// </summary> [ComVisible(true)] public abstract class BaseRelationshipAU : IMMRelationshipAUStrategy, IMMRelationshipAUStrategyEx { #region Fields private static readonly ILog Log = LogProvider.For<BaseRelationshipAU>(); #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="BaseRelationshipAU" /> class. /// </summary> /// <param name="name">The name.</param> protected BaseRelationshipAU(string name) { Name = name; } #endregion #region Public Properties /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get; } #endregion #region Public Methods /// <summary> /// Executes the specified relationship AU. /// </summary> /// <param name="pRelationship">The relationship.</param> /// <param name="mode">The AU mode.</param> /// <param name="eEvent">The edit event.</param> public void Execute(IRelationship pRelationship, mmAutoUpdaterMode mode, mmEditEvent eEvent) { try { if (InoperableAutoUpdaters.Instance.Contains(pRelationship.RelationshipClass.RelationshipClassID, -1, this.GetType())) return; if (this.CanExecute(mode)) { this.InternalExecute(pRelationship, mode, eEvent); } } catch (COMException e) { // If the MM_E_CANCELEDIT error is thrown, let it out. if (e.ErrorCode == (int) mmErrorCodes.MM_E_CANCELEDIT) throw; this.WriteError(e); } catch (Exception e) { this.WriteError(e); } } /// <summary> /// Gets whether the specified AU is enabled. /// </summary> /// <param name="pRelClass">The relationship class.</param> /// <param name="eEvent">The edit event.</param> /// <returns><c>true</c> if this AutoUpdater is enabled; otherwise <c>false</c></returns> public bool get_Enabled(IRelationshipClass pRelClass, mmEditEvent eEvent) { try { if (pRelClass == null) return false; return this.InternalEnabled(pRelClass, pRelClass.OriginClass, pRelClass.DestinationClass, eEvent); } catch (Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Enabling Relationship AU " + Name, e); else Log.Error(e); } return false; } /// <summary> /// Gets whether the specified AU is enabled. /// </summary> /// <param name="pRelationshipClass">The relationship class.</param> /// <param name="pOriginClass">The origin class.</param> /// <param name="pDestClass">The destination class.</param> /// <param name="eEvent">The edit event.</param> /// <returns><c>true</c> if this AutoUpdater is enabled; otherwise <c>false</c></returns> public bool get_Enabled(IRelationshipClass pRelationshipClass, IObjectClass pOriginClass, IObjectClass pDestClass, mmEditEvent eEvent) { try { return this.InternalEnabled(pRelationshipClass, pOriginClass, pDestClass, eEvent); } catch (Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Enabling Relationship AU " + Name, e); else Log.Error(e); } return false; } #endregion #region Internal Methods /// <summary> /// Registers the specified registry key. /// </summary> /// <param name="registryKey">The registry key.</param> [ComRegisterFunction] internal static void Register(string registryKey) { RelationshipAutoupdateStrategy.Register(registryKey); } /// <summary> /// Unregisters the specified registry key. /// </summary> /// <param name="registryKey">The registry key.</param> [ComUnregisterFunction] internal static void Unregister(string registryKey) { RelationshipAutoupdateStrategy.Unregister(registryKey); } #endregion #region Protected Methods /// <summary> /// Aborts the execution by causing an exception to be raised that notifies ArcFM to rollback the edits. /// </summary> /// <param name="message">The message.</param> /// <exception cref="Miner.CancelEditException"></exception> protected void Abort(string message) { throw new CancelEditException(message); } /// <summary> /// Determines whether this instance can execute using the specified AU mode. /// </summary> /// <param name="mode">The AU mode.</param> /// <returns> /// <c>true</c> if this instance can execute using the specified AU mode; otherwise, <c>false</c>. /// </returns> protected virtual bool CanExecute(mmAutoUpdaterMode mode) { return (mode != mmAutoUpdaterMode.mmAUMNoEvents); } /// <summary> /// Implementation of enabled method for derived classes. /// </summary> /// <param name="relClass">The relationship class.</param> /// <param name="originClass">The origin class.</param> /// <param name="destClass">The destination class.</param> /// <param name="editEvent">The edit event.</param> /// <returns><c>true</c> if this AutoUpdater is enabled; otherwise <c>false</c></returns> /// <remarks> /// This method will be called from IMMRelationshipAUStrategyEx::get_Enabled /// and is wrapped within the exception handling for that method. /// </remarks> protected abstract bool InternalEnabled(IRelationshipClass relClass, IObjectClass originClass, IObjectClass destClass, mmEditEvent editEvent); /// <summary> /// Implementation of execute method for derived classes. /// </summary> /// <param name="relationship">The relationship.</param> /// <param name="mode">The mode.</param> /// <param name="editEvent">The edit event.</param> /// <remarks> /// This method will be called from IMMRelationshipAUStrategy::Execute /// and is wrapped within the exception handling for that method. /// </remarks> protected abstract void InternalExecute(IRelationship relationship, mmAutoUpdaterMode mode, mmEditEvent editEvent); #endregion #region Private Methods /// <summary> /// Logs the exception. /// </summary> /// <param name="e">The exception.</param> private void WriteError(Exception e) { if (MinerRuntimeEnvironment.IsUserInterfaceSupported) Log.Error("Error Executing Relationship AU " + Name, e); else Log.Error(e); } #endregion } }
/* * Copyright (C) 2006-2010 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.Globalization; using System.Xml; using System.Web; using System.Collections.Specialized; using System.Net; using System.IO; using System.Security.Principal; using System.Configuration; using System.Collections; using System.Security; using System.ComponentModel; using System.Data; using System.Security.Cryptography; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace SAMLServices { /// <summary> /// Summary description for Common. /// </summary> public class Common { // String to hold the SAML namespace declaration public static String SAML_NAMESPACE = "urn:oasis:names:tc:SAML:2.0:protocol"; public static String SAML_NAMESPACE_ASSERTION = "urn:oasis:names:tc:SAML:2.0:assertion"; // String used as prefix for artifacts public static String ARTIFACT = "Artifact"; // SAML element name when resolving artifacts public static String ArtifactResolve = "ArtifactResolve"; public static String ID = "ID"; //String used to identiy the Issuer Node public static String ISSUER = "Issuer"; public static String AuthNResponseTemplate = null; public static String AuthZResponseTemplate = null; public static String AuthZResponseSopaEnvelopeStart = null; public static String AuthZResponseSopaEnvelopeEnd = null; public static String LogFile = null; public static bool bDebug = false; public static String assertionConsumer = null; public static String idpEntityId = null; public static Type provider = typeof(SAMLServices.Wia.AuthImpl); public static int DEBUG = 0, INFO = 1, ERROR = 2; public static int LOG_LEVEL = INFO; public static String SsoSubjectVar = null; public static Hashtable denyUrls = new Hashtable(); public static Hashtable denyCodes = new Hashtable(); public static String DenyAction = null; public static String DENY_REDIRECT = "redirect"; public static String DENY_RETURN_CODE = "return_code"; public static int iTrustDuration = 300; public static XmlDocument postResponse; public static X509Certificate2 certificate = null; public static String postForm = null; public static String subjectFormat = ""; /// <summary> /// When log level lower or equal to debug, show debug(most detailed msg) /// </summary> /// <param name="msg"></param> public static void debug(String msg) { if (LOG_LEVEL <= DEBUG) log(msg); } /// <summary> /// If log level is lower than error, then show all error msgs /// </summary> /// <param name="msg"></param> public static void error(String msg) { if (LOG_LEVEL <= ERROR) log(msg); } /// <summary> /// Method for logging debug/trace information to a file. ///NOTE: Read/Write privileges must be given to the web service /// process owner and domain users if impersonation is performed /// </summary> /// <param name="msg"></param> private static void log(String msg) { if (LogFile == null) { // TODO: log this to event log return; } lock (LogFile) { StreamWriter logger = File.AppendText(LogFile); System.Diagnostics.StackFrame frame = new System.Diagnostics.StackTrace().GetFrame(2); logger.WriteLine(System.DateTime.Now + ", " + frame.GetMethod().Name + ": " + msg); logger.Close(); } } /// <summary> ///Method to determine the URL to which the user is redirected /// after login. /// Based on whether this is a simulation or not. ///The simulator is a test utility that simulates ///the SAML requests that come from a GSA. /// /// </summary> public static String GSAAssertionConsumer { get { return assertionConsumer; } set { assertionConsumer = value; } } /// <summary> /// Method to determine the IDP Entity ID /// </summary> public static String IDPEntityId { get { return idpEntityId; } set { if (value != null) { idpEntityId = value.Trim(); } else { idpEntityId = ""; } } } /// <summary> /// Method to obtain the current time, converted /// tto a specific format for insertion into responses /// </summary> /// <param name="time"></param> /// <returns>Universal time format</returns> public static String FormatInvariantTime(DateTime time) { return time.ToUniversalTime().ToString("s", DateTimeFormatInfo.InvariantInfo) + "Z"; } /// <summary> /// Method that creates a random string that's used ///as the artifact after login. The GSA uses the artifact /// to then obtain the user ID. The random strings that used by all the different "ID" must start with alphabet, or an underscore. /// That's why I've prefixed "a" here. /// </summary> /// <returns>Random string</returns> public static String GenerateRandomString() { String id = "a" + System.Guid.NewGuid().ToString("N"); id = System.Web.HttpUtility.UrlEncode(id); return id; } /// <summary> /// Method to obtain an XML element within an XML string, /// given the element name. /// </summary> /// <param name="xml">The xml to be searched</param> /// <param name="name">element name</param> /// <returns></returns> public static XmlNode FindOnly(String xml, String name) { XmlDocument doc = new XmlDocument(); doc.InnerXml = xml; return FindOnly(doc, name); } /// <summary> /// Method to obtain an XML element within an XMLDocument, /// given the element name. /// </summary> /// <param name="doc">Xml Document</param> /// <param name="name">element name to be found</param> /// <returns></returns> public static XmlNode FindOnly(XmlDocument doc, String name) { XmlNodeList list = FindAllElements(doc, name); return list.Item(0); } /// <summary> /// Method to obtain a List of XML elements within an XMLDocument, /// given the element name. /// </summary> /// <param name="doc">Xml Document</param> /// <param name="name">element name to be found</param> /// <returns>List of XML Elements with matcing name</returns> public static XmlNodeList FindAllElements(XmlDocument doc, String name) { XmlNodeList list = doc.GetElementsByTagName(name, name.Equals(Common.ISSUER) ? Common.SAML_NAMESPACE_ASSERTION : Common.SAML_NAMESPACE); return list; } /// <summary> /// Method to add an XML attribute to an element /// </summary> /// <param name="node"></param> /// <param name="name"></param> /// <param name="value"></param> public static void AddAttribute(XmlNode node, String name, String value) { XmlAttribute attr = node.OwnerDocument.CreateAttribute(name); attr.Value = value; node.Attributes.Append(attr); } static public string EncodeTo64(string toEncode) { byte[] toEncodeAsBytes = System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode); string returnValue = System.Convert.ToBase64String(toEncodeAsBytes); return returnValue; } } }
// AdminCollectionUsersModal.cs // using System; using System.Collections.Generic; using System.Html; using System.Runtime.CompilerServices; using afung.MangaWeb3.Client.Admin.Module; using afung.MangaWeb3.Client.Modal; using afung.MangaWeb3.Client.Widget; using afung.MangaWeb3.Common; using jQueryApi; namespace afung.MangaWeb3.Client.Admin.Modal { public class AdminCollectionUsersModal : ModalBase { private static AdminCollectionUsersModal instance = null; private int cid; private string collectionName; private string[] usernames; private Pagination pagination; private CollectionUserJson[] data; private int currentPage; private bool submittingForm; private AdminCollectionUsersModal() : base("admin", "admin-collection-users-modal") { } protected override void Initialize() { pagination = new Pagination(jQuery.Select("#admin-collection-users-pagination"), ChangePage, GetTotalPage, "right"); jQuery.Select("#admin-collection-users-add-submit").Click(SubmitAddForm); jQuery.Select("#admin-collection-users-form").Submit(SubmitAddForm); jQuery.Select("#admin-collection-users-delete-btn").Click(DeleteButtonClicked); jQuery.Select("#admin-collection-users-allow-btn").Click(AllowButtonClicked); jQuery.Select("#admin-collection-users-deny-btn").Click(DenyButtonClicked); Utility.FixDropdownTouch(jQuery.Select("#admin-collection-users-action-dropdown")); } private int GetTotalPage() { if (data == null || data.Length == 0) { return 1; } return Math.Ceil(data.Length / Environment.ModalElementsPerPage); } public static void ShowDialog(int cid) { if (instance == null) { instance = new AdminCollectionUsersModal(); } instance.InternalShow(cid); } public void InternalShow(int cid) { this.cid = cid; Refresh(); } [AlternateSignature] public extern void Refresh(JsonResponse response); public void Refresh() { AdminCollectionsUsersGetRequest request = new AdminCollectionsUsersGetRequest(); request.t = 0; request.id = cid; Request.Send(request, GetRequestSuccess); jQuery.Select("#admin-collection-users-tbody").Children().Remove(); Template.Get("admin", "loading-trow", true).AppendTo(jQuery.Select("#admin-collection-users-tbody")); } [AlternateSignature] private extern void GetRequestSuccess(JsonResponse response); private void GetRequestSuccess(AdminCollectionsUsersGetResponse response) { Show(); jQuery.Select("#admin-collection-users-name").Text(collectionName = response.name); ((BootstrapTypeahead)((jQueryBootstrap)jQuery.Select("#admin-collection-users-add-user").Value("")).Typeahead().GetDataValue("typeahead")).Source = usernames = response.names; data = response.data; ChangePage(1); pagination.Refresh(true); } private void ChangePage(int page) { currentPage = page; jQuery.Select("#admin-collection-users-tbody").Children().Remove(); if (data.Length == 0) { Template.Get("admin", "noitem-trow", true).AppendTo(jQuery.Select("#admin-collection-users-tbody")); } for (int i = (page - 1) * Environment.ModalElementsPerPage; i < data.Length && i < page * Environment.ModalElementsPerPage; i++) { jQueryObject row = Template.Get("admin", "admin-collection-users-trow", true).AppendTo(jQuery.Select("#admin-collection-users-tbody")); jQuery.Select(".admin-collection-users-checkbox", row).Value(data[i].uid.ToString()); jQuery.Select(".admin-collection-users-username", row).Text(data[i].username); jQuery.Select(".admin-collection-users-access", row).Text(Strings.Get(data[i].access ? "Yes" : "No")).AddClass(data[i].access ? "label-success" : ""); } Show(); } private void SubmitAddForm(jQueryEvent e) { e.PreventDefault(); string username = jQuery.Select("#admin-collection-users-add-user").GetValue(); if (usernames.Contains(username) && !submittingForm) { submittingForm = true; AdminCollectionUserAddRequest request = new AdminCollectionUserAddRequest(); request.username = username; request.collectionName = collectionName; request.access = jQuery.Select("#admin-collection-users-add-access").GetValue() == "true"; Request.Send(request, SubmitAddFormSuccess, SubmitAddFormFailure); } } private void SubmitAddFormSuccess(JsonResponse response) { submittingForm = false; Refresh(); } private void SubmitAddFormFailure(Exception error) { submittingForm = false; ErrorModal.ShowError(error.ToString()); } private void AllowButtonClicked(jQueryEvent e) { e.PreventDefault(); InternalAccessButtonClicked(true); } private void DenyButtonClicked(jQueryEvent e) { e.PreventDefault(); InternalAccessButtonClicked(false); } private void InternalAccessButtonClicked(bool access) { int[] ids = GetSelectedIds(); if (ids.Length > 0) { AdminCollectionsUsersAccessRequest request = new AdminCollectionsUsersAccessRequest(); request.t = 0; request.id = cid; request.ids = ids; request.access = access; Request.Send(request, Refresh); } } private void DeleteButtonClicked(jQueryEvent e) { e.PreventDefault(); int[] ids = GetSelectedIds(); if (ids.Length > 0) { ConfirmModal.Show(Strings.Get("DeleteItemsConfirm"), DeleteConfirm); } } private void DeleteConfirm(bool confirm) { int[] ids = GetSelectedIds(); if (confirm && ids.Length > 0) { AdminCollectionsUsersDeleteRequest request = new AdminCollectionsUsersDeleteRequest(); request.t = 0; request.id = cid; request.ids = ids; Request.Send(request, Refresh); } } private int[] GetSelectedIds() { return Utility.GetSelectedCheckboxIds("admin-collection-users-checkbox"); } } }
//----------------------------------------------------------------------- // <copyright file="BaseTask.cs">(c) http://www.codeplex.com/MSBuildExtensionPack. This source is subject to the Microsoft Permissive License. See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx. All other rights reserved.</copyright> //----------------------------------------------------------------------- namespace MSBuild.ExtensionPack { using System; using System.Globalization; using System.Management; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; /// <summary> /// Provides a common task for all the MSBuildExtensionPack Tasks /// </summary> public abstract class BaseTask : Task { private string machineName; private AuthenticationLevel authenticationLevel = System.Management.AuthenticationLevel.Default; /// <summary> /// Sets the TaskAction. /// </summary> public virtual string TaskAction { get; set; } /// <summary> /// Sets the MachineName. /// </summary> public virtual string MachineName { get { return this.machineName ?? Environment.MachineName; } set { this.machineName = value; } } /// <summary> /// Sets the UserName /// </summary> public virtual string UserName { get; set; } /// <summary> /// Sets the UserPassword. /// </summary> public virtual string UserPassword { get; set; } /// <summary> /// Sets the authority to be used to authenticate the specified user. /// </summary> public string Authority { get; set; } /// <summary> /// Sets the authentication level to be used to connect to WMI. Default is Default. Also supports: Call, Connect, None, Packet, PacketIntegrity, PacketPrivacy, Unchanged /// </summary> public string AuthenticationLevel { get { return this.authenticationLevel.ToString(); } set { this.authenticationLevel = (AuthenticationLevel)Enum.Parse(typeof(AuthenticationLevel), value); } } /// <summary> /// Set to true to log the full Exception Stack to the console. /// </summary> public bool LogExceptionStack { get; set; } /// <summary> /// Set to true to suppress all Message logging by tasks. Errors and Warnings are not affected. /// </summary> public bool SuppressTaskMessages { get; set; } internal ManagementScope Scope { get; set; } /// <summary> /// Executes this instance. /// </summary> /// <returns>bool</returns> public override sealed bool Execute() { this.DetermineLogging(); try { this.InternalExecute(); return !this.Log.HasLoggedErrors; } catch (Exception ex) { this.GetExceptionLevel(); this.Log.LogErrorFromException(ex, this.LogExceptionStack, true, null); return !this.Log.HasLoggedErrors; } } /// <summary> /// Determines whether the task is targeting the local machine /// </summary> /// <returns>bool</returns> internal bool TargetingLocalMachine() { return this.TargetingLocalMachine(false); } /// <summary> /// Determines whether the task is targeting the local machine /// </summary> /// <param name="canExecuteRemotely">True if the current TaskAction can run against a remote machine</param> /// <returns>bool</returns> internal bool TargetingLocalMachine(bool canExecuteRemotely) { if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) != 0) { if (!canExecuteRemotely) { this.Log.LogError(string.Format(CultureInfo.CurrentCulture, "This task does not support remote execution. Please remove the MachineName: {0}", this.MachineName)); } return false; } return true; } internal void LogTaskWarning(string message) { this.Log.LogWarning(message); } internal void LogTaskMessage(MessageImportance messageImportance, string message) { this.LogTaskMessage(messageImportance, message, null); } internal void LogTaskMessage(string message, object[] arguments) { this.LogTaskMessage(MessageImportance.Normal, message, arguments); } internal void LogTaskMessage(string message) { this.LogTaskMessage(MessageImportance.Normal, message, null); } internal void LogTaskMessage(MessageImportance messageImportance, string message, object[] arguments) { if (!this.SuppressTaskMessages) { if (arguments == null) { this.Log.LogMessage(messageImportance, message); } else { this.Log.LogMessage(messageImportance, message, arguments); } } } internal void GetManagementScope(string wmiNamespace) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "ManagementScope Set: {0}", "\\\\" + this.MachineName + wmiNamespace)); if (string.Compare(this.MachineName, Environment.MachineName, StringComparison.OrdinalIgnoreCase) == 0) { this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace); } else { ConnectionOptions options = new ConnectionOptions { Authentication = this.authenticationLevel, Username = this.UserName, Password = this.UserPassword, Authority = this.Authority }; this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace, options); } } internal void GetManagementScope(string wmiNamespace, ConnectionOptions options) { this.LogTaskMessage(MessageImportance.Low, string.Format(CultureInfo.CurrentCulture, "ManagementScope Set: {0}", "\\\\" + this.MachineName + wmiNamespace)); this.Scope = new ManagementScope("\\\\" + this.MachineName + wmiNamespace, options); } /// <summary> /// This is the main InternalExecute method that all tasks should implement /// </summary> /// <remarks> /// LogError should be thrown in the event of errors /// </remarks> protected abstract void InternalExecute(); private void GetExceptionLevel() { string s = Environment.GetEnvironmentVariable("LogExceptionStack", EnvironmentVariableTarget.Machine); if (!string.IsNullOrEmpty(s)) { this.LogExceptionStack = Convert.ToBoolean(s, CultureInfo.CurrentCulture); } } private void DetermineLogging() { string s = Environment.GetEnvironmentVariable("SuppressTaskMessages", EnvironmentVariableTarget.Machine); if (!string.IsNullOrEmpty(s)) { this.SuppressTaskMessages = Convert.ToBoolean(s, CultureInfo.CurrentCulture); } } } }
// 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 AddInt32() { var test = new SimpleBinaryOpTest__AddInt32(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // 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(); // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleBinaryOpTest__AddInt32 { private const int VectorSize = 16; private const int ElementCount = VectorSize / sizeof(Int32); private static Int32[] _data1 = new Int32[ElementCount]; private static Int32[] _data2 = new Int32[ElementCount]; private static Vector128<Int32> _clsVar1; private static Vector128<Int32> _clsVar2; private Vector128<Int32> _fld1; private Vector128<Int32> _fld2; private SimpleBinaryOpTest__DataTable<Int32> _dataTable; static SimpleBinaryOpTest__AddInt32() { var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar1), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _clsVar2), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); } public SimpleBinaryOpTest__AddInt32() { Succeeded = true; var random = new Random(); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld1), ref Unsafe.As<Int32, byte>(ref _data1[0]), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int32>, byte>(ref _fld2), ref Unsafe.As<Int32, byte>(ref _data2[0]), VectorSize); for (var i = 0; i < ElementCount; i++) { _data1[i] = (int)(random.Next(int.MinValue, int.MaxValue)); _data2[i] = (int)(random.Next(int.MinValue, int.MaxValue)); } _dataTable = new SimpleBinaryOpTest__DataTable<Int32>(_data1, _data2, new Int32[ElementCount], VectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse2.Add( Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse2.Add( Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse2.Add( Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse2).GetMethod(nameof(Sse2.Add), new Type[] { typeof(Vector128<Int32>), typeof(Vector128<Int32>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)), Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse2.Add( _clsVar1, _clsVar2 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar1, _clsVar2, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var left = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray1Ptr); var right = Unsafe.Read<Vector128<Int32>>(_dataTable.inArray2Ptr); var result = Sse2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var left = Sse2.LoadVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var left = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray1Ptr)); var right = Sse2.LoadAlignedVector128((Int32*)(_dataTable.inArray2Ptr)); var result = Sse2.Add(left, right); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(left, right, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleBinaryOpTest__AddInt32(); var result = Sse2.Add(test._fld1, test._fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld1, test._fld2, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse2.Add(_fld1, _fld2); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld1, _fld2, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<Int32> left, Vector128<Int32> right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[ElementCount]; Int32[] inArray2 = new Int32[ElementCount]; Int32[] outArray = new Int32[ElementCount]; Unsafe.Write(Unsafe.AsPointer(ref inArray1[0]), left); Unsafe.Write(Unsafe.AsPointer(ref inArray2[0]), right); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(void* left, void* right, void* result, [CallerMemberName] string method = "") { Int32[] inArray1 = new Int32[ElementCount]; Int32[] inArray2 = new Int32[ElementCount]; Int32[] outArray = new Int32[ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(left), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(right), VectorSize); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), VectorSize); ValidateResult(inArray1, inArray2, outArray, method); } private void ValidateResult(Int32[] left, Int32[] right, Int32[] result, [CallerMemberName] string method = "") { if ((int)(left[0] + right[0]) != result[0]) { Succeeded = false; } else { for (var i = 1; i < left.Length; i++) { if ((int)(left[i] + right[i]) != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse2)}.{nameof(Sse2.Add)}<Int32>: {method} failed:"); Console.WriteLine($" left: ({string.Join(", ", left)})"); Console.WriteLine($" right: ({string.Join(", ", right)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.ServiceModel.ServiceHostBase.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.ServiceModel { abstract public partial class ServiceHostBase : System.ServiceModel.Channels.CommunicationObject, IExtensibleObject<ServiceHostBase>, IDisposable { #region Methods and constructors protected void AddBaseAddress(Uri baseAddress) { } public virtual new System.Collections.ObjectModel.ReadOnlyCollection<System.ServiceModel.Description.ServiceEndpoint> AddDefaultEndpoints() { return default(System.Collections.ObjectModel.ReadOnlyCollection<System.ServiceModel.Description.ServiceEndpoint>); } public System.ServiceModel.Description.ServiceEndpoint AddServiceEndpoint(string implementedContract, System.ServiceModel.Channels.Binding binding, Uri address, Uri listenUri) { Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpoint>() != null); return default(System.ServiceModel.Description.ServiceEndpoint); } public virtual new void AddServiceEndpoint(System.ServiceModel.Description.ServiceEndpoint endpoint) { } public System.ServiceModel.Description.ServiceEndpoint AddServiceEndpoint(string implementedContract, System.ServiceModel.Channels.Binding binding, Uri address) { Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpoint>() != null); return default(System.ServiceModel.Description.ServiceEndpoint); } public System.ServiceModel.Description.ServiceEndpoint AddServiceEndpoint(string implementedContract, System.ServiceModel.Channels.Binding binding, string address) { Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpoint>() != null); return default(System.ServiceModel.Description.ServiceEndpoint); } public System.ServiceModel.Description.ServiceEndpoint AddServiceEndpoint(string implementedContract, System.ServiceModel.Channels.Binding binding, string address, Uri listenUri) { Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceEndpoint>() != null); return default(System.ServiceModel.Description.ServiceEndpoint); } protected virtual new void ApplyConfiguration() { } protected abstract System.ServiceModel.Description.ServiceDescription CreateDescription(out IDictionary<string, System.ServiceModel.Description.ContractDescription> implementedContracts); public int IncrementManualFlowControlLimit(int incrementBy) { return default(int); } protected void InitializeDescription(UriSchemeKeyedCollection baseAddresses) { Contract.Requires(baseAddresses != null); } protected virtual new void InitializeRuntime() { } protected void LoadConfigurationSection(System.ServiceModel.Configuration.ServiceElement serviceSection) { } protected override void OnAbort() { } protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, Object state) { return default(IAsyncResult); } protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, Object state) { return default(IAsyncResult); } protected override void OnClose(TimeSpan timeout) { } protected override void OnClosed() { } protected override void OnEndClose(IAsyncResult result) { } protected override void OnEndOpen(IAsyncResult result) { } protected override void OnOpen(TimeSpan timeout) { } protected override void OnOpened() { } protected void ReleasePerformanceCounters() { } protected ServiceHostBase() { } public void SetEndpointAddress(System.ServiceModel.Description.ServiceEndpoint endpoint, string relativeAddress) { } void System.IDisposable.Dispose() { } #endregion #region Properties and indexers #if !NETFRAMEWORK_3_5 public System.ServiceModel.Description.ServiceAuthenticationBehavior Authentication { get { return default(System.ServiceModel.Description.ServiceAuthenticationBehavior); } } #endif public System.ServiceModel.Description.ServiceAuthorizationBehavior Authorization { get { return default(System.ServiceModel.Description.ServiceAuthorizationBehavior); } } public System.Collections.ObjectModel.ReadOnlyCollection<Uri> BaseAddresses { get { Contract.Ensures(Contract.Result<System.Collections.ObjectModel.ReadOnlyCollection<System.Uri>>() != null); return default(System.Collections.ObjectModel.ReadOnlyCollection<Uri>); } } public System.ServiceModel.Dispatcher.ChannelDispatcherCollection ChannelDispatchers { get { return default(System.ServiceModel.Dispatcher.ChannelDispatcherCollection); } } public TimeSpan CloseTimeout { get { return default(TimeSpan); } set { } } public System.ServiceModel.Description.ServiceCredentials Credentials { get { return default(System.ServiceModel.Description.ServiceCredentials); } } protected override TimeSpan DefaultCloseTimeout { get { return default(TimeSpan); } } protected override TimeSpan DefaultOpenTimeout { get { return default(TimeSpan); } } public System.ServiceModel.Description.ServiceDescription Description { get { Contract.Ensures(Contract.Result<System.ServiceModel.Description.ServiceDescription>() != null); return default(System.ServiceModel.Description.ServiceDescription); } } public IExtensionCollection<System.ServiceModel.ServiceHostBase> Extensions { get { return default(IExtensionCollection<System.ServiceModel.ServiceHostBase>); } } #if !NETFRAMEWORK_3_5 internal protected IDictionary<string, System.ServiceModel.Description.ContractDescription> ImplementedContracts { get { return default(IDictionary<string, System.ServiceModel.Description.ContractDescription>); } } #endif public int ManualFlowControlLimit { get { return default(int); } set { } } public TimeSpan OpenTimeout { get { return default(TimeSpan); } set { } } #endregion #region Events public event EventHandler<UnknownMessageReceivedEventArgs> UnknownMessageReceived { add { } remove { } } #endregion } }
// // JsonSerializer.cs // // Author: // Marek Habersack <[email protected]> // // (C) 2008 Novell, Inc. http://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. // namespace Nancy.Json { using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Nancy.Extensions; internal sealed class JsonSerializer { internal static readonly long InitialJavaScriptDateTicks = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks; static readonly DateTime MinimumJavaScriptDate = new DateTime(100, 1, 1, 0, 0, 0, DateTimeKind.Utc); static readonly MethodInfo serializeGenericDictionary = typeof(JsonSerializer).GetMethod("SerializeGenericDictionary", BindingFlags.NonPublic | BindingFlags.Instance); Dictionary <object, bool> objectCache; JavaScriptSerializer serializer; JavaScriptTypeResolver typeResolver; int recursionLimit; int maxJsonLength; int recursionDepth; bool retainCasing; bool iso8601DateFormat; Dictionary <Type, MethodInfo> serializeGenericDictionaryMethods; public JsonSerializer (JavaScriptSerializer serializer) { if (serializer == null) throw new ArgumentNullException ("serializer"); this.serializer = serializer; typeResolver = serializer.TypeResolver; recursionLimit = serializer.RecursionLimit; maxJsonLength = serializer.MaxJsonLength; retainCasing = serializer.RetainCasing; iso8601DateFormat = serializer.ISO8601DateFormat; } public void Serialize (object obj, StringBuilder output) { if (output == null) throw new ArgumentNullException ("output"); DoSerialize (obj, output); } public void Serialize (object obj, TextWriter output) { if (output == null) throw new ArgumentNullException ("output"); StringBuilder sb = new StringBuilder (); DoSerialize (obj, sb); output.Write (sb.ToString ()); } void DoSerialize (object obj, StringBuilder output) { recursionDepth = 0; objectCache = new Dictionary <object, bool> (); SerializeValue (obj, output); } void SerializeValue (object obj, StringBuilder output) { recursionDepth++; SerializeValueImpl (obj, output); recursionDepth--; } void SerializeValueImpl (object obj, StringBuilder output) { if (recursionDepth > recursionLimit) throw new ArgumentException ("Recursion limit has been exceeded while serializing object of type '{0}'", obj != null ? obj.GetType ().ToString () : "[null]"); if (obj == null || DBNull.Value.Equals (obj)) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "null"); return; } #if !__MonoCS__ if (obj.GetType().Name == "RuntimeType") { obj = obj.ToString(); } #else if (obj.GetType().Name == "MonoType") { obj = obj.ToString(); } #endif Type valueType = obj.GetType (); JavaScriptConverter jsc = serializer.GetConverter (valueType); if (jsc != null) { IDictionary <string, object> result = jsc.Serialize (obj, serializer); if (result == null) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "null"); return; } if (typeResolver != null) { string typeId = typeResolver.ResolveTypeId (valueType); if (!String.IsNullOrEmpty (typeId)) result [JavaScriptSerializer.SerializedTypeNameKey] = typeId; } SerializeValue (result, output); return; } JavaScriptPrimitiveConverter jscp = serializer.GetPrimitiveConverter (valueType); if (jscp != null) { obj = jscp.Serialize (obj, serializer); if (obj == null || DBNull.Value.Equals (obj)) { // Recurse in order that there be one place in the code that handles null values. SerializeValueImpl (obj, output); return; } valueType = obj.GetType (); } TypeCode typeCode = Type.GetTypeCode (valueType); switch (typeCode) { case TypeCode.String: WriteValue (output, (string)obj); return; case TypeCode.Char: WriteValue (output, (char)obj); return; case TypeCode.Boolean: WriteValue (output, (bool)obj); return; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.Byte: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (valueType.IsEnum) { WriteEnumValue (output, obj, typeCode); return; } goto case TypeCode.Decimal; case TypeCode.Single: WriteValue (output, (float)obj); return; case TypeCode.Double: WriteValue (output, (double)obj); return; case TypeCode.Decimal: WriteValue (output, obj as IConvertible); return; case TypeCode.DateTime: WriteValue (output, (DateTime)obj); return; } if (typeof (Uri).IsAssignableFrom (valueType)) { WriteValue (output, (Uri)obj); return; } if (typeof (Guid).IsAssignableFrom (valueType)) { WriteValue (output, (Guid)obj); return; } if (valueType == typeof(DateTimeOffset)) { WriteValue(output, (DateTimeOffset)obj); return; } if (typeof (DynamicDictionaryValue).IsAssignableFrom(valueType)) { var o = (DynamicDictionaryValue) obj; SerializeValue(o.Value, output); return; } IConvertible convertible = obj as IConvertible; if (convertible != null) { WriteValue (output, convertible); return; } try { if (objectCache.ContainsKey (obj)) throw new InvalidOperationException ("Circular reference detected."); objectCache.Add (obj, true); Type closedIDict = GetClosedIDictionaryBase(valueType); if (closedIDict != null) { if (serializeGenericDictionaryMethods == null) serializeGenericDictionaryMethods = new Dictionary <Type, MethodInfo> (); MethodInfo mi; if (!serializeGenericDictionaryMethods.TryGetValue (closedIDict, out mi)) { Type[] types = closedIDict.GetGenericArguments (); mi = serializeGenericDictionary.MakeGenericMethod (types [0], types [1]); serializeGenericDictionaryMethods.Add (closedIDict, mi); } mi.Invoke (this, new object[] {output, obj}); return; } IDictionary dict = obj as IDictionary; if (dict != null) { SerializeDictionary (output, dict); return; } IEnumerable enumerable = obj as IEnumerable; if (enumerable != null) { SerializeEnumerable (output, enumerable); return; } SerializeArbitraryObject (output, obj, valueType); } finally { objectCache.Remove (obj); } } Type GetClosedIDictionaryBase(Type t) { if(t.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (t.GetGenericTypeDefinition ())) return t; foreach(Type iface in t.GetInterfaces()) { if(iface.IsGenericType && typeof (IDictionary <,>).IsAssignableFrom (iface.GetGenericTypeDefinition ())) return iface; } return null; } bool ShouldIgnoreMember (MemberInfo mi, out MethodInfo getMethod) { getMethod = null; if (mi == null) return true; if (mi.GetCustomAttributes(true).Any(a => a.GetType().Name == "ScriptIgnoreAttribute")) return true; FieldInfo fi = mi as FieldInfo; if (fi != null) return false; PropertyInfo pi = mi as PropertyInfo; if (pi == null) return true; getMethod = pi.GetGetMethod (); if (getMethod == null || getMethod.GetParameters ().Length > 0) { getMethod = null; return true; } return false; } object GetMemberValue (object obj, MemberInfo mi) { FieldInfo fi = mi as FieldInfo; if (fi != null) return fi.GetValue (obj); MethodInfo method = mi as MethodInfo; if (method == null) throw new InvalidOperationException ("Member is not a method (internal error)."); object ret; try { ret = method.Invoke (obj, null); } catch (TargetInvocationException niex) { if (niex.InnerException is NotImplementedException) { Console.WriteLine ("!!! COMPATIBILITY WARNING. FEATURE NOT IMPLEMENTED. !!!"); Console.WriteLine (niex); Console.WriteLine ("!!! RETURNING NULL. PLEASE LET MONO DEVELOPERS KNOW ABOUT THIS EXCEPTION. !!!"); return null; } throw; } return ret; } void SerializeArbitraryObject (StringBuilder output, object obj, Type type) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "{"); bool first = true; if (typeResolver != null) { string typeId = typeResolver.ResolveTypeId (type); if (!String.IsNullOrEmpty (typeId)) { WriteDictionaryEntry (output, first, JavaScriptSerializer.SerializedTypeNameKey, typeId); first = false; } } SerializeMembers <FieldInfo> (type.GetFields (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first); SerializeMembers <PropertyInfo> (type.GetProperties (BindingFlags.Public | BindingFlags.Instance), obj, output, ref first); StringBuilderExtensions.AppendCount (output, maxJsonLength, "}"); } void SerializeMembers <T> (T[] members, object obj, StringBuilder output, ref bool first) where T: MemberInfo { MemberInfo member; MethodInfo getMethod; foreach (T mi in members) { if (ShouldIgnoreMember (mi as MemberInfo, out getMethod)) continue; if (getMethod != null) member = getMethod; else member = mi; WriteDictionaryEntry (output, first, mi.Name, GetMemberValue (obj, member)); if (first) first = false; } } void SerializeEnumerable (StringBuilder output, IEnumerable enumerable) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "["); bool first = true; foreach (object value in enumerable) { if (!first) StringBuilderExtensions.AppendCount (output, maxJsonLength, ','); SerializeValue (value, output); if (first) first = false; } StringBuilderExtensions.AppendCount (output, maxJsonLength, "]"); } void SerializeDictionary (StringBuilder output, IDictionary dict) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "{"); bool first = true; foreach (DictionaryEntry entry in dict) { WriteDictionaryEntry (output, first, entry.Key as string, entry.Value); if (first) first = false; } StringBuilderExtensions.AppendCount (output, maxJsonLength, "}"); } void SerializeGenericDictionary <TKey, TValue> (StringBuilder output, IDictionary <TKey, TValue> dict) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "{"); bool first = true; foreach (KeyValuePair <TKey, TValue> kvp in dict) { var key = typeof(TKey) == typeof(Guid) ? kvp.Key.ToString() : kvp.Key as string; WriteDictionaryEntry (output, first, key, kvp.Value); if (first) first = false; } StringBuilderExtensions.AppendCount (output, maxJsonLength, "}"); } void WriteDictionaryEntry (StringBuilder output, bool skipComma, string key, object value) { if (key == null) throw new InvalidOperationException ("Only dictionaries with keys convertible to string, or guid keys are supported."); if (!skipComma) StringBuilderExtensions.AppendCount (output, maxJsonLength, ','); key = retainCasing ? key : key.ToCamelCase(); WriteValue(output, key); StringBuilderExtensions.AppendCount (output, maxJsonLength, ':'); SerializeValue (value, output); } void WriteEnumValue (StringBuilder output, object value, TypeCode typeCode) { switch (typeCode) { case TypeCode.SByte: StringBuilderExtensions.AppendCount (output, maxJsonLength, (sbyte)value); return; case TypeCode.Int16: StringBuilderExtensions.AppendCount (output, maxJsonLength, (short)value); return; case TypeCode.UInt16: StringBuilderExtensions.AppendCount (output, maxJsonLength, (ushort)value); return; case TypeCode.Int32: StringBuilderExtensions.AppendCount (output, maxJsonLength, (int)value); return; case TypeCode.Byte: StringBuilderExtensions.AppendCount (output, maxJsonLength, (byte)value); return; case TypeCode.UInt32: StringBuilderExtensions.AppendCount (output, maxJsonLength, (uint)value); return; case TypeCode.Int64: StringBuilderExtensions.AppendCount (output, maxJsonLength, (long)value); return; case TypeCode.UInt64: StringBuilderExtensions.AppendCount (output, maxJsonLength, (ulong)value); return; default: throw new InvalidOperationException (String.Format ("Invalid type code for enum: {0}", typeCode)); } } void WriteValue (StringBuilder output, float value) { StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString ("r",Json.DefaultNumberFormatInfo)); } void WriteValue (StringBuilder output, double value) { StringBuilderExtensions.AppendCount(output, maxJsonLength, value.ToString("r",Json.DefaultNumberFormatInfo)); } void WriteValue (StringBuilder output, Guid value) { WriteValue (output, value.ToString ()); } void WriteValue (StringBuilder output, Uri value) { WriteValue (output, value.GetComponents (UriComponents.AbsoluteUri, UriFormat.UriEscaped)); } void WriteValue (StringBuilder output, DateTime value) { if (this.iso8601DateFormat) { if (value.Kind == DateTimeKind.Unspecified) { // To avoid confusion, treat "Unspecified" datetimes as Local -- just like the WCF datetime format does as well. value = new DateTime(value.Ticks, DateTimeKind.Local); } StringBuilderExtensions.AppendCount(output, maxJsonLength, string.Concat("\"", value.ToString("o", CultureInfo.InvariantCulture), "\"")); } else { DateTime time = value.ToUniversalTime(); string suffix = ""; if (value.Kind != DateTimeKind.Utc) { TimeSpan localTZOffset; if (value >= time) { localTZOffset = value - time; suffix = "+"; } else { localTZOffset = time - value; suffix = "-"; } suffix += localTZOffset.ToString("hhmm"); } if (time < MinimumJavaScriptDate) time = MinimumJavaScriptDate; long ticks = (time.Ticks - InitialJavaScriptDateTicks)/(long)10000; StringBuilderExtensions.AppendCount(output, maxJsonLength, "\"\\/Date(" + ticks + suffix + ")\\/\""); } } void WriteValue(StringBuilder output, DateTimeOffset value) { StringBuilderExtensions.AppendCount(output, maxJsonLength, string.Concat("\"", value.ToString("o", CultureInfo.InvariantCulture), "\"")); } void WriteValue (StringBuilder output, IConvertible value) { StringBuilderExtensions.AppendCount (output, maxJsonLength, value.ToString (CultureInfo.InvariantCulture)); } void WriteValue (StringBuilder output, bool value) { StringBuilderExtensions.AppendCount (output, maxJsonLength, value ? "true" : "false"); } void WriteValue (StringBuilder output, char value) { if (value == '\0') { StringBuilderExtensions.AppendCount (output, maxJsonLength, "null"); return; } WriteValue (output, value.ToString ()); } void WriteValue (StringBuilder output, string value) { if (String.IsNullOrEmpty (value)) { StringBuilderExtensions.AppendCount (output, maxJsonLength, "\"\""); return; } StringBuilderExtensions.AppendCount (output, maxJsonLength, "\""); char c; for (int i = 0; i < value.Length; i++) { c = value [i]; switch (c) { case '\t': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\t"); break; case '\n': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\n"); break; case '\r': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\r"); break; case '\f': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\f"); break; case '\b': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\b"); break; case '<': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003c"); break; case '>': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u003e"); break; case '"': StringBuilderExtensions.AppendCount (output, maxJsonLength, "\\\""); break; case '\'': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\u0027"); break; case '\\': StringBuilderExtensions.AppendCount (output, maxJsonLength, @"\\"); break; default: if (c > '\u001f') StringBuilderExtensions.AppendCount (output, maxJsonLength, c); else { output.Append("\\u00"); int intVal = (int) c; StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) ('0' + (intVal >> 4))); intVal &= 0xf; StringBuilderExtensions.AppendCount (output, maxJsonLength, (char) (intVal < 10 ? '0' + intVal : 'a' + (intVal - 10))); } break; } } StringBuilderExtensions.AppendCount (output, maxJsonLength, "\""); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using 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.Vision.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedImageAnnotatorClientTest { [xunit::FactAttribute] public void BatchAnnotateImagesRequestObject() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest { Requests = { new AnnotateImageRequest(), }, Parent = "parent7858e4d0", }; BatchAnnotateImagesResponse expectedResponse = new BatchAnnotateImagesResponse { Responses = { new AnnotateImageResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateImages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateImagesResponse response = client.BatchAnnotateImages(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchAnnotateImagesRequestObjectAsync() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest { Requests = { new AnnotateImageRequest(), }, Parent = "parent7858e4d0", }; BatchAnnotateImagesResponse expectedResponse = new BatchAnnotateImagesResponse { Responses = { new AnnotateImageResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateImagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchAnnotateImagesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateImagesResponse responseCallSettings = await client.BatchAnnotateImagesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchAnnotateImagesResponse responseCancellationToken = await client.BatchAnnotateImagesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchAnnotateImages() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest { Requests = { new AnnotateImageRequest(), }, }; BatchAnnotateImagesResponse expectedResponse = new BatchAnnotateImagesResponse { Responses = { new AnnotateImageResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateImages(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateImagesResponse response = client.BatchAnnotateImages(request.Requests); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchAnnotateImagesAsync() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateImagesRequest request = new BatchAnnotateImagesRequest { Requests = { new AnnotateImageRequest(), }, }; BatchAnnotateImagesResponse expectedResponse = new BatchAnnotateImagesResponse { Responses = { new AnnotateImageResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateImagesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchAnnotateImagesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateImagesResponse responseCallSettings = await client.BatchAnnotateImagesAsync(request.Requests, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchAnnotateImagesResponse responseCancellationToken = await client.BatchAnnotateImagesAsync(request.Requests, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchAnnotateFilesRequestObject() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateFilesRequest request = new BatchAnnotateFilesRequest { Requests = { new AnnotateFileRequest(), }, Parent = "parent7858e4d0", }; BatchAnnotateFilesResponse expectedResponse = new BatchAnnotateFilesResponse { Responses = { new AnnotateFileResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateFiles(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateFilesResponse response = client.BatchAnnotateFiles(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchAnnotateFilesRequestObjectAsync() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateFilesRequest request = new BatchAnnotateFilesRequest { Requests = { new AnnotateFileRequest(), }, Parent = "parent7858e4d0", }; BatchAnnotateFilesResponse expectedResponse = new BatchAnnotateFilesResponse { Responses = { new AnnotateFileResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateFilesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchAnnotateFilesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateFilesResponse responseCallSettings = await client.BatchAnnotateFilesAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchAnnotateFilesResponse responseCancellationToken = await client.BatchAnnotateFilesAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void BatchAnnotateFiles() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateFilesRequest request = new BatchAnnotateFilesRequest { Requests = { new AnnotateFileRequest(), }, }; BatchAnnotateFilesResponse expectedResponse = new BatchAnnotateFilesResponse { Responses = { new AnnotateFileResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateFiles(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateFilesResponse response = client.BatchAnnotateFiles(request.Requests); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task BatchAnnotateFilesAsync() { moq::Mock<ImageAnnotator.ImageAnnotatorClient> mockGrpcClient = new moq::Mock<ImageAnnotator.ImageAnnotatorClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); BatchAnnotateFilesRequest request = new BatchAnnotateFilesRequest { Requests = { new AnnotateFileRequest(), }, }; BatchAnnotateFilesResponse expectedResponse = new BatchAnnotateFilesResponse { Responses = { new AnnotateFileResponse(), }, }; mockGrpcClient.Setup(x => x.BatchAnnotateFilesAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<BatchAnnotateFilesResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ImageAnnotatorClient client = new ImageAnnotatorClientImpl(mockGrpcClient.Object, null); BatchAnnotateFilesResponse responseCallSettings = await client.BatchAnnotateFilesAsync(request.Requests, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); BatchAnnotateFilesResponse responseCancellationToken = await client.BatchAnnotateFilesAsync(request.Requests, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
// Copyright (c) ppy Pty Ltd <[email protected]>. 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.IO; using System.Linq; using System.Reflection; using osu.Framework.Allocation; using osu.Framework.Audio; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.IO.Stores; using osu.Framework.Platform; using osu.Game.Beatmaps; using osu.Game.Configuration; using osu.Game.Graphics; using osu.Game.Graphics.Cursor; using osu.Game.Online.API; using osu.Framework.Graphics.Performance; using osu.Framework.Graphics.Textures; using osu.Framework.Input; using osu.Framework.Logging; using osu.Game.Audio; using osu.Game.Database; using osu.Game.Graphics.Containers; using osu.Game.Input; using osu.Game.Input.Bindings; using osu.Game.IO; using osu.Game.Rulesets; using osu.Game.Scoring; using osu.Game.Skinning; using osuTK.Input; using DebugUtils = osu.Game.Utils.DebugUtils; namespace osu.Game { /// <summary> /// The most basic <see cref="Game"/> that can be used to host osu! components and systems. /// Unlike <see cref="OsuGame"/>, this class will not load any kind of UI, allowing it to be used /// for provide dependencies to test cases without interfering with them. /// </summary> public class OsuGameBase : Framework.Game, ICanAcceptFiles { protected OsuConfigManager LocalConfig; protected BeatmapManager BeatmapManager; protected ScoreManager ScoreManager; protected SkinManager SkinManager; protected RulesetStore RulesetStore; protected FileStore FileStore; protected KeyBindingStore KeyBindingStore; protected SettingsStore SettingsStore; protected RulesetConfigCache RulesetConfigCache; protected APIAccess API; protected MenuCursorContainer MenuCursorContainer; private Container content; protected override Container<Drawable> Content => content; private Bindable<WorkingBeatmap> beatmap; protected Bindable<WorkingBeatmap> Beatmap => beatmap; private Bindable<bool> fpsDisplayVisible; public virtual Version AssemblyVersion => Assembly.GetEntryAssembly()?.GetName().Version ?? new Version(); public bool IsDeployedBuild => AssemblyVersion.Major > 0; public string Version { get { if (!IsDeployedBuild) return @"local " + (DebugUtils.IsDebug ? @"debug" : @"release"); var version = AssemblyVersion; return $@"{version.Major}.{version.Minor}.{version.Build}"; } } public OsuGameBase() { Name = @"osu!lazer"; } private DependencyContainer dependencies; protected override IReadOnlyDependencyContainer CreateChildDependencies(IReadOnlyDependencyContainer parent) => dependencies = new DependencyContainer(base.CreateChildDependencies(parent)); private DatabaseContextFactory contextFactory; protected override UserInputManager CreateUserInputManager() => new OsuUserInputManager(); [BackgroundDependencyLoader] private void load() { Resources.AddStore(new DllResourceStore(@"osu.Game.Resources.dll")); dependencies.Cache(contextFactory = new DatabaseContextFactory(Host.Storage)); var largeStore = new LargeTextureStore(Host.CreateTextureLoaderStore(new NamespacedResourceStore<byte[]>(Resources, @"Textures"))); largeStore.AddStore(Host.CreateTextureLoaderStore(new OnlineStore())); dependencies.Cache(largeStore); dependencies.CacheAs(this); dependencies.Cache(LocalConfig); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/osuFont")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Medium")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-MediumItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Basic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-Hangul")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Basic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Noto-CJK-Compatibility")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Regular")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-RegularItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBold")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-SemiBoldItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Bold")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BoldItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Light")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-LightItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-Black")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Exo2.0-BlackItalic")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera")); Fonts.AddStore(new GlyphStore(Resources, @"Fonts/Venera-Light")); runMigrations(); dependencies.Cache(SkinManager = new SkinManager(Host.Storage, contextFactory, Host, Audio)); dependencies.CacheAs<ISkinSource>(SkinManager); API = new APIAccess(LocalConfig); dependencies.CacheAs<IAPIProvider>(API); var defaultBeatmap = new DummyWorkingBeatmap(this); dependencies.Cache(RulesetStore = new RulesetStore(contextFactory)); dependencies.Cache(FileStore = new FileStore(contextFactory, Host.Storage)); dependencies.Cache(BeatmapManager = new BeatmapManager(Host.Storage, contextFactory, RulesetStore, API, Audio, Host, defaultBeatmap)); dependencies.Cache(ScoreManager = new ScoreManager(RulesetStore, BeatmapManager, Host.Storage, contextFactory, Host)); dependencies.Cache(KeyBindingStore = new KeyBindingStore(contextFactory, RulesetStore)); dependencies.Cache(SettingsStore = new SettingsStore(contextFactory)); dependencies.Cache(RulesetConfigCache = new RulesetConfigCache(SettingsStore)); dependencies.Cache(new OsuColour()); fileImporters.Add(BeatmapManager); fileImporters.Add(ScoreManager); fileImporters.Add(SkinManager); // tracks play so loud our samples can't keep up. // this adds a global reduction of track volume for the time being. Audio.Track.AddAdjustment(AdjustableProperty.Volume, new BindableDouble(0.8)); beatmap = new OsuBindableBeatmap(defaultBeatmap, Audio); dependencies.CacheAs<IBindable<WorkingBeatmap>>(beatmap); dependencies.CacheAs(beatmap); FileStore.Cleanup(); AddInternal(API); GlobalActionContainer globalBinding; MenuCursorContainer = new MenuCursorContainer { RelativeSizeAxes = Axes.Both }; MenuCursorContainer.Child = globalBinding = new GlobalActionContainer(this) { RelativeSizeAxes = Axes.Both, Child = content = new OsuTooltipContainer(MenuCursorContainer.Cursor) { RelativeSizeAxes = Axes.Both } }; base.Content.Add(new ScalingContainer(ScalingMode.Everything) { Child = MenuCursorContainer }); KeyBindingStore.Register(globalBinding); dependencies.Cache(globalBinding); PreviewTrackManager previewTrackManager; dependencies.Cache(previewTrackManager = new PreviewTrackManager()); Add(previewTrackManager); } protected override void LoadComplete() { base.LoadComplete(); // TODO: This is temporary until we reimplement the local FPS display. // It's just to allow end-users to access the framework FPS display without knowing the shortcut key. fpsDisplayVisible = LocalConfig.GetBindable<bool>(OsuSetting.ShowFpsDisplay); fpsDisplayVisible.ValueChanged += visible => { FrameStatisticsMode = visible.NewValue ? FrameStatisticsMode.Minimal : FrameStatisticsMode.None; }; fpsDisplayVisible.TriggerChange(); } private void runMigrations() { try { using (var db = contextFactory.GetForWrite(false)) db.Context.Migrate(); } catch (Exception e) { Logger.Error(e.InnerException ?? e, "Migration failed! We'll be starting with a fresh database.", LoggingTarget.Database); // if we failed, let's delete the database and start fresh. // todo: we probably want a better (non-destructive) migrations/recovery process at a later point than this. contextFactory.ResetDatabase(); Logger.Log("Database purged successfully.", LoggingTarget.Database); // only run once more, then hard bail. using (var db = contextFactory.GetForWrite(false)) db.Context.Migrate(); } } public override void SetHost(GameHost host) { if (LocalConfig == null) LocalConfig = new OsuConfigManager(host.Storage); base.SetHost(host); } private readonly List<ICanAcceptFiles> fileImporters = new List<ICanAcceptFiles>(); public void Import(params string[] paths) { var extension = Path.GetExtension(paths.First())?.ToLowerInvariant(); foreach (var importer in fileImporters) if (importer.HandledExtensions.Contains(extension)) importer.Import(paths); } public string[] HandledExtensions => fileImporters.SelectMany(i => i.HandledExtensions).ToArray(); private class OsuBindableBeatmap : BindableBeatmap { public OsuBindableBeatmap(WorkingBeatmap defaultValue, AudioManager audioManager) : this(defaultValue) { RegisterAudioManager(audioManager); } public OsuBindableBeatmap(WorkingBeatmap defaultValue) : base(defaultValue) { } public override BindableBeatmap GetBoundCopy() { var copy = new OsuBindableBeatmap(Default); copy.BindTo(this); return copy; } } private class OsuUserInputManager : UserInputManager { protected override MouseButtonEventManager CreateButtonManagerFor(MouseButton button) { switch (button) { case MouseButton.Right: return new RightMouseManager(button); } return base.CreateButtonManagerFor(button); } private class RightMouseManager : MouseButtonEventManager { public RightMouseManager(MouseButton button) : base(button) { } public override bool EnableDrag => true; // allow right-mouse dragging for absolute scroll in scroll containers. public override bool EnableClick => false; public override bool ChangeFocusOnClick => false; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Diagnostics; using System.ComponentModel; using System.Xml; using System.IO; using System.Globalization; using System.Text; namespace System.Xml.Schema { public abstract class XmlSchemaDatatype { public abstract Type ValueType { get; } public abstract XmlTokenizedType TokenizedType { get; } public abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr); public virtual XmlSchemaDatatypeVariety Variety { get { return XmlSchemaDatatypeVariety.Atomic; } } public virtual object ChangeType(object value, Type targetType) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } return ValueConverter.ChangeType(value, targetType); } public virtual object ChangeType(object value, Type targetType, IXmlNamespaceResolver namespaceResolver) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (targetType == null) { throw new ArgumentNullException(nameof(targetType)); } if (namespaceResolver == null) { throw new ArgumentNullException(nameof(namespaceResolver)); } return ValueConverter.ChangeType(value, targetType, namespaceResolver); } public virtual XmlTypeCode TypeCode { get { return XmlTypeCode.None; } } public virtual bool IsDerivedFrom(XmlSchemaDatatype datatype) { return false; } internal abstract bool HasLexicalFacets { get; } internal abstract bool HasValueFacets { get; } internal abstract XmlValueConverter ValueConverter { get; } internal abstract RestrictionFacets Restriction { get; set; } internal abstract int Compare(object value1, object value2); internal abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, bool createAtomicValue); internal abstract Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue); internal abstract Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver namespaceResolver, out object typedValue); internal abstract FacetsChecker FacetsChecker { get; } internal abstract XmlSchemaWhiteSpace BuiltInWhitespaceFacet { get; } internal abstract XmlSchemaDatatype DeriveByRestriction(XmlSchemaObjectCollection facets, XmlNameTable nameTable, XmlSchemaType schemaType); internal abstract XmlSchemaDatatype DeriveByList(XmlSchemaType schemaType); internal abstract void VerifySchemaValid(XmlSchemaObjectTable notations, XmlSchemaObject caller); internal abstract bool IsEqual(object o1, object o2); internal abstract bool IsComparable(XmlSchemaDatatype dtype); //Error message helper internal string TypeCodeString { get { string typeCodeString = string.Empty; XmlTypeCode typeCode = this.TypeCode; switch (this.Variety) { case XmlSchemaDatatypeVariety.List: if (typeCode == XmlTypeCode.AnyAtomicType) { //List of union typeCodeString = "List of Union"; } else { typeCodeString = "List of " + TypeCodeToString(typeCode); } break; case XmlSchemaDatatypeVariety.Union: typeCodeString = "Union"; break; case XmlSchemaDatatypeVariety.Atomic: if (typeCode == XmlTypeCode.AnyAtomicType) { typeCodeString = "anySimpleType"; } else { typeCodeString = TypeCodeToString(typeCode); } break; } return typeCodeString; } } internal string TypeCodeToString(XmlTypeCode typeCode) { switch (typeCode) { case XmlTypeCode.None: return "None"; case XmlTypeCode.Item: return "AnyType"; case XmlTypeCode.AnyAtomicType: return "AnyAtomicType"; case XmlTypeCode.String: return "String"; case XmlTypeCode.Boolean: return "Boolean"; case XmlTypeCode.Decimal: return "Decimal"; case XmlTypeCode.Float: return "Float"; case XmlTypeCode.Double: return "Double"; case XmlTypeCode.Duration: return "Duration"; case XmlTypeCode.DateTime: return "DateTime"; case XmlTypeCode.Time: return "Time"; case XmlTypeCode.Date: return "Date"; case XmlTypeCode.GYearMonth: return "GYearMonth"; case XmlTypeCode.GYear: return "GYear"; case XmlTypeCode.GMonthDay: return "GMonthDay"; case XmlTypeCode.GDay: return "GDay"; case XmlTypeCode.GMonth: return "GMonth"; case XmlTypeCode.HexBinary: return "HexBinary"; case XmlTypeCode.Base64Binary: return "Base64Binary"; case XmlTypeCode.AnyUri: return "AnyUri"; case XmlTypeCode.QName: return "QName"; case XmlTypeCode.Notation: return "Notation"; case XmlTypeCode.NormalizedString: return "NormalizedString"; case XmlTypeCode.Token: return "Token"; case XmlTypeCode.Language: return "Language"; case XmlTypeCode.NmToken: return "NmToken"; case XmlTypeCode.Name: return "Name"; case XmlTypeCode.NCName: return "NCName"; case XmlTypeCode.Id: return "Id"; case XmlTypeCode.Idref: return "Idref"; case XmlTypeCode.Entity: return "Entity"; case XmlTypeCode.Integer: return "Integer"; case XmlTypeCode.NonPositiveInteger: return "NonPositiveInteger"; case XmlTypeCode.NegativeInteger: return "NegativeInteger"; case XmlTypeCode.Long: return "Long"; case XmlTypeCode.Int: return "Int"; case XmlTypeCode.Short: return "Short"; case XmlTypeCode.Byte: return "Byte"; case XmlTypeCode.NonNegativeInteger: return "NonNegativeInteger"; case XmlTypeCode.UnsignedLong: return "UnsignedLong"; case XmlTypeCode.UnsignedInt: return "UnsignedInt"; case XmlTypeCode.UnsignedShort: return "UnsignedShort"; case XmlTypeCode.UnsignedByte: return "UnsignedByte"; case XmlTypeCode.PositiveInteger: return "PositiveInteger"; default: return typeCode.ToString(); } } internal static string ConcatenatedToString(object value) { Type t = value.GetType(); string stringValue = string.Empty; if (t == typeof(IEnumerable) && t != typeof(string)) { StringBuilder bldr = new StringBuilder(); IEnumerator enumerator = (value as IEnumerable).GetEnumerator(); if (enumerator.MoveNext()) { bldr.Append("{"); object cur = enumerator.Current; if (cur is IFormattable) { bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); } else { bldr.Append(cur.ToString()); } while (enumerator.MoveNext()) { bldr.Append(" , "); cur = enumerator.Current; if (cur is IFormattable) { bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); } else { bldr.Append(cur.ToString()); } } bldr.Append("}"); stringValue = bldr.ToString(); } } else if (value is IFormattable) { stringValue = ((IFormattable)value).ToString("", CultureInfo.InvariantCulture); } else { stringValue = value.ToString(); } return stringValue; } internal static XmlSchemaDatatype FromXmlTokenizedType(XmlTokenizedType token) { return DatatypeImplementation.FromXmlTokenizedType(token); } internal static XmlSchemaDatatype FromXmlTokenizedTypeXsd(XmlTokenizedType token) { return DatatypeImplementation.FromXmlTokenizedTypeXsd(token); } internal static XmlSchemaDatatype FromXdrName(string name) { return DatatypeImplementation.FromXdrName(name); } internal static XmlSchemaDatatype DeriveByUnion(XmlSchemaSimpleType[] types, XmlSchemaType schemaType) { return DatatypeImplementation.DeriveByUnion(types, schemaType); } internal static string XdrCanonizeUri(string uri, XmlNameTable nameTable, SchemaNames schemaNames) { string canonicalUri; int offset = 5; bool convert = false; if (uri.Length > 5 && uri.StartsWith("uuid:", StringComparison.Ordinal)) { convert = true; } else if (uri.Length > 9 && uri.StartsWith("urn:uuid:", StringComparison.Ordinal)) { convert = true; offset = 9; } if (convert) { canonicalUri = nameTable.Add(string.Concat(uri.AsSpan(0, offset), CultureInfo.InvariantCulture.TextInfo.ToUpper(uri.Substring(offset, uri.Length - offset)))); } else { canonicalUri = uri; } if ( Ref.Equal(schemaNames.NsDataTypeAlias, canonicalUri) || Ref.Equal(schemaNames.NsDataTypeOld, canonicalUri) ) { canonicalUri = schemaNames.NsDataType; } else if (Ref.Equal(schemaNames.NsXdrAlias, canonicalUri)) { canonicalUri = schemaNames.NsXdr; } return canonicalUri; } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Debugger.ArmProcessor { using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.IO; using System.Windows.Forms; using System.Threading; using IR = Microsoft.Zelig.CodeGeneration.IR; using RT = Microsoft.Zelig.Runtime; using TS = Microsoft.Zelig.Runtime.TypeSystem; using Cfg = Microsoft.Zelig.Configuration.Environment; using Hst = Microsoft.Zelig.Emulation.Hosting; public partial class DebuggerMainForm : Form, IMainForm { class ViewEntry { // // State // internal readonly Hst.Forms.BaseDebuggerForm Form; internal readonly Hst.Forms.HostingSite.PublicationMode Mode; internal readonly ToolStripMenuItem MenuItem; // // Constructor Methods // internal ViewEntry( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { var item = new ToolStripMenuItem(); this.Mode = mode; this.Form = form; this.MenuItem = item; //--// var image = form.ViewImage; var title = form.ViewTitle; item.Text = (title != null) ? title : form.GetType().FullName; item.DisplayStyle = (image != null) ? ToolStripItemDisplayStyle.ImageAndText : ToolStripItemDisplayStyle.Text; item.Image = image; item.Tag = this; item.ImageAlign = ContentAlignment.MiddleLeft; item.TextAlign = ContentAlignment.MiddleRight; item.Click += new System.EventHandler( delegate( object sender, EventArgs e ) { if(this.MenuItem.Checked) { this.Form.Hide(); } else { this.Form.Show(); } } ); } // // Helper Methods // internal static ViewEntry Find( List< ViewEntry > lst , Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { foreach(var item in lst) { if(item.Form == form && item.Mode == mode) { return item; } } return null; } } class HostingSiteImpl : Hst.Forms.HostingSite { // // State // DebuggerMainForm m_owner; // // Constructor Methods // internal HostingSiteImpl( DebuggerMainForm owner ) { m_owner = owner; } // // Helper Methods // public override void ProcessKeyDownEvent( KeyEventArgs e ) { m_owner.ProcessKeyDownEvent( e ); } public override void ProcessKeyUpEvent( KeyEventArgs e ) { m_owner.ProcessKeyUpEvent( e ); } public override void ReportFormStatus( Hst.Forms.BaseDebuggerForm form , bool fOpened ) { m_owner.ReportFormStatus( form, fOpened ); } public override void RegisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { m_owner.RegisterView( form, mode ); } public override void UnregisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { m_owner.UnregisterView( form, mode ); } public override void VisualizeDebugInfo( Debugging.DebugInfo di ) { m_owner.VisualizeDebugInfo( di ); } public override object GetHostingService( Type t ) { return m_owner.Host.GetHostingService( t ); } public override void RegisterService( Type type , object impl ) { m_owner.Host.RegisterService( type, impl ); } public override void UnregisterService( object impl ) { m_owner.Host.UnregisterService( impl ); } // // Access Methods // public override bool IsIdle { get { return m_owner.IsIdle; } } } class ApplicationArguments { // // State // internal string[] m_arguments; internal string m_sessionName; internal string m_sessionFile; internal string m_imageFile; internal List< string > m_breakpoints = new List< string >(); internal List< System.Reflection.Assembly > m_asssemblies = new List< System.Reflection.Assembly >(); internal List< Type > m_handlers = new List< Type >(); // // Constructor Methods // internal ApplicationArguments( string[] args ) { m_arguments = args; } // // Helper Methods // internal bool Parse() { return Parse( m_arguments ); } private bool Parse( string line ) { List< string > args = new List< string >(); for(int pos = 0; pos < line.Length; ) { char c = line[pos++]; switch(c) { case ' ': case '\t': break; case '\'': case '"': { StringBuilder sb = new StringBuilder(); int pos2 = pos; bool fAdd = false; while(pos2 < line.Length) { char c2 = line[pos2++]; if(fAdd == false) { if(c2 == c) { break; } if(c2 == '\\') { fAdd = true; continue; } } sb.Append( c2 ); fAdd = false; } pos = pos2; args.Add( sb.ToString() ); } break; default: { StringBuilder sb = new StringBuilder(); int pos2 = pos; sb.Append( c ); while(pos2 < line.Length) { char c2 = line[pos2++]; if(c2 == ' ' || c2 == '\t' ) { break; } sb.Append( c2 ); } pos = pos2; args.Add( sb.ToString() ); } break; } } if(args.Count == 0) { return true; } return Parse( args.ToArray() ); } private bool Parse( string[] args ) { if(args != null) { for(int i = 0; i < args.Length; i++) { string arg = args[i]; if(arg == string.Empty) { continue; } if(arg.StartsWith( "/" ) || arg.StartsWith( "-" ) ) { string option = arg.Substring( 1 ); if(IsMatch( option, "Cfg" )) { string file; if(!GetArgument( arg, args, true, ref i, out file )) { return false; } using(System.IO.StreamReader stream = new System.IO.StreamReader( file )) { string line; while((line = stream.ReadLine()) != null) { if(line.StartsWith( "#" )) { continue; } if(Parse( line ) == false) { return false; } } } } else if(IsMatch( option, "Session" )) { if(!GetArgument( arg, args, false, ref i, out m_sessionName )) { return false; } } else if(IsMatch( option, "SessionFile" )) { if(!GetArgument( arg, args, true, ref i, out m_sessionFile )) { return false; } } else if(IsMatch( option, "ImageFile" )) { if(!GetArgument( arg, args, true, ref i, out m_imageFile )) { return false; } } else if(IsMatch( option, "Breakpoint" )) { string str; if(!GetArgument( arg, args, false, ref i, out str )) { return false; } m_breakpoints.Add( str ); } else if(IsMatch( option, "LoadAssembly" )) { string file; if(!GetArgument( arg, args, true, ref i, out file )) { return false; } try { m_asssemblies.Add( System.Reflection.Assembly.LoadFrom( file ) ); // // The plug-ins will come from a different directory structure. // But the loader won't resolve assembly names to assemblies outside the application directory structure, // even if the assemblies are already loaded in the current AppDomain. // // Let's register with the AppDomain, so we can check if an assembly has already been loaded, and // just override the loader policy. // if(m_asssemblies.Count == 1) { AppDomain.CurrentDomain.AssemblyResolve += delegate( object sender, ResolveEventArgs args2 ) { foreach(System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { if(asm.FullName == args2.Name) { return asm; } } return null; }; } } catch(Exception ex) { MessageBox.Show( string.Format( "Exception caught while loading assembly from file {0}:\r\n{1}", file, ex ), "Type Load Error", MessageBoxButtons.OK ); return false; } } else if(IsMatch( option, "AddHandler" )) { string cls; if(!GetArgument( arg, args, false, ref i, out cls )) { return false; } Type t = Type.GetType( cls ); if(t == null) { foreach(System.Reflection.Assembly asm in AppDomain.CurrentDomain.GetAssemblies()) { t = asm.GetType( cls ); if(t != null) { break; } } } if(t == null) { MessageBox.Show( string.Format( "Cannot find type for handler '{0}'", cls ), "Type Load Error", MessageBoxButtons.OK ); return false; } m_handlers.Add( t ); } //// else if(IsMatch( option, "DumpIR" )) //// { //// m_fDumpIR = true; //// } //// else if(IsMatch( option, "DumpASM" )) //// { //// m_fDumpASM = true; //// } //// else if(IsMatch( option, "DumpHEX" )) //// { //// m_fDumpHEX = true; //// } else { MessageBox.Show( string.Format( "Unrecognized option: {0}", option ) ); return false; } } //// else //// { //// arg = Expand( arg ); //// if(File.Exists( arg ) == false) //// { //// Console.WriteLine( "Cannot find '{0}'", arg ); //// return false; //// } //// //// if(m_targetFile != null) //// { //// Console.WriteLine( "ERROR: Only one target file per compilation." ); //// } //// //// m_targetFile = arg; //// //// m_searchOrder.Insert( 0, System.IO.Path.GetDirectoryName( arg ) ); //// } } return true; } return false; } private static bool IsMatch( string arg , string cmd ) { return arg.ToUpper().CompareTo( cmd.ToUpper() ) == 0; } private static bool GetArgument( string arg , string[] args , bool fExpandEnvVar , ref int i , out string value ) { if(i + 1 < args.Length) { i++; value = args[i]; if(fExpandEnvVar) { value = Expand( value ); } return true; } MessageBox.Show( string.Format( "Option '{0}' needs an argument", arg ) ); value = null; return false; } private static string Expand( string str ) { return Environment.ExpandEnvironmentVariables( str ); } } //--// const int c_visualEffect_Depth_CurrentStatement = 1; const int c_visualEffect_Depth_OnTheStackTrace = 2; const int c_visualEffect_Depth_Breakpoint = 3; const int c_visualEffect_Depth_Disassembly = 4; const int c_visualEffect_Depth_Profile = 5; // // State // ApplicationArguments m_arguments; bool m_fFullyInitialized; ProfilerMainForm m_profilerForm; DisplayForm m_displayForm; OutputForm m_outputForm; EnvironmentForm m_environmentForm; SessionManagerForm m_sessionManagerForm; List< Hst.AbstractUIPlugIn > m_plugIns = new List< Hst.AbstractUIPlugIn >(); Hst.Forms.HostingSite.ExecutionState m_currentState; HostingSiteImpl m_hostingSiteImpl; ProcessorHost m_processorHost; int m_versionBreakpoints; ulong m_baseSample_clockTicks; ulong m_baseSample_nanoseconds; ulong m_currentSample_clockTicks; ulong m_currentSample_nanoseconds; ulong m_lastSample_clockTicks; ulong m_lastSample_nanoseconds; ImageInformation m_imageInformation; int m_versionStackTrace; List< ThreadStatus > m_threads; ThreadStatus m_activeThread; ThreadStatus m_selectedThread; Thread m_processorWorker; AutoResetEvent m_processorWorkerSignal; Queue< WorkerWorkItem > m_processorWorkerRequests; bool m_processorWorkerExit; DebugGarbageColllection m_debugGC; //--// List< VisualTreeInfo > m_visualTreesList; List< ViewEntry > m_viewEntriesList; //--// Session m_currentSession; Cfg.Manager m_configurationManager; Brush m_brush_CurrentPC = new SolidBrush( Color.FromArgb( 255, 238, 98 ) ); Brush m_brush_PastPC = new SolidBrush( Color.FromArgb( 180, 228, 180 ) ); Brush m_brush_Breakpoint = new SolidBrush( Color.FromArgb( 150, 58, 70 ) ); Pen m_pen_Breakpoint = new Pen ( Color.FromArgb( 150, 58, 70 ) ); Icon m_icon_Breakpoint = Properties.Resources.Breakpoint; Icon m_icon_BreakpointDisabled = Properties.Resources.BreakpointDisabled; Icon m_icon_CurrentStatement = Properties.Resources.CurrentStatement; Icon m_icon_StackFrame = Properties.Resources.StackFrame; //--// public bool DebugGC = false; public bool DebugGCVerbose = false; //--// // // Constructor Methods // public DebuggerMainForm( string[] args ) { InitializeComponent(); //--// m_arguments = new ApplicationArguments( args ); m_configurationManager = new Cfg.Manager(); m_configurationManager.AddAllAssemblies( null ); m_configurationManager.ComputeAllPossibleValuesForFields(); //--// m_currentState = Hst.Forms.HostingSite.ExecutionState.Invalid; m_threads = new List< ThreadStatus >(); m_processorWorker = new Thread( ProcessorWorker ); m_processorWorkerSignal = new AutoResetEvent( false ); m_processorWorkerRequests = new Queue< WorkerWorkItem >(); m_visualTreesList = new List< VisualTreeInfo >(); m_viewEntriesList = new List< ViewEntry >(); //--// m_hostingSiteImpl = new HostingSiteImpl( this ); m_processorHost = new ProcessorHost ( this ); m_profilerForm = new ProfilerMainForm ( m_hostingSiteImpl ); m_displayForm = new DisplayForm ( m_hostingSiteImpl ); m_outputForm = new OutputForm ( m_hostingSiteImpl ); m_environmentForm = new EnvironmentForm ( this ); m_sessionManagerForm = new SessionManagerForm( this ); //--// codeView1.DefaultHitSink = codeView1_HitSink; localsView1 .Link( this ); stackTraceView1 .Link( this ); threadsView1 .Link( this ); registersView1 .Link( this ); breakpointsView1.Link( this ); memoryView1 .Link( this ); } // // Helper Methods // private void FullyInitialized() { if(m_arguments.Parse() == false) { Application.Exit(); } string name = m_arguments.m_sessionName; if(name != null) { m_currentSession = m_sessionManagerForm.FindSession( name ); if(m_currentSession == null) { MessageBox.Show( string.Format( "Cannot find session '{0}'", name ) ); Application.Exit(); } } string file = m_arguments.m_sessionFile; if(file != null) { m_currentSession = m_sessionManagerForm.LoadSession( file, true ); if(m_currentSession == null) { MessageBox.Show( string.Format( "Cannot load session file '{0}'", file ) ); Application.Exit(); } } if(m_currentSession != null) { m_sessionManagerForm.SelectSession( m_currentSession ); if(m_arguments.m_imageFile != null) { m_currentSession.ImageToLoad = m_arguments.m_imageFile; } } foreach(Type t in m_arguments.m_handlers) { if(t.IsSubclassOf( typeof(Hst.AbstractUIPlugIn) )) { Hst.AbstractUIPlugIn plugIn = (Hst.AbstractUIPlugIn)Activator.CreateInstance( t, m_hostingSiteImpl ); m_plugIns.Add( plugIn ); plugIn.Start(); } } if(m_currentSession == null) { m_currentSession = m_sessionManagerForm.SelectSession( true ); } if(m_arguments.m_breakpoints.Count > 0) { m_hostingSiteImpl.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.ExecutionState oldState, Hst.Forms.HostingSite.ExecutionState newState ) { if(newState != Hst.Forms.HostingSite.ExecutionState.Loaded) { return Hst.Forms.HostingSite.NotificationResponse.DoNothing; } tabControl_Data.SelectedTab = tabPage_Breakpoints; foreach(string breakpoint in m_arguments.m_breakpoints) { breakpointsView1.Set( breakpoint ); } return Hst.Forms.HostingSite.NotificationResponse.RemoveFromNotificationList; }; } m_hostingSiteImpl.NotifyOnExecutionStateChange += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.ExecutionState oldState, Hst.Forms.HostingSite.ExecutionState newState ) { if(newState == Hst.Forms.HostingSite.ExecutionState.Loaded) { Action_ResetAbsoluteTime(); } if(newState == Hst.Forms.HostingSite.ExecutionState.Paused) { if(m_processorHost.GetAbsoluteTime( out m_currentSample_clockTicks, out m_currentSample_nanoseconds )) { DisplayExecutionTime(); } else { toolStripStatus_AbsoluteTime.Text = ""; } } else { m_lastSample_clockTicks = m_currentSample_clockTicks; m_lastSample_nanoseconds = m_currentSample_nanoseconds; toolStripStatus_AbsoluteTime.Text = ""; } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; m_hostingSiteImpl.NotifyOnVisualizationEvent += delegate( Hst.Forms.HostingSite host, Hst.Forms.HostingSite.VisualizationEvent e ) { switch(e) { case Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame: UpdateCurrentMethod(); break; } return Hst.Forms.HostingSite.NotificationResponse.DoNothing; }; InnerAction_LoadImage(); } private void UpdateCurrentMethod() { string txt = "<no current method>"; while(true) { var th = m_selectedThread ; if(th == null) break; var stackFrame = m_selectedThread.StackFrame; if(stackFrame == null) break; var cm = stackFrame.CodeMapOfTarget ; if(cm == null) break; var md = cm.Target ; if(md == null) break; txt = string.Format( "{0}", md.ToShortString() ); break; } toolStripStatus_CurrentMethod.Text = txt; } //--// public static void SetPanelHeight( Panel panel , int height ) { Size size = panel.Size; if(size.Height != height) { size.Height = height; panel.Size = size; } } internal void ReportFormStatus( Form form , bool fOpened ) { foreach(var item in m_viewEntriesList) { if(item.Form == form) { item.MenuItem.Checked = fOpened; } } } private void RegisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { if(ViewEntry.Find( m_viewEntriesList, form, mode ) == null) { var item = new ViewEntry( form, mode ); m_viewEntriesList.Add( item ); switch(mode) { case Hst.Forms.HostingSite.PublicationMode.Window: { var items = this.toolStripMenuItem_Windows.DropDownItems; var index = items.IndexOf( this.toolStripSeparator_Files ); items.Insert( index, item.MenuItem ); } break; case Hst.Forms.HostingSite.PublicationMode.View: { var items = this.toolStripMenuItem_View.DropDownItems; items.Add( item.MenuItem ); } break; case Hst.Forms.HostingSite.PublicationMode.Tools: { var items = this.toolStripMenuItem_Tools.DropDownItems; var indexTop = items.IndexOf( this.toolStripSeparator_Tools_Top ); var indexBottom = items.IndexOf( this.toolStripSeparator_Tools_Bottom ); items.Insert( indexBottom, item.MenuItem ); this.toolStripSeparator_Tools_Bottom.Visible = true; } break; } } } private void UnregisterView( Hst.Forms.BaseDebuggerForm form , Hst.Forms.HostingSite.PublicationMode mode ) { var item = ViewEntry.Find( m_viewEntriesList, form, mode ); if(item != null) { m_viewEntriesList.Remove( item ); var menu = item.MenuItem; var menuOwner = (ToolStripMenuItem)menu.OwnerItem; menuOwner.DropDownItems.Remove( menu ); switch(mode) { case Hst.Forms.HostingSite.PublicationMode.Window: { var items = this.toolStripMenuItem_Windows.DropDownItems; var index = items.IndexOf( this.toolStripSeparator_Files ); if(index == 0) { this.toolStripSeparator_Files.Visible = false; } } break; case Hst.Forms.HostingSite.PublicationMode.View: { } break; case Hst.Forms.HostingSite.PublicationMode.Tools: { var items = this.toolStripMenuItem_Tools.DropDownItems; var indexTop = items.IndexOf( this.toolStripSeparator_Tools_Top ); var indexBottom = items.IndexOf( this.toolStripSeparator_Tools_Bottom ); if(indexTop + 1 == indexBottom) { this.toolStripSeparator_Tools_Bottom.Visible = false; } } break; } } } //--// private void SetWaitCursor( Hst.Forms.HostingSite.ExecutionState state ) { switch(state) { case Hst.Forms.HostingSite.ExecutionState.Idle : case Hst.Forms.HostingSite.ExecutionState.Loaded : case Hst.Forms.HostingSite.ExecutionState.Running: case Hst.Forms.HostingSite.ExecutionState.Paused : this.UseWaitCursor = false; break; default: this.UseWaitCursor = false; break; } } private void UpdateExecutionState( Hst.Forms.HostingSite.ExecutionState state ) { toolStripButton_Start .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Loaded || state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_BreakAll .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Running; toolStripButton_StopDebugging .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused || state == Hst.Forms.HostingSite.ExecutionState.Running; toolStripButton_ShowNextStatement.Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_Restart .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepInto .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Loaded || state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepOver .Enabled = state == Hst.Forms.HostingSite.ExecutionState.Paused ; toolStripButton_StepOut .Enabled = m_activeThread != null && m_activeThread.StackTrace.Count > 1; toolStripStatus_ExecutionState.Text = state.ToString(); SetWaitCursor( state ); var oldState = m_currentState; m_currentState = state; m_hostingSiteImpl.RaiseNotification( oldState, state ); } private void DisplayExecutionTime() { ulong diff_clockTicks = m_currentSample_clockTicks - m_lastSample_clockTicks; ulong diff_nanoseconds = m_currentSample_nanoseconds - m_lastSample_nanoseconds; ulong base_clockTicks = m_currentSample_clockTicks - m_baseSample_clockTicks; ulong base_nanoseconds = m_currentSample_nanoseconds - m_baseSample_nanoseconds; // // \u0393 = Greek Delta // \u00b5 = Greek micro // toolStripStatus_AbsoluteTime.Text = string.Format( "Clks={0} (\u0394={2}) \u00B5Sec={1} (\u0394={3})", base_clockTicks, (double)base_nanoseconds / 1000.0, diff_clockTicks, (double)diff_nanoseconds / 1000.0 ); } private void EnteringState_Running() { m_threads.Clear(); m_activeThread = null; m_selectedThread = null; ResetVisualEffects(); SwitchToFile( null, null ); } private void ExitingState_Running( Debugging.DebugInfo diTarget ) { if(m_imageInformation != null) { m_activeThread = ThreadStatus.Analyze( m_threads, m_processorHost.MemoryDelta, m_processorHost.Breakpoints ); m_selectedThread = m_activeThread; if(diTarget != null) { m_activeThread.TopStackFrame.MoveForwardToDebugInfo( diTarget ); } UpdateDisplay( true ); } } private void ProcessCodeCoverage() { Emulation.Hosting.CodeCoverage svc; if(m_processorHost.GetHostingService( out svc )) { if(svc.Enable) { m_imageInformation.CollectCodeCoverage( m_processorHost ); foreach(VisualTreeInfo vti in m_visualTreesList) { List < ImageInformation.RangeToSourceCode > lst; GrowOnlyHashTable< Debugging.DebugInfo, ulong > ht = HashTableFactory.New< Debugging.DebugInfo, ulong >(); if(m_imageInformation.FileToCodeLookup.TryGetValue( vti.Input.File.ToUpper(), out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { ImageInformation.RangeToSourceCode.CodeCoverage profile = rng.Profile; if(profile != null) { foreach(var pair in rng.DebugInfos) { ulong count; ht.TryGetValue( pair.Info, out count ); count += profile.Cycles; ht[pair.Info] = count; } } } } ulong max = 0; foreach(Debugging.DebugInfo di in ht.Keys) { max = Math.Max( ht[di], max ); } if(max != 0) { double scale = 1.0 / max; foreach(Debugging.DebugInfo di in ht.Keys) { double ratio = ht[di] * scale; Brush brush = new SolidBrush( Color.FromArgb( (int)(255 * ratio), 255, 0, 0 ) ); vti.HighlightSourceCode( codeView1, uint.MaxValue, di, null, null, brush, c_visualEffect_Depth_Profile ); } } } } } } //--// public bool LocateVisualTreeForDebugInfo( Debugging.DebugInfo di , out VisualTreeInfo vti , out VisualItem bringIntoView ) { vti = null; bringIntoView = null; if(di != null) { string file = di.SrcFileName; vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { for(int lineNum = di.BeginLineNumber; lineNum <= di.EndLineNumber; lineNum++) { bringIntoView = vti.FindLine( lineNum ); if(bringIntoView != null) { break; } } return true; } } return false; } public void VisualizeFile( string file ) { VisualTreeInfo vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { SwitchToFile( vti, null ); } } public void VisualizeDebugInfo( Debugging.DebugInfo di ) { VisualTreeInfo vti; VisualItem bringIntoView; if(LocateVisualTreeForDebugInfo( di, out vti, out bringIntoView )) { SwitchToFile( vti, bringIntoView ); this.BringToFront(); } } public void VisualizeStackFrame( StackFrame sf ) { VisualTreeInfo vti; VisualItem bringIntoView; m_selectedThread = sf.Thread; m_selectedThread.StackFrame = sf; LocateVisualTreeForDebugInfo( sf.DebugInfo, out vti, out bringIntoView ); PrepareDisplay( vti, sf, bringIntoView ); NotifyNewStackFrame(); } private void SwitchToFile( VisualTreeInfo vti , VisualItem bringIntoView ) { if(vti != null) { m_visualTreesList.Remove( vti ); m_visualTreesList.Insert( 0, vti ); UpdateCheckedStatusForFiles( vti ); codeView1.InstallVisualTree( vti, bringIntoView ); } else { codeView1.RefreshVisualTree(); } } private void UpdateCheckedStatusForFiles( VisualTreeInfo vti ) { ToolStripItemCollection coll = toolStripMenuItem_Windows.DropDownItems; // // Remove previous files. // int index = coll.IndexOf( this.toolStripSeparator_Files ); while(index + 1 < coll.Count) { coll.RemoveAt( index + 1 ); } // // Have separator only if there are open files. // this.toolStripSeparator_Files.Visible = index > 0 && (m_visualTreesList.Count != 0); for(int pos = 0; pos < m_visualTreesList.Count; pos++) { VisualTreeInfo vti2 = m_visualTreesList[pos]; ToolStripMenuItem newItem = new ToolStripMenuItem(); int fileIdx = pos + 1; IR.SourceCodeTracker.SourceCode srcFile = vti2.Input; newItem.Text = string.Format( fileIdx < 10 ? "&{0} {1}{2}" : "{0} {1}{2}", fileIdx, vti2.DisplayName, (srcFile != null && srcFile.UsingCachedValues) ? " <cached>" : "" ); newItem.Tag = vti2; newItem.Checked = (vti2 == vti); newItem.Click += new System.EventHandler( delegate( object sender, EventArgs e ) { SwitchToFile( vti2, null ); } ); coll.Add( newItem ); } } //--// private void UpdateDisplay( bool fProcessCodeCoverage ) { ResetVisualEffects(); if(fProcessCodeCoverage) { ProcessCodeCoverage(); } VisualTreeInfo switchToVti; VisualItem bringIntoView; CreateVisualEffects( out switchToVti, out bringIntoView ); PrepareDisplay( switchToVti, m_selectedThread.StackFrame, bringIntoView ); SynchronizeBreakpointsUI(); NotifyNewStackFrame(); } private void ResetVisualEffects() { foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { vti.EnumerateVisualEffects( delegate( VisualEffect ve ) { if(ve is VisualEffect.InlineDisassembly) { return VisualTreeInfo.CallbackResult.Delete; } if(ve is VisualEffect.SourceCodeHighlight) { if(ve.Context == null) { return VisualTreeInfo.CallbackResult.Delete; } } return VisualTreeInfo.CallbackResult.Keep; } ); } } private void CreateVisualEffects( out VisualTreeInfo switchToVti , out VisualItem bringIntoView ) { GrowOnlySet< Debugging.DebugInfo > visited = SetFactory.NewWithReferenceEquality< Debugging.DebugInfo >(); switchToVti = null; bringIntoView = null; m_versionStackTrace++; foreach(StackFrame sf in m_selectedThread.StackTrace) { Debugging.DebugInfo di = sf.DebugInfo; if(di != null) { string file = di.SrcFileName; VisualTreeInfo vti = codeView1.CreateVisualTree( m_imageInformation, file, file ); if(vti != null) { VisualEffect.SourceCodeHighlight ve; if(sf.Depth == 0) { ve = vti.HighlightSourceCode( codeView1, sf.ProgramCounter, di, m_icon_CurrentStatement, null, m_brush_CurrentPC, c_visualEffect_Depth_CurrentStatement ); } else { if(visited.Contains( di ) == false) { ve = vti.HighlightSourceCode( codeView1, sf.ProgramCounter, di, m_icon_StackFrame, null, m_brush_PastPC, c_visualEffect_Depth_OnTheStackTrace ); } else { ve = null; } } if(ve != null && sf == m_selectedThread.StackFrame) { switchToVti = vti; bringIntoView = ve.TopSelectedLine; } } visited.Insert( di ); } } } private void PrepareDisplay( VisualTreeInfo vti , StackFrame sf , VisualItem bringIntoView ) { if(vti == null) { vti = codeView1.CreateEmptyVisualTree( "<disassembly>" ); } vti.ClearVisualEffects( typeof(VisualEffect.InlineDisassembly) ); if(m_currentSession.DisplayDisassembly || sf == null) { InstallDisassemblyBlock( vti, sf ); } SwitchToFile( vti, bringIntoView ); } private void InstallDisassemblyBlock( VisualTreeInfo vti , StackFrame sf ) { List< ImageInformation.DisassemblyLine > disasm; ContainerVisualItem line = null; uint pastOpcodesToDisassembly = m_currentSession.PastOpcodesToDisassembly; uint futureOpcodesToDisassembly = m_currentSession.FutureOpcodesToDisassembly; if(sf != null && sf.Region != null && sf.DebugInfo != null) { disasm = sf.DisassembleBlock( m_processorHost.MemoryDelta, pastOpcodesToDisassembly, futureOpcodesToDisassembly ); line = vti.FindLine( sf.DebugInfo.EndLineNumber ); } else { ContainerVisualItem topElement = vti.VisualTreeRoot; GraphicsContext ctx = codeView1.CtxForLayout; topElement.Clear(); line = new ContainerVisualItem( null ); topElement.Add( line ); TextVisualItem item = new TextVisualItem( null, "<No Source Code Available>" ); item.PrepareText( ctx ); line.Add( item ); //--// disasm = new List< ImageInformation.DisassemblyLine >(); Emulation.Hosting.ProcessorStatus svc; m_processorHost.GetHostingService( out svc ); uint address = svc.ProgramCounter; uint addressStart = address - 3 * pastOpcodesToDisassembly * sizeof(uint); uint addressEnd = address + 3 * futureOpcodesToDisassembly * sizeof(uint); m_imageInformation.DisassembleBlock( m_processorHost.MemoryDelta, disasm, addressStart, address, addressEnd ); } if(disasm.Count > 0) { vti.InstallDisassemblyBlock( line, codeView1, disasm.ToArray(), c_visualEffect_Depth_Disassembly ); SynchronizeBreakpointsUI(); } } //--// public static void GrayOutRowInDataGridView( DataGridViewRow row ) { foreach(DataGridViewCell cell in row.Cells) { cell.Style.SelectionBackColor = SystemColors.Window; cell.Style.SelectionForeColor = SystemColors.GrayText; cell.Style.ForeColor = SystemColors.GrayText; } } public static void GrayOutRowsInDataGridView( DataGridViewRowCollection rows ) { foreach(DataGridViewRow row in rows) { GrayOutRowInDataGridView( row ); } } //--// void ProcessKeyDownEvent( KeyEventArgs e ) { if(e.Handled == false) { bool fGot = false; switch(e.KeyCode) { case Keys.Up: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheStackTrace( -1 ); fGot = true; break; } break; case Keys.Down: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheStackTrace( 1 ); fGot = true; break; } break; case Keys.Left: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheThreadList( -1 ); fGot = true; break; } break; case Keys.Right: switch(e.Modifiers) { case Keys.Control: Action_MoveInTheThreadList( 1 ); fGot = true; break; } break; case Keys.F5: switch(e.Modifiers) { case Keys.Control | Keys.Shift: Action_Restart(); fGot = true; break; case Keys.Shift: Action_StopDebugging(); fGot = true; break; case Keys.None: Action_Start(); fGot = true; break; } break; case Keys.Cancel: switch(e.Modifiers) { case Keys.Control | Keys.Alt: Action_BreakAll(); fGot = true; break; } break; case Keys.F10: switch(e.Modifiers) { case Keys.None: Action_StepOver(); fGot = true; break; } break; case Keys.F11: switch(e.Modifiers) { case Keys.None: Action_StepInto(); fGot = true; break; case Keys.Control: Action_ToggleDisassembly(); fGot = true; break; case Keys.Shift: Action_StepOut(); fGot = true; break; } break; } if(fGot) { e.Handled = true; e.SuppressKeyPress = true; } } } void ProcessKeyUpEvent( KeyEventArgs e ) { } //--// private void NotifyNewStackFrame() { ExecuteInFormThread( delegate() { m_hostingSiteImpl.RaiseNotification( Hst.Forms.HostingSite.VisualizationEvent.NewStackFrame ); } ); } private void SynchronizeBreakpointsUI() { ExecuteInFormThread( delegate() { foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { vti.EnumerateVisualEffects( delegate( VisualEffect ve ) { if(ve is VisualEffect.SourceCodeHighlight) { if(ve.Context is Emulation.Hosting.Breakpoint) { return VisualTreeInfo.CallbackResult.Delete; } } return VisualTreeInfo.CallbackResult.Keep; } ); } foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(bp.ShowInUI) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di )) { if(bp.DebugInfo != null) { di = bp.DebugInfo; } if(di != null) { string file = di.SrcFileName; VisualTreeInfo vti = codeView1.GetVisualTree( file ); if(vti != null) { VisualEffect.SourceCodeHighlight ve; if(bp.IsActive) { ve = vti.HighlightSourceCode( codeView1, uint.MaxValue, di, m_icon_Breakpoint, null, m_brush_Breakpoint, c_visualEffect_Depth_Breakpoint ); } else { ve = vti.HighlightSourceCode( codeView1, uint.MaxValue, di, m_icon_BreakpointDisabled, m_pen_Breakpoint, null, c_visualEffect_Depth_Breakpoint ); } ve.Context = bp; ve.Version = bp.Version; } } } foreach(VisualTreeInfo vti in codeView1.VisualTrees.Values) { VisualEffect.SourceCodeHighlight ve; if(bp.IsActive) { ve = vti.HighlightSourceCode( codeView1, bp.Address, null, m_icon_Breakpoint, null, m_brush_Breakpoint, c_visualEffect_Depth_Breakpoint ); } else { ve = vti.HighlightSourceCode( codeView1, bp.Address, null, m_icon_BreakpointDisabled, m_pen_Breakpoint, null, c_visualEffect_Depth_Breakpoint ); } ve.Context = bp; ve.Version = bp.Version; } } } codeView1.RefreshVisualTree(); m_hostingSiteImpl.RaiseNotification( Hst.Forms.HostingSite.VisualizationEvent.BreakpointsChange ); } ); } // // Access Methods // public Hst.Forms.HostingSite HostingSite { get { return m_hostingSiteImpl; } } public Hst.AbstractHost Host { get { return m_processorHost; } } public MemoryDelta MemoryDelta { get { return m_processorHost.MemoryDelta; } } public ImageInformation ImageInformation { get { return m_imageInformation; } } public int VersionBreakpoints { get { return m_versionBreakpoints; } } //--// public Hst.Forms.HostingSite.ExecutionState CurrentState { get { return m_currentState; } } public Session CurrentSession { get { return m_currentSession; } set { m_currentSession = value; InnerAction_LoadImage(); } } //--// public List< ThreadStatus > Threads { get { return m_threads; } } public ThreadStatus ActiveThread { get { return m_activeThread; } } public ThreadStatus SelectedThread { get { return m_selectedThread; } } public StackFrame SelectedStackFrame { get { if(m_selectedThread != null) { return m_selectedThread.StackFrame; } return null; } } public int VersionStackTrace { get { return m_versionStackTrace; } } //--// public Configuration.Environment.Manager ConfigurationManager { get { return m_configurationManager; } } //--// public bool IsIdle { get { switch(m_currentState) { case Hst.Forms.HostingSite.ExecutionState.Idle: case Hst.Forms.HostingSite.ExecutionState.Loaded: case Hst.Forms.HostingSite.ExecutionState.Paused: return true; } return false; } } // // Event Methods // private void codeView1_HitSink( CodeView owner , VisualItem origin , PointF relPos , MouseEventArgs e , bool fDown , bool fUp ) { VisualTreeInfo vti = codeView1.ActiveVisualTree; if(vti != null) { if(fDown && e.Clicks >= 2) { Debugging.DebugInfo diTarget = origin.Context as Debugging.DebugInfo; if(diTarget != null) { List< ImageInformation.RangeToSourceCode > lst; Debugging.DebugInfo diTargetLine; Debugging.DebugInfo diClosest = null; bool fClosestIntersects = false; string fileName = vti.Input.File; diTargetLine = Debugging.DebugInfo.CreateMarkerForLine( diTarget.SrcFileName, diTarget.MethodName, diTarget.BeginLineNumber ); if(m_imageInformation.FileToCodeLookup.TryGetValue( fileName.ToUpper(), out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { foreach(var pair in rng.DebugInfos) { Debugging.DebugInfo di = pair.Info; if(di.SrcFileName == fileName) { Debugging.DebugInfo diLine = diTargetLine.ComputeIntersection( di ); if(diLine != null) { Debugging.DebugInfo diIntersection = diTarget.ComputeIntersection( di ); if(diIntersection != null) { if(diClosest == null || di.IsContainedIn( diClosest ) || fClosestIntersects == false) { diClosest = di; fClosestIntersects = true; } } else { if(diClosest == null) { diClosest = di; } else if(fClosestIntersects == false) { int diff1 = Math.Abs( di .BeginColumn - diTarget.BeginColumn ); int diff2 = Math.Abs( diClosest.BeginColumn - diTarget.BeginColumn ); if(diff1 < diff2) { diClosest = di; } } } } } } } } if(diClosest != null) { // // Remove all the existing break points having the same DebugInfo. // bool fAdd = true; foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; bool fDelete = false; if(bp.DebugInfo == diClosest) { fDelete = true; } else { if(m_imageInformation.LocateFirstSourceCode( bp.Address, out reg, out offset, out di )) { if(di == diClosest) { fDelete = true; } } } if(fDelete) { Action_RemoveBreakpoint( bp ); fAdd = false; } } if(fAdd && m_imageInformation.SourceCodeToCodeLookup.TryGetValue( diClosest, out lst )) { foreach(ImageInformation.RangeToSourceCode rng in lst) { Action_SetBreakpoint( rng.BaseAddress, diClosest, true, false, null ); break; } } } } var disasm = origin.Context as ImageInformation.DisassemblyLine; if(disasm != null) { IR.ImageBuilders.SequentialRegion reg; uint offset; Debugging.DebugInfo di; if(m_imageInformation.LocateFirstSourceCode( disasm.Address, out reg, out offset, out di )) { // // Remove all the existing break points having the same DebugInfo. // bool fAdd = true; foreach(Emulation.Hosting.Breakpoint bp in m_processorHost.Breakpoints) { if(disasm.Address == bp.Address) { Action_RemoveBreakpoint( bp ); fAdd = false; } } if(fAdd) { Action_SetBreakpoint( disasm.Address, di, true, false, null ); } } } } } } private void DebuggerMainForm_Load( object sender, EventArgs e ) { m_processorWorker.Start(); } private void DebuggerMainForm_KeyDown( object sender , KeyEventArgs e ) { ProcessKeyDownEvent( e ); } private void DebuggerMainForm_FormClosing( object sender , FormClosingEventArgs e ) { foreach(Hst.AbstractUIPlugIn plugIn in m_plugIns) { plugIn.Stop(); } ExecuteInWorkerThread( Hst.Forms.HostingSite.ExecutionState.Invalid, delegate() { m_processorWorkerExit = true; } ); InnerAction_StopExecution(); m_processorWorker.Join(); m_sessionManagerForm.SaveSessions(); } //--// private void toolStripMenuItem_File_Open_Click( object sender , EventArgs e ) { Action_LoadImage(); } private void toolStripMenuItem_File_Session_Load_Click( object sender , EventArgs e ) { Action_LoadSession(); } private void toolStripMenuItem_File_Session_Edit_Click( object sender , EventArgs e ) { Action_EditConfiguration(); } private void toolStripMenuItem_File_Session_Save_Click( object sender , EventArgs e ) { if(m_currentSession.SettingsFile != null) { Action_SaveSession( m_currentSession.SettingsFile ); } } private void toolStripMenuItem_File_Session_SaveAs_Click( object sender , EventArgs e ) { Action_SaveSession(); } private void toolStripMenuItem_File_Exit_Click( object sender , EventArgs e ) { this.Close(); } //--// private void toolStripMenuItem_Tools_SessionManager_Click( object sender , EventArgs e ) { Session session = m_sessionManagerForm.SelectSession( false ); if(session != null && session != m_currentSession) { m_currentSession = session; if(InnerAction_LoadImage() == false) { m_imageInformation = null; } } } //--// private void toolStripButton_Start_Click( object sender , EventArgs e ) { Action_Start(); } private void toolStripButton_BreakAll_Click( object sender , EventArgs e ) { Action_BreakAll(); } private void toolStripButton_StopDebugging_Click( object sender , EventArgs e ) { Action_StopDebugging(); } private void toolStripButton_Restart_Click( object sender , EventArgs e ) { Action_Restart(); } private void toolStripButton_ShowNextStatement_Click( object sender , EventArgs e ) { if(m_activeThread != null) { m_selectedThread = m_activeThread; m_activeThread.StackFrame = m_activeThread.TopStackFrame; Action_SelectThread( this.Threads.IndexOf( m_activeThread ) ); } } private void toolStripButton_StepInto_Click( object sender , EventArgs e ) { Action_StepInto(); } private void toolStripButton_StepOver_Click( object sender, EventArgs e ) { Action_StepOver(); } private void toolStripButton_StepOut_Click( object sender, EventArgs e ) { Action_StepOut(); } private void toolStripButton_ToggleDisassembly_Click( object sender, EventArgs e ) { Action_ToggleDisassembly(); } private void toolStripButton_ToggleWrapper_Click( object sender, EventArgs e ) { Action_ToggleWrapper(); } //--// private void statusTrip1_DoubleClick( object sender, EventArgs e ) { if(this.IsIdle) { Action_ResetAbsoluteTime(); DisplayExecutionTime(); } } } }
// // MRGamePieceStack.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // 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 UnityEngine; using System.Collections; using System.Collections.Generic; using AssemblyCSharp; namespace PortableRealm { /// <summary> /// A stack of pieces. Responsible for setting the pieces positions and layer. /// </summary> public class MRGamePieceStack : MonoBehaviour, MRISerializable, MRITouchable { #region Properties public string Name { get{ return mName; } set{ mName = value; } } public IList<MRIGamePiece> Pieces { get{ return mPieces; } } public int Count { get{ return mPieces.Count; } } public int Layer { get{ return mLayer; } set{ if (value >= 0 && value < 32) { mLayer = value; gameObject.layer = value; // set the layer of our pieces foreach (MRIGamePiece piece in mPieces) piece.Layer = mLayer; } else { Debug.LogError("Trying to set game piece stack to layer " + value); } } } public bool Inspecting { get{ return mInspecting; } set{ if (value != mInspecting) { mInspecting = value; mInspectionOffset = 0; foreach (MRIGamePiece piece in mPieces) { if (mInspecting) { SetPieceInspectionPos(piece); } else { SetPieceBasePos(piece); } } } } } public float StackScale { get{ return mStackScale; } set{ mStackScale = value; if (!mInspecting) { for (int i = 0; i < mPieces.Count; ++i) { MRIGamePiece piece = mPieces[i]; piece.LocalScale = new Vector3(piece.OldScale.x * mStackScale, piece.OldScale.y * mStackScale, 1f); } } } } public bool Visible { get{ return mVisible; } set{ mVisible = value; foreach (MRIGamePiece piece in mPieces) { piece.Visible = mVisible; } } } #endregion #region Methods /// <summary> /// Called when the script is loaded. /// </summary> void Awake() { mInspecting = false; mStackScale = 1.0f; } /// <summary> /// Called when the script is enabled, before the first Update call. /// </summary> void Start () { } // Update is called once per frame void Update () { // adjust piece position if (mInspecting) { // draw the pieces in the inspection area if (MRGame.IsTouching) { // adjust the top offset for the user dragging the view Camera inspectionCamera = MRGame.TheGame.InspectionArea.InspectionCamera; Vector3 worldTouch = inspectionCamera.ScreenToWorldPoint(new Vector3(MRGame.LastTouchPos.x, MRGame.LastTouchPos.y, inspectionCamera.nearClipPlane)); if (MRGame.TheGame.InspectionArea.InspectionBoundsWorld.Contains(worldTouch)) { if (MRGame.JustTouched) mLastTouchPos = MRGame.LastTouchPos; else { //Vector2 deltaTouch = MRGame.LastTouchPos - mLastTouchPos; mInspectionOffset += worldTouch.y - inspectionCamera.ScreenToWorldPoint(new Vector3(mLastTouchPos.x, mLastTouchPos.y, inspectionCamera.nearClipPlane)).y; mLastTouchPos = MRGame.LastTouchPos; } } } SetInspectionPositions(); } else { // stack the pieces float zpos = transform.position.z - 0.1f; for (int i = mPieces.Count - 1; i >= 0; --i) { MRIGamePiece piece = mPieces[i]; piece.Position = new Vector3(transform.position.x, transform.position.y, zpos); // if the piece is a MonoBehavior, it will be updated by the system if (!(piece is MonoBehaviour)) piece.Update(); zpos -= 0.2f; } } } public bool OnTouched(GameObject touchedObject) { return true; } public bool OnReleased(GameObject touchedObject) { return true; } public bool OnSingleTapped(GameObject touchedObject) { return true; } public bool OnDoubleTapped(GameObject touchedObject) { if (mInspecting || mPieces.Count == 1) { // see if a piece was selected Camera camera = null; if (mInspecting) camera = MRGame.TheGame.InspectionArea.InspectionCamera; else { foreach (Camera testCamera in Camera.allCameras) { if ((testCamera.cullingMask & (1 << gameObject.layer)) != 0) { camera = testCamera; break; } } } if (camera != null) { Vector3 worldTouch = camera.ScreenToWorldPoint(new Vector3(MRGame.LastTouchPos.x, MRGame.LastTouchPos.y, camera.nearClipPlane)); for (int i = 0; i < mPieces.Count; ++i) { MRIGamePiece piece = mPieces[i]; Bounds bounds = piece.Bounds; if (worldTouch.x - piece.Position.x >= bounds.min.x * piece.LocalScale.x && worldTouch.x - piece.Position.x <= bounds.max.x * piece.LocalScale.x && worldTouch.y - piece.Position.y >= bounds.min.y * piece.LocalScale.y && worldTouch.y - piece.Position.y <= bounds.max.y * piece.LocalScale.y) { Debug.Log ("Select piece " + piece.Name); MRGame.TheGame.OnGamePieceSelectedGame(piece); break; } } } } return true; } public bool OnTouchHeld(GameObject touchedObject) { return true; } public virtual bool OnTouchMove(GameObject touchedObject, float delta_x, float delta_y) { return true; } public bool OnButtonActivate(GameObject touchedObject) { return true; } public bool OnPinchZoom(float pinchDelta) { return true; } /// <summary> /// Adds a piece to the top of the stack. /// </summary> /// <param name="piece">the piece</param> public void AddPieceToTop(MRIGamePiece piece) { if (piece.Stack != null) piece.Stack.RemovePiece(piece); piece.Stack = this; mPieces.Insert(0, piece); piece.OldScale = piece.LocalScale; SetPieceBasePos(piece); if (Inspecting) SetPieceInspectionPos(piece); } /// <summary> /// Adds a piece to the bottom of the stack. /// </summary> /// <param name="piece">the piece</param> public void AddPieceToBottom(MRIGamePiece piece) { if (piece.Stack != null) piece.Stack.RemovePiece(piece); piece.Stack = this; mPieces.Insert(mPieces.Count, piece); piece.OldScale = piece.LocalScale; SetPieceBasePos(piece); if (Inspecting) SetPieceInspectionPos(piece); } /// <summary> /// Adds a piece at a given position in the stack. /// </summary> /// <param name="piece">the piece</param> /// <param name="index">position in the stack to add it</param> public void AddPieceAt(MRIGamePiece piece, int index) { if (piece.Stack != null) piece.Stack.RemovePiece(piece); piece.Stack = this; if (index < 0) index = 0; else if (index > mPieces.Count) index = mPieces.Count; mPieces.Insert(index, piece); piece.OldScale = piece.LocalScale; SetPieceBasePos(piece); if (Inspecting) SetPieceInspectionPos(piece); } /// <summary> /// Adds a piece before (over) a given piece. If the target piece is null or not in the stack, /// the priece will be added at the top of the stack. /// </summary> /// <param name="piece">the piece</param> /// <param name="target">piece the piece will be placed under</param> public void AddPieceBefore(MRIGamePiece piece, MRIGamePiece target) { if (piece.Stack != null) piece.Stack.RemovePiece(piece); piece.Stack = this; int index = 0; if (target != null) { index = mPieces.IndexOf(target); if (index < 0) index = 0; } mPieces.Insert(index, piece); piece.OldScale = piece.LocalScale; SetPieceBasePos(piece); if (Inspecting) SetPieceInspectionPos(piece); } /// <summary> /// Adds a piece after (under) a given piece. If the target piece is null or not in the stack, /// the priece will be added at the top of the stack. /// </summary> /// <param name="piece">the piece</param> /// <param name="target">piece the piece will be placed under</param> public void AddPieceAfter(MRIGamePiece piece, MRIGamePiece target) { if (piece.Stack != null) piece.Stack.RemovePiece(piece); piece.Stack = this; int index = 0; if (target != null) { index = mPieces.IndexOf(target) + 1; if (index < 1) index = 0; } mPieces.Insert(index, piece); piece.OldScale = piece.LocalScale; SetPieceBasePos(piece); if (Inspecting) SetPieceInspectionPos(piece); } /// <summary> /// Removes a piece from the stack. /// </summary> /// <param name="piece">the piece to remove</param> public void RemovePiece(MRIGamePiece piece) { if (mPieces.Contains(piece)) { // SetPieceBasePos(piece); piece.OldScale = Vector3.one; piece.LocalScale = Vector3.one; mPieces.Remove(piece); piece.Layer = LayerMask.NameToLayer("Dummy"); piece.Stack = null; piece.Visible = false; } } /// <summary> /// Sorts the items in the stack, with the biggest objects on the bottom. However, character chits will be put on top, /// and monsters will be put over their head/club counters. /// </summary> public void SortBySize() { mPieces.Sort( delegate(MRIGamePiece x, MRIGamePiece y) { if (Object.ReferenceEquals(x, y)) return 0; // current character takes precidence if (x is MRCharacter && (MRCharacter)x == MRGame.TheGame.ActiveControllable) return -1; else if (y is MRCharacter && (MRCharacter)y == MRGame.TheGame.ActiveControllable) return 1; else return x.SortValue - y.SortValue; } ); } /// <summary> /// Removes all game pieces from this stack. /// </summary> public void Clear() { while (mPieces.Count > 0) { MRIGamePiece piece = mPieces[0]; RemovePiece(piece); } //foreach (MRIGamePiece piece in mPieces) //{ // SetPieceBasePos(piece); // piece.Stack = null; //} //mPieces.Clear(); } private void SetPieceBasePos(MRIGamePiece piece) { piece.Layer = mLayer; piece.Parent = transform; piece.LocalScale = new Vector3(piece.OldScale.x * mStackScale, piece.OldScale.y * mStackScale, 1f); piece.Rotation = Quaternion.identity; piece.Visible = mVisible; } private void SetPieceInspectionPos(MRIGamePiece piece) { piece.Layer = LayerMask.NameToLayer("InspectionList"); piece.OldScale = new Vector3(piece.LocalScale.x / mStackScale, piece.LocalScale.y / mStackScale, 1f); float inspectionScale = 2.0f / piece.Parent.localScale.x; piece.LocalScale = new Vector3(inspectionScale, inspectionScale, 1f); } private void SetInspectionPositions() { if (mPieces.Count == 0) return; if (mInspectionOffset < 0) mInspectionOffset = 0; // display the pieces in the inspection area Camera inspectionCamera = MRGame.TheGame.InspectionArea.InspectionCamera; float pieceTopPos = MRGame.TheGame.InspectionArea.InspectionBoundsWorld.yMax; float spacing = pieceTopPos - inspectionCamera.ScreenToWorldPoint(new Vector3(0, MRGame.TheGame.InspectionArea.InspectionBoundsPixels.height - 15, 0)).y; for (int i = 0; i < mPieces.Count; ++i) { MRIGamePiece piece = mPieces[i]; Bounds bounds = piece.Bounds; piece.Position = new Vector3(0, mInspectionOffset + pieceTopPos - bounds.extents.y * piece.LossyScale.y, 2f); pieceTopPos -= bounds.size.y * piece.LossyScale.y + spacing; } // if we're scrolling, make sure the bottom piece isn't too high pieceTopPos += mInspectionOffset; if (mInspectionOffset > 0 && pieceTopPos > MRGame.TheGame.InspectionArea.InspectionBoundsWorld.yMin) { mInspectionOffset -= (pieceTopPos - MRGame.TheGame.InspectionArea.InspectionBoundsWorld.yMin); SetInspectionPositions(); } } public bool Load(JSONObject root) { JSONArray pieces = (JSONArray)root["pieces"]; for (int i = 0; i < pieces.Count; ++i) { MRIGamePiece piece = MRGame.TheGame.GetGamePiece(pieces[i]); if (piece != null) { AddPieceToBottom(piece); } } return true; } public void Save(JSONObject root) { JSONArray pieces = new JSONArray(mPieces.Count); for (int i = 0; i < mPieces.Count; ++i) { if (mPieces[i].Id != 0) pieces[i] = new JSONNumber(mPieces[i].Id); else { Debug.LogError("Trying to save clearing piece with id 0"); } } root["pieces"] = pieces; } #endregion #region Members // The list of pieces, in order of topmost to bottommost private List<MRIGamePiece> mPieces = new List<MRIGamePiece>(); private int mLayer; private bool mInspecting; private float mInspectionOffset; private float mStackScale; private Vector2 mLastTouchPos; private string mName = ""; private bool mVisible = true; #endregion } }
// Copyright (c) MOSA Project. Licensed under the New BSD License. using System.Collections.Generic; using System.Runtime.InteropServices; namespace Mosa.TestWorld.x86.Tests { public class OtherTest : KernelTest { public OtherTest() : base("Other") { testMethods.AddLast(OtherTest1); testMethods.AddLast(OtherTest2); testMethods.AddLast(OtherTest3); testMethods.AddLast(OtherTest4); testMethods.AddLast(OtherTest5); testMethods.AddLast(ForeachNestedTest); testMethods.AddLast(ForeachNested2Test); testMethods.AddLast(StructNewObjTest); testMethods.AddLast(StructNotBoxed); testMethods.AddLast(ForeachBreak); testMethods.AddLast(ConditionalBug); testMethods.AddLast(PointerBug); testMethods.AddLast(AddressOfThisBug); testMethods.AddLast(RemR4); testMethods.AddLast(RemR8); testMethods.AddLast(NullableTest1); testMethods.AddLast(NullableTest2); testMethods.AddLast(NullableTest3); testMethods.AddLast(NullableTest4); testMethods.AddLast(NullableTest5); } private static uint StaticValue = 0x200000; public static bool OtherTest1() { uint x = StaticValue; return x == 0x200000; } public static bool OtherTest2() { return StaticValue == 0x200000; } public static bool OtherTest3() { return 3.Equals(3); } public static bool OtherTest4() { return 3.Equals((object)3); } public static bool OtherTest5() { return ((object)3).Equals(3); } public static bool ForeachNestedTest() { var list = Populate(); var nestedList = Populate(); int sum = 0; int nestedSum = 0; int nestedCount = 0; foreach (var item in list) { sum = sum + item; foreach (var nestedItem in nestedList) { nestedSum = nestedSum + nestedItem; nestedSum = nestedSum / ++nestedCount; } } return (sum + nestedSum) == 4556; } public static bool ForeachNested2Test() { var list = Populate2(); int sum = 0; foreach (var item in list) { sum = sum + item; foreach (var nested in list) { sum = sum + nested; } } return sum == 1200; } private static LinkedList<int> Populate() { LinkedList<int> IntList = new LinkedList<int>(); for (int i = 1; i < 10; i++) { IntList.AddLast(101 * i); } return IntList; } private static LinkedList<int> Populate2() { var IntList = new LinkedList<int>(); IntList.AddLast(100); IntList.AddLast(300); return IntList; } public static bool StructNewObjTest() { Pair t1 = default(Pair); try { t1 = new Pair(5, 10); } catch { } return (t1.A == 5 && t1.B == 10); } public static bool StructNotBoxed() { NotBoxedStruct s = new NotBoxedStruct(); s.ToString(); s.ToString(); s.ToString(); return s.I == 3; } public static bool ForeachBreak() { LinkedList<Pair> PairList = new LinkedList<Pair>(); for (int i = 1; i < 10; i++) { Pair p = new Pair(10 * i, 20 * i); PairList.AddLast(p); } Pair found = FindPair(PairList); return (found.A == 90 && found.B == 180); } private static Pair FindPair(LinkedList<Pair> PairList) { foreach (Pair p in PairList) { if (p.A == 90 && p.B == 180) return p; } return new Pair(0, 0); } public static bool ConditionalBug() { uint address = 0x1000; Mosa.Platform.Internal.x86.Native.Set8(address, 81); var num = Mosa.Platform.Internal.x86.Native.Get8(address); if (num >= 32 && num < 128) return true; else return false; } public static bool PointerBug() { return PointerBugClass.Test(); } public static bool AddressOfThisBug() { return PointerBugClass.Test2(); } private static float f1 = 1.232145E+10f; private static float f2 = 2f; public static bool RemR4() { return (f1 % f2) == 0f; } private static double d1 = 1.232145E+10d; private static double d2 = 15d; public static bool RemR8() { return (d1 % d2) == 0d; } public static bool NullableTest1() { bool? v1 = true; return (v1 == true); } public static bool NullableTest2() { bool? v1 = null; return (v1 == null); } public static bool NullableTest3() { bool? v1 = null; return !(v1 == true); } public static bool NullableTest4() { bool? v1 = null; bool? v2 = true; return !(v1 == v2); } public static bool NullableTest5() { int? v1 = null; int? v2 = 32; long? v3 = v1 ?? v2; return (v3 == 32); } unsafe public static class PointerBugClass { private static uint pageDirectoryAddress = 0x1000; private static PageDirectoryEntry* pageDirectoryEntries; public static bool Test() { pageDirectoryEntries = (PageDirectoryEntry*)pageDirectoryAddress; return GetItem(1); } public static bool Test2() { return (uint)pageDirectoryEntries == pageDirectoryEntries->AddressOfThis; } internal static bool GetItem(uint index) { //increpmenting a pointer var addr1 = (uint)(pageDirectoryEntries + index); //increpmenting a UInt32 var addr2 = (uint)(pageDirectoryAddress + (index * 4)); //struct PageDirectoryEntry as a size of 4 bytes return addr1 == addr2; } [StructLayout(LayoutKind.Explicit)] unsafe public struct PageDirectoryEntry { [FieldOffset(0)] private uint data; public uint AddressOfThis { get { fixed (PageDirectoryEntry* ptr = &this) return (uint)ptr; } } } } } public struct TestStruct { public byte One; } public struct NotBoxedStruct { public int I; public override string ToString() { I++; return ""; } } public struct Pair { public int A; public int B; public Pair(int a, int b) { A = a; B = b; } } }
namespace BookShop.Server.Api.Areas.HelpPage.ModelDescriptions { 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.Web.Http; using System.Web.Http.Description; using Newtonsoft.Json; using System.Runtime.Serialization; using System.Xml.Serialization; /// <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; } } }
// // DataCore.cs // // Authors: // Gabriel Burt // Fredrik Hedberg // Aaron Bockover // Lukas Lipka // // Copyright (C) 2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Net; using System.Web; using System.Xml; using System.Collections; using System.Collections.Generic; using ICSharpCode.SharpZipLib.GZip; using Hyena; namespace Lastfm.Data { public sealed class DataCore { private const int CACHE_VERSION = 2; public static string UserAgent = null; //Banshee.Web.Browser.UserAgent; public static string CachePath = null; //Path.Combine (Banshee.Base.Paths.UserPluginDirectory, "recommendation"); public static TimeSpan NormalCacheTime = TimeSpan.FromHours (2); private static bool initialized = false; internal static void Initialize () { if (!initialized) { initialized = true; if (CachePath == null || UserAgent == null) { throw new NotSupportedException ("Lastfm.Data.DataCore.CachePath and/or Lastfm.Data.DataCore.Useragent are null. Applications must set this value."); } CheckForCacheWipe(); SetupCache(); } } public static string DownloadContent (string data_url) { return DownloadContent (data_url, CacheDuration.Infinite); } public static string DownloadContent (string data_url, CacheDuration cache_duration) { return DownloadContent (data_url, GetCachedPathFromUrl (data_url), cache_duration); } internal static string DownloadContent (string data_url, string cache_file, CacheDuration cache_duration) { if (String.IsNullOrEmpty (data_url) || String.IsNullOrEmpty (cache_file)) { return null; } data_url = FixLastfmUrl (data_url); // See if we have a valid cached copy if (cache_duration != CacheDuration.None) { if (File.Exists (cache_file)) { DateTime last_updated_time = File.GetLastWriteTime (cache_file); if (cache_duration == CacheDuration.Infinite || DateTime.Now - last_updated_time < DataCore.NormalCacheTime) { return cache_file; } } } HttpWebRequest request = (HttpWebRequest) WebRequest.Create (data_url); request.UserAgent = DataCore.UserAgent; request.KeepAlive = false; using (HttpWebResponse response = (HttpWebResponse) request.GetResponse ()) { using (Stream stream = GetResponseStream (response)) { using (FileStream file_stream = File.Open (cache_file, FileMode.Create)) { using (BufferedStream buffered_stream = new BufferedStream (file_stream)) { byte [] buffer = new byte[8192]; int read; while (true) { read = stream.Read (buffer, 0, buffer.Length); if (read <= 0) { break; } buffered_stream.Write (buffer, 0, read); } } } } } return cache_file; } public static string GetCachedPathFromUrl (string url) { if (url == null) { return null; } string hash = FixLastfmUrl (url).GetHashCode ().ToString ("X").ToLower (); if (hash.Length > 2) { return Path.Combine (Path.Combine (DataCore.CachePath, hash.Substring (0, 2)), hash); } else { return String.Empty; } } private static Stream GetResponseStream (HttpWebResponse response) { return response.ContentEncoding == "gzip" ? new GZipInputStream (response.GetResponseStream ()) : response.GetResponseStream (); } // FIXME: This is to (try to) work around a bug in last.fm's XML // Some XML nodes with URIs as content do not return a URI with a // host name. It appears that in these cases the hostname is to be // static3.last.fm, but it may not always be the case - this is // a bug in last.fm, but we attempt to work around it here // http://bugzilla.gnome.org/show_bug.cgi?id=408068 internal static string FixLastfmUrl (string url) { if (url.StartsWith ("http:///storable/")) { url = url.Insert (7, "static3.last.fm"); } return url; } private static void SetupCache() { bool clean = false; if(!Directory.Exists(CachePath)) { clean = true; Directory.CreateDirectory(CachePath); } // Create our cache subdirectories. for(int i = 0; i < 256; ++i) { string subdir = i.ToString("x"); if(i < 16) { subdir = "0" + subdir; } subdir = System.IO.Path.Combine(CachePath, subdir); if(!Directory.Exists(subdir)) { Directory.CreateDirectory(subdir); } } //RecommendationPlugin.CacheVersion.Set (CACHE_VERSION); if(clean) { Log.Debug("Recommendation Plugin", "Created a new cache layout"); } } private static void CheckForCacheWipe() { //bool wipe = false; if(!Directory.Exists(CachePath)) { return; } /*if (RecommendationPlugin.CacheVersion.Get() < CACHE_VERSION) { Directory.Delete(CachePath, true); Log.Debug("Recommendation Plugin", "Destroyed outdated cache"); }*/ } } }
#region License // /* // See license included in this library folder. // */ #endregion using System; using System.Collections.Generic; using System.Globalization; using Sqloogle.Libs.NLog.Config; using Sqloogle.Libs.NLog.Internal; using Sqloogle.Libs.NLog.Layouts; namespace Sqloogle.Libs.NLog.Conditions { /// <summary> /// Condition parser. Turns a string representation of condition expression /// into an expression tree. /// </summary> public class ConditionParser { private readonly ConfigurationItemFactory configurationItemFactory; private readonly ConditionTokenizer tokenizer; /// <summary> /// Initializes a new instance of the <see cref="ConditionParser" /> class. /// </summary> /// <param name="stringReader">The string reader.</param> /// <param name="configurationItemFactory"> /// Instance of <see cref="ConfigurationItemFactory" /> used to resolve references to condition methods and layout renderers. /// </param> private ConditionParser(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactory) { this.configurationItemFactory = configurationItemFactory; tokenizer = new ConditionTokenizer(stringReader); } /// <summary> /// Parses the specified condition string and turns it into /// <see cref="ConditionExpression" /> tree. /// </summary> /// <param name="expressionText">The expression to be parsed.</param> /// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns> public static ConditionExpression ParseExpression(string expressionText) { return ParseExpression(expressionText, ConfigurationItemFactory.Default); } /// <summary> /// Parses the specified condition string and turns it into /// <see cref="ConditionExpression" /> tree. /// </summary> /// <param name="expressionText">The expression to be parsed.</param> /// <param name="configurationItemFactories"> /// Instance of <see cref="ConfigurationItemFactory" /> used to resolve references to condition methods and layout renderers. /// </param> /// <returns>The root of the expression syntax tree which can be used to get the value of the condition in a specified context.</returns> public static ConditionExpression ParseExpression(string expressionText, ConfigurationItemFactory configurationItemFactories) { if (expressionText == null) { return null; } var parser = new ConditionParser(new SimpleStringReader(expressionText), configurationItemFactories); var expression = parser.ParseExpression(); if (!parser.tokenizer.IsEOF()) { throw new ConditionParseException("Unexpected token: " + parser.tokenizer.TokenValue); } return expression; } /// <summary> /// Parses the specified condition string and turns it into /// <see cref="ConditionExpression" /> tree. /// </summary> /// <param name="stringReader">The string reader.</param> /// <param name="configurationItemFactories"> /// Instance of <see cref="ConfigurationItemFactory" /> used to resolve references to condition methods and layout renderers. /// </param> /// <returns> /// The root of the expression syntax tree which can be used to get the value of the condition in a specified context. /// </returns> internal static ConditionExpression ParseExpression(SimpleStringReader stringReader, ConfigurationItemFactory configurationItemFactories) { var parser = new ConditionParser(stringReader, configurationItemFactories); var expression = parser.ParseExpression(); return expression; } private ConditionMethodExpression ParsePredicate(string functionName) { var par = new List<ConditionExpression>(); while (!tokenizer.IsEOF() && tokenizer.TokenType != ConditionTokenType.RightParen) { par.Add(ParseExpression()); if (tokenizer.TokenType != ConditionTokenType.Comma) { break; } tokenizer.GetNextToken(); } tokenizer.Expect(ConditionTokenType.RightParen); try { var methodInfo = configurationItemFactory.ConditionMethods.CreateInstance(functionName); return new ConditionMethodExpression(functionName, methodInfo, par); } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } throw new ConditionParseException("Cannot resolve function '" + functionName + "'", exception); } } private ConditionExpression ParseLiteralExpression() { if (tokenizer.IsToken(ConditionTokenType.LeftParen)) { tokenizer.GetNextToken(); var e = ParseExpression(); tokenizer.Expect(ConditionTokenType.RightParen); return e; } if (tokenizer.IsToken(ConditionTokenType.Minus)) { tokenizer.GetNextToken(); if (!tokenizer.IsNumber()) { throw new ConditionParseException("Number expected, got " + tokenizer.TokenType); } var numberString = tokenizer.TokenValue; tokenizer.GetNextToken(); if (numberString.IndexOf('.') >= 0) { return new ConditionLiteralExpression(-double.Parse(numberString, CultureInfo.InvariantCulture)); } return new ConditionLiteralExpression(-int.Parse(numberString, CultureInfo.InvariantCulture)); } if (tokenizer.IsNumber()) { var numberString = tokenizer.TokenValue; tokenizer.GetNextToken(); if (numberString.IndexOf('.') >= 0) { return new ConditionLiteralExpression(double.Parse(numberString, CultureInfo.InvariantCulture)); } return new ConditionLiteralExpression(int.Parse(numberString, CultureInfo.InvariantCulture)); } if (tokenizer.TokenType == ConditionTokenType.String) { ConditionExpression e = new ConditionLayoutExpression(Layout.FromString(tokenizer.StringTokenValue, configurationItemFactory)); tokenizer.GetNextToken(); return e; } if (tokenizer.TokenType == ConditionTokenType.Keyword) { var keyword = tokenizer.EatKeyword(); if (0 == string.Compare(keyword, "level", StringComparison.OrdinalIgnoreCase)) { return new ConditionLevelExpression(); } if (0 == string.Compare(keyword, "logger", StringComparison.OrdinalIgnoreCase)) { return new ConditionLoggerNameExpression(); } if (0 == string.Compare(keyword, "message", StringComparison.OrdinalIgnoreCase)) { return new ConditionMessageExpression(); } if (0 == string.Compare(keyword, "loglevel", StringComparison.OrdinalIgnoreCase)) { tokenizer.Expect(ConditionTokenType.Dot); return new ConditionLiteralExpression(LogLevel.FromString(tokenizer.EatKeyword())); } if (0 == string.Compare(keyword, "true", StringComparison.OrdinalIgnoreCase)) { return new ConditionLiteralExpression(true); } if (0 == string.Compare(keyword, "false", StringComparison.OrdinalIgnoreCase)) { return new ConditionLiteralExpression(false); } if (0 == string.Compare(keyword, "null", StringComparison.OrdinalIgnoreCase)) { return new ConditionLiteralExpression(null); } if (tokenizer.TokenType == ConditionTokenType.LeftParen) { tokenizer.GetNextToken(); var predicateExpression = ParsePredicate(keyword); return predicateExpression; } } throw new ConditionParseException("Unexpected token: " + tokenizer.TokenValue); } private ConditionExpression ParseBooleanRelation() { var e = ParseLiteralExpression(); if (tokenizer.IsToken(ConditionTokenType.EqualTo)) { tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Equal); } if (tokenizer.IsToken(ConditionTokenType.NotEqual)) { tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.NotEqual); } if (tokenizer.IsToken(ConditionTokenType.LessThan)) { tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Less); } if (tokenizer.IsToken(ConditionTokenType.GreaterThan)) { tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.Greater); } if (tokenizer.IsToken(ConditionTokenType.LessThanOrEqualTo)) { tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.LessOrEqual); } if (tokenizer.IsToken(ConditionTokenType.GreaterThanOrEqualTo)) { tokenizer.GetNextToken(); return new ConditionRelationalExpression(e, ParseLiteralExpression(), ConditionRelationalOperator.GreaterOrEqual); } return e; } private ConditionExpression ParseBooleanPredicate() { if (tokenizer.IsKeyword("not") || tokenizer.IsToken(ConditionTokenType.Not)) { tokenizer.GetNextToken(); return new ConditionNotExpression(ParseBooleanPredicate()); } return ParseBooleanRelation(); } private ConditionExpression ParseBooleanAnd() { var expression = ParseBooleanPredicate(); while (tokenizer.IsKeyword("and") || tokenizer.IsToken(ConditionTokenType.And)) { tokenizer.GetNextToken(); expression = new ConditionAndExpression(expression, ParseBooleanPredicate()); } return expression; } private ConditionExpression ParseBooleanOr() { var expression = ParseBooleanAnd(); while (tokenizer.IsKeyword("or") || tokenizer.IsToken(ConditionTokenType.Or)) { tokenizer.GetNextToken(); expression = new ConditionOrExpression(expression, ParseBooleanAnd()); } return expression; } private ConditionExpression ParseBooleanExpression() { return ParseBooleanOr(); } private ConditionExpression ParseExpression() { return ParseBooleanExpression(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace pltkw3msCustomer.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
/**************************************************************************** Copyright (c) 2010 cocos2d-x.org Copyright (c) 2011-2012 openxlive.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System.Collections.Generic; using Microsoft.Xna.Framework.Graphics; using System.Globalization; #if !WINDOWS_PHONE && !XBOX && !WINDOWS &&!NETFX_CORE && !PSM #if MACOS using MonoMac.OpenGL; #elif WINDOWSGL || LINUX using OpenTK.Graphics.OpenGL; #else using OpenTK.Graphics.ES20; using BeginMode = OpenTK.Graphics.ES20.All; using EnableCap = OpenTK.Graphics.ES20.All; using TextureTarget = OpenTK.Graphics.ES20.All; using BufferTarget = OpenTK.Graphics.ES20.All; using BufferUsageHint = OpenTK.Graphics.ES20.All; using DrawElementsType = OpenTK.Graphics.ES20.All; using GetPName = OpenTK.Graphics.ES20.All; using FramebufferErrorCode = OpenTK.Graphics.ES20.All; using FramebufferTarget = OpenTK.Graphics.ES20.All; using FramebufferAttachment = OpenTK.Graphics.ES20.All; using RenderbufferTarget = OpenTK.Graphics.ES20.All; using RenderbufferStorage = OpenTK.Graphics.ES20.All; #endif #endif namespace Cocos2D { public class CCUtils { #if !WINDOWS_PHONE && !XBOX && !PSM #if OPENGL private static List<string> _GLExtensions = null; public static List<string> GetGLExtensions() { // Setup extensions. if(_GLExtensions == null) { List<string> extensions = new List<string>(); #if GLES var extstring = GL.GetString(RenderbufferStorage.Extensions); GraphicsExtensions.CheckGLError(); #elif MACOS // for right now there are errors with GL before we even get here so the // CheckGLError for MACOS is throwing errors even though the extensions are read // correctly. Placed this here for now so that we can continue the processing // until we find the real error. var extstring = GL.GetString(StringName.Extensions); #else var extstring = GL.GetString(StringName.Extensions); GraphicsExtensions.CheckGLError(); #endif if (!string.IsNullOrEmpty(extstring)) { extensions.AddRange(extstring.Split(' ')); CCLog.Log("Supported GL extensions:"); foreach (string extension in extensions) CCLog.Log(extension); } _GLExtensions = extensions; } return _GLExtensions; } #endif #endif /// <summary> /// Returns the Cardinal Spline position for a given set of control points, tension and time /// </summary> /// <param name="p0"></param> /// <param name="p1"></param> /// <param name="p2"></param> /// <param name="p3"></param> /// <param name="tension"></param> /// <param name="t"></param> /// <returns></returns> public static CCPoint CCCardinalSplineAt(CCPoint p0, CCPoint p1, CCPoint p2, CCPoint p3, float tension, float t) { float t2 = t * t; float t3 = t2 * t; /* * Formula: s(-ttt + 2tt - t)P1 + s(-ttt + tt)P2 + (2ttt - 3tt + 1)P2 + s(ttt - 2tt + t)P3 + (-2ttt + 3tt)P3 + s(ttt - tt)P4 */ float s = (1 - tension) / 2; float b1 = s * ((-t3 + (2 * t2)) - t); // s(-t3 + 2 t2 - t)P1 float b2 = s * (-t3 + t2) + (2 * t3 - 3 * t2 + 1); // s(-t3 + t2)P2 + (2 t3 - 3 t2 + 1)P2 float b3 = s * (t3 - 2 * t2 + t) + (-2 * t3 + 3 * t2); // s(t3 - 2 t2 + t)P3 + (-2 t3 + 3 t2)P3 float b4 = s * (t3 - t2); // s(t3 - t2)P4 float x = (p0.X * b1 + p1.X * b2 + p2.X * b3 + p3.X * b4); float y = (p0.Y * b1 + p1.Y * b2 + p2.Y * b3 + p3.Y * b4); return new CCPoint(x, y); } /// <summary> /// Parses an int value using the default number style and the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse</param> /// <returns>The int value of the string</returns> public static int CCParseInt(string toParse) { // http://www.cocos2d-x.org/boards/17/topics/11690 // Issue #17 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return int.Parse(toParse, CultureInfo.InvariantCulture); } /// <summary> /// Parses aint value for the given string using the given number style and using /// the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse.</param> /// <param name="ns">The number style used to parse the int value.</param> /// <returns>The int value of the string.</returns> public static int CCParseInt(string toParse, NumberStyles ns) { // http://www.cocos2d-x.org/boards/17/topics/11690 // Issue #17 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return int.Parse(toParse, ns, CultureInfo.InvariantCulture); } /// <summary> /// Parses a float value using the default number style and the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse</param> /// <returns>The float value of the string.</returns> public static float CCParseFloat(string toParse) { // http://www.cocos2d-x.org/boards/17/topics/11690 // Issue #17 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return float.Parse(toParse, CultureInfo.InvariantCulture); } /// <summary> /// Parses a float value for the given string using the given number style and using /// the invariant culture parser. /// </summary> /// <param name="toParse">The value to parse.</param> /// <param name="ns">The number style used to parse the float value.</param> /// <returns>The float value of the string.</returns> public static float CCParseFloat(string toParse, NumberStyles ns) { // http://www.cocos2d-x.org/boards/17/topics/11690 // https://github.com/cocos2d/cocos2d-x-for-xna/issues/17 return float.Parse(toParse, ns, CultureInfo.InvariantCulture); } /// <summary> /// Returns the next Power of Two for the given value. If x = 3, then this returns 4. /// If x = 4 then 4 is returned. If the value is a power of two, then the same value /// is returned. /// </summary> /// <param name="x">The base of the POT test</param> /// <returns>The next power of 2 (1, 2, 4, 8, 16, 32, 64, 128, etc)</returns> public static long CCNextPOT(long x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } /// <summary> /// Returns the next Power of Two for the given value. If x = 3, then this returns 4. /// If x = 4 then 4 is returned. If the value is a power of two, then the same value /// is returned. /// </summary> /// <param name="x">The base of the POT test</param> /// <returns>The next power of 2 (1, 2, 4, 8, 16, 32, 64, 128, etc)</returns> public static int CCNextPOT(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >> 16); return x + 1; } public static void Split(string src, string token, List<string> vect) { int nend = 0; int nbegin = 0; while (nend != -1) { nend = src.IndexOf(token, nbegin); if (nend == -1) vect.Add(src.Substring(nbegin, src.Length - nbegin)); else vect.Add(src.Substring(nbegin, nend - nbegin)); nbegin = nend + token.Length; } } // first, judge whether the form of the string like this: {x,y} // if the form is right,the string will be splited into the parameter strs; // or the parameter strs will be empty. // if the form is right return true,else return false. public static bool SplitWithForm(string pStr, List<string> strs) { bool bRet = false; do { if (pStr == null) { break; } // string is empty string content = pStr; if (content.Length == 0) { break; } int nPosLeft = content.IndexOf('{'); int nPosRight = content.IndexOf('}'); // don't have '{' and '}' if (nPosLeft == -1 || nPosRight == -1) { break; } // '}' is before '{' if (nPosLeft > nPosRight) { break; } string pointStr = content.Substring(nPosLeft + 1, nPosRight - nPosLeft - 1); // nothing between '{' and '}' if (pointStr.Length == 0) { break; } int nPos1 = pointStr.IndexOf('{'); int nPos2 = pointStr.IndexOf('}'); // contain '{' or '}' if (nPos1 != -1 || nPos2 != -1) break; Split(pointStr, ",", strs); if (strs.Count != 2 || strs[0].Length == 0 || strs[1].Length == 0) { strs.Clear(); break; } bRet = true; } while (false); return bRet; } } }
using System; using System.Collections.Generic; using Android.Content; using Android.Graphics; using Android.Views; using Avalonia.Android.Platform.Input; using Avalonia.Android.Platform.Specific; using Avalonia.Android.Platform.Specific.Helpers; using Avalonia.Controls.Platform.Surfaces; using Avalonia.Input; using Avalonia.Input.Raw; using Avalonia.Platform; using Avalonia.Rendering; namespace Avalonia.Android.Platform.SkiaPlatform { class TopLevelImpl : IAndroidView, ITopLevelImpl, IFramebufferPlatformSurface { private readonly AndroidKeyboardEventsHelper<TopLevelImpl> _keyboardHelper; private readonly AndroidTouchEventsHelper<TopLevelImpl> _touchHelper; private ViewImpl _view; public TopLevelImpl(Context context, bool placeOnTop = false) { _view = new ViewImpl(context, this, placeOnTop); _keyboardHelper = new AndroidKeyboardEventsHelper<TopLevelImpl>(this); _touchHelper = new AndroidTouchEventsHelper<TopLevelImpl>(this, () => InputRoot, p => GetAvaloniaPointFromEvent(p)); Surfaces = new object[] { this }; MaxClientSize = new Size(_view.Resources.DisplayMetrics.WidthPixels, _view.Resources.DisplayMetrics.HeightPixels); } private bool _handleEvents; public bool HandleEvents { get { return _handleEvents; } set { _handleEvents = value; _keyboardHelper.HandleEvents = _handleEvents; } } public virtual Point GetAvaloniaPointFromEvent(MotionEvent e) => new Point(e.GetX(), e.GetY()); public IInputRoot InputRoot { get; private set; } public virtual Size ClientSize { get { if (_view == null) return new Size(0, 0); return new Size(_view.Width, _view.Height); } set { } } public IMouseDevice MouseDevice => AndroidMouseDevice.Instance; public Action Closed { get; set; } public Action<RawInputEventArgs> Input { get; set; } public Size MaxClientSize { get; protected set; } public Action<Rect> Paint { get; set; } public Action<Size> Resized { get; set; } public Action<double> ScalingChanged { get; set; } public View View => _view; public IPlatformHandle Handle => _view; public IEnumerable<object> Surfaces { get; } public IRenderer CreateRenderer(IRenderRoot root) { return new ImmediateRenderer(root); } public virtual void Hide() { _view.Visibility = ViewStates.Invisible; } public void Invalidate(Rect rect) { if (_view.Holder?.Surface?.IsValid == true) _view.Invalidate(); } public Point PointToClient(PixelPoint point) { return point.ToPoint(1); } public PixelPoint PointToScreen(Point point) { return PixelPoint.FromPoint(point, 1); } public void SetCursor(IPlatformHandle cursor) { //still not implemented } public void SetInputRoot(IInputRoot inputRoot) { InputRoot = inputRoot; } public virtual void Show() { _view.Visibility = ViewStates.Visible; } public double RenderScaling => 1; void Draw() { Paint?.Invoke(new Rect(new Point(0, 0), ClientSize)); } public virtual void Dispose() { _view.Dispose(); _view = null; } protected virtual void OnResized(Size size) { Resized?.Invoke(size); } class ViewImpl : InvalidationAwareSurfaceView, ISurfaceHolderCallback { private readonly TopLevelImpl _tl; private Size _oldSize; public ViewImpl(Context context, TopLevelImpl tl, bool placeOnTop) : base(context) { _tl = tl; if (placeOnTop) SetZOrderOnTop(true); } protected override void Draw() { _tl.Draw(); } public override bool DispatchTouchEvent(MotionEvent e) { bool callBase; bool? result = _tl._touchHelper.DispatchTouchEvent(e, out callBase); bool baseResult = callBase ? base.DispatchTouchEvent(e) : false; return result != null ? result.Value : baseResult; } public override bool DispatchKeyEvent(KeyEvent e) { bool callBase; bool? res = _tl._keyboardHelper.DispatchKeyEvent(e, out callBase); bool baseResult = callBase ? base.DispatchKeyEvent(e) : false; return res != null ? res.Value : baseResult; } void ISurfaceHolderCallback.SurfaceChanged(ISurfaceHolder holder, Format format, int width, int height) { var newSize = new Size(width, height); if (newSize != _oldSize) { _oldSize = newSize; _tl.OnResized(newSize); } base.SurfaceChanged(holder, format, width, height); } } public IPopupImpl CreatePopup() => null; public Action LostFocus { get; set; } ILockedFramebuffer IFramebufferPlatformSurface.Lock()=>new AndroidFramebuffer(_view.Holder.Surface); } }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using Lewis.SST.Controls; using Lewis.SST.SQLMethods; #region change history /// 08-22-2008: C01: LLEWIS: fix added to resolve local machine name, otherwise sql commands fail #endregion namespace Lewis.SST.Gui { /// <summary> /// Summary description for SQLSecuritySettings. /// </summary> public class SQLSecuritySettings : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox txt_UID; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txt_PWD; private System.Windows.Forms.RadioButton rdb_Integrated; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.RadioButton rdb_Mixed; private System.Windows.Forms.Button btn_OK; private System.Windows.Forms.Button btn_Cancel; private System.Windows.Forms.ComboBox txt_ServerName; private System.Windows.Forms.CheckBox chkSavePwd; private SQLConnections _SQLConnections; private ComboBox comboBox1; private Label label4; private Label lblWarning; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// Initializes a new instance of the <see cref="SQLSecuritySettings"/> class. /// </summary> public SQLSecuritySettings() { // // Required for Windows Form Designer support // InitializeComponent(); this.Height = 230; btn_OK.Top = 138; btn_Cancel.Top = 169; comboBox1.Enabled = false; } /// <summary> /// Initializes a new instance of the <see cref="SQLSecuritySettings"/> class. /// </summary> /// <param name="SQLServer">The SQL server.</param> public SQLSecuritySettings(string SQLServer) { // // Required for Windows Form Designer support // InitializeComponent(); this.Height = 230; btn_OK.Top = 138; btn_Cancel.Top = 169; comboBox1.Enabled = false; chkSavePwd.Checked = false; rdb_Integrated.Checked = true; rdb_Mixed.Checked = false; txt_ServerName.Text = SQLServer; if (SQLServer == null || SQLServer.Equals("Enter Server Name...")) { txt_ServerName.Enabled = true; txt_ServerName.Focus(); } } /// <summary> /// Initializes a new instance of the <see cref="SQLSecuritySettings"/> class. /// </summary> /// <param name="SQLServer">The SQL server.</param> /// <param name="UID">The UID.</param> /// <param name="PWD">The PWD.</param> public SQLSecuritySettings(string SQLServer, string UID, string PWD, bool SavePWD) { // // Required for Windows Form Designer support // InitializeComponent(); this.Height = 230; btn_OK.Top = 138; btn_Cancel.Top = 169; comboBox1.Enabled = false; rdb_Integrated.Checked = false; rdb_Mixed.Checked = true; SavePwd = SavePWD; txt_ServerName.Text = SQLServer; txt_UID.Text = UID; txt_PWD.Text = PWD; } /// <summary> /// Initializes a new instance of the <see cref="SQLSecuritySettings"/> class. /// </summary> /// <param name="SQLServers"></param> public SQLSecuritySettings(string[] SQLServers) { // InitializeComponent(); this.Height = 230; btn_OK.Top = 138; btn_Cancel.Top = 169; comboBox1.Enabled = false; chkSavePwd.Visible = false; rdb_Integrated.Checked = true; rdb_Mixed.Checked = false; txt_ServerName.Enabled = true; if (SQLServers != null) { txt_ServerName.Items.AddRange(SQLServers); } else { txt_ServerName.Enabled = true; txt_ServerName.Focus(); } if (txt_ServerName.Items.Count > 0) { txt_ServerName.SelectedIndex = 0; } } /// <summary> /// Initializes a new instance of the <see cref="SQLSecuritySettings"/> class. /// </summary> /// <param name="SQLServers">The SQL servers.</param> /// <param name="showSave">shows the save pwd checkbox</param> public SQLSecuritySettings(string [] SQLServers, bool showSave) { // // Required for Windows Form Designer support // InitializeComponent(); this.Height = 230; btn_OK.Top = 138; btn_Cancel.Top = 169; comboBox1.Enabled = false; chkSavePwd.Visible = showSave; rdb_Integrated.Checked = true; rdb_Mixed.Checked = false; txt_ServerName.Enabled = true; if (SQLServers != null) { txt_ServerName.Items.AddRange(SQLServers); } else { txt_ServerName.Enabled = true; txt_ServerName.Focus(); } if (txt_ServerName.Items.Count > 0) { txt_ServerName.SelectedIndex = 0; } } public SQLSecuritySettings(SQLServerExplorer sse) { string[] SQLServers = sse.Servers; SQLConnections sqlConnections = sse.SQLConnections; // // Required for Windows Form Designer support // InitializeComponent(); this.Height = 188; lblWarning.Visible = true; rdb_Integrated.Visible = false; rdb_Mixed.Visible = false; groupBox1.Visible = false; label2.Visible = false; label3.Visible = false; txt_PWD.Visible = false; txt_UID.Visible = false; label4.Top = 30; comboBox1.Top = 32; comboBox1.Enabled = false; btn_OK.Top = 88; btn_Cancel.Top = 119; lblWarning.Top = 88; _SQLConnections = sqlConnections; chkSavePwd.Visible = false; rdb_Integrated.Checked = true; rdb_Mixed.Checked = false; txt_ServerName.SelectedIndexChanged += new EventHandler(txt_ServerName_SelectedIndexChanged); txt_ServerName.Enabled = true; if (SQLServers != null) { txt_ServerName.Items.AddRange(SQLServers); } else { txt_ServerName.Enabled = true; txt_ServerName.Focus(); } string servername = string.Empty; if (typeof(ServerTreeNode).IsInstanceOfType(sse.SelectedTreeNode)) { servername = sse.SelectedTreeNode.Text; } if (typeof(DBTreeNode).IsInstanceOfType(sse.SelectedTreeNode)) { servername = sse.SelectedTreeNode.Parent.Text; } txt_ServerName.Text = servername; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SQLSecuritySettings)); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.txt_UID = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.txt_PWD = new System.Windows.Forms.TextBox(); this.rdb_Integrated = new System.Windows.Forms.RadioButton(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.rdb_Mixed = new System.Windows.Forms.RadioButton(); this.btn_OK = new System.Windows.Forms.Button(); this.btn_Cancel = new System.Windows.Forms.Button(); this.txt_ServerName = new System.Windows.Forms.ComboBox(); this.chkSavePwd = new System.Windows.Forms.CheckBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label4 = new System.Windows.Forms.Label(); this.lblWarning = new System.Windows.Forms.Label(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(16, 7); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(100, 24); this.label1.TabIndex = 1; this.label1.Text = "SQL Server Name:"; this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // label2 // this.label2.Location = new System.Drawing.Point(16, 30); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(100, 24); this.label2.TabIndex = 3; this.label2.Text = "User ID:"; this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // txt_UID // this.txt_UID.Location = new System.Drawing.Point(120, 32); this.txt_UID.Name = "txt_UID"; this.txt_UID.Size = new System.Drawing.Size(264, 20); this.txt_UID.TabIndex = 1; // // label3 // this.label3.Location = new System.Drawing.Point(16, 54); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(100, 24); this.label3.TabIndex = 5; this.label3.Text = "Password:"; this.label3.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // txt_PWD // this.txt_PWD.Location = new System.Drawing.Point(120, 56); this.txt_PWD.Name = "txt_PWD"; this.txt_PWD.PasswordChar = '*'; this.txt_PWD.Size = new System.Drawing.Size(264, 20); this.txt_PWD.TabIndex = 2; // // rdb_Integrated // this.rdb_Integrated.Location = new System.Drawing.Point(16, 24); this.rdb_Integrated.Name = "rdb_Integrated"; this.rdb_Integrated.Size = new System.Drawing.Size(96, 24); this.rdb_Integrated.TabIndex = 0; this.rdb_Integrated.Text = "Integrated"; this.rdb_Integrated.CheckedChanged += new System.EventHandler(this.rdb_Integrated_CheckedChanged); // // groupBox1 // this.groupBox1.Controls.Add(this.rdb_Mixed); this.groupBox1.Controls.Add(this.rdb_Integrated); this.groupBox1.Location = new System.Drawing.Point(120, 104); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(120, 88); this.groupBox1.TabIndex = 7; this.groupBox1.TabStop = false; this.groupBox1.Text = "Security Mode"; // // rdb_Mixed // this.rdb_Mixed.Location = new System.Drawing.Point(16, 52); this.rdb_Mixed.Name = "rdb_Mixed"; this.rdb_Mixed.Size = new System.Drawing.Size(96, 24); this.rdb_Mixed.TabIndex = 7; this.rdb_Mixed.Text = "Mixed Mode"; this.rdb_Mixed.CheckedChanged += new System.EventHandler(this.rdb_Mixed_CheckedChanged); // // btn_OK // this.btn_OK.DialogResult = System.Windows.Forms.DialogResult.OK; this.btn_OK.Location = new System.Drawing.Point(309, 229); this.btn_OK.Name = "btn_OK"; this.btn_OK.Size = new System.Drawing.Size(75, 23); this.btn_OK.TabIndex = 4; this.btn_OK.Text = "OK"; // // btn_Cancel // this.btn_Cancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btn_Cancel.Location = new System.Drawing.Point(309, 260); this.btn_Cancel.Name = "btn_Cancel"; this.btn_Cancel.Size = new System.Drawing.Size(75, 23); this.btn_Cancel.TabIndex = 5; this.btn_Cancel.Text = "Cancel"; // // txt_ServerName // this.txt_ServerName.Enabled = false; this.txt_ServerName.Location = new System.Drawing.Point(120, 8); this.txt_ServerName.Name = "txt_ServerName"; this.txt_ServerName.Size = new System.Drawing.Size(264, 21); this.txt_ServerName.TabIndex = 0; // // chkSavePwd // this.chkSavePwd.AutoSize = true; this.chkSavePwd.Location = new System.Drawing.Point(120, 82); this.chkSavePwd.Name = "chkSavePwd"; this.chkSavePwd.Size = new System.Drawing.Size(100, 17); this.chkSavePwd.TabIndex = 3; this.chkSavePwd.Text = "Save Password"; this.chkSavePwd.UseVisualStyleBackColor = true; // // comboBox1 // this.comboBox1.Enabled = false; this.comboBox1.Location = new System.Drawing.Point(120, 201); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(264, 21); this.comboBox1.TabIndex = 8; // // label4 // this.label4.Location = new System.Drawing.Point(15, 200); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(100, 24); this.label4.TabIndex = 9; this.label4.Text = "DB Name:"; this.label4.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblWarning // this.lblWarning.Image = ((System.Drawing.Image)(resources.GetObject("lblWarning.Image"))); this.lblWarning.ImageAlign = System.Drawing.ContentAlignment.TopRight; this.lblWarning.Location = new System.Drawing.Point(13, 229); this.lblWarning.Name = "lblWarning"; this.lblWarning.Size = new System.Drawing.Size(234, 63); this.lblWarning.TabIndex = 10; this.lblWarning.Text = "Be sure to make a backup of your database before running this script!"; this.lblWarning.Visible = false; // // SQLSecuritySettings // this.AcceptButton = this.btn_OK; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.btn_Cancel; this.ClientSize = new System.Drawing.Size(399, 294); this.Controls.Add(this.lblWarning); this.Controls.Add(this.label4); this.Controls.Add(this.comboBox1); this.Controls.Add(this.chkSavePwd); this.Controls.Add(this.txt_ServerName); this.Controls.Add(this.btn_Cancel); this.Controls.Add(this.btn_OK); this.Controls.Add(this.groupBox1); this.Controls.Add(this.label3); this.Controls.Add(this.txt_PWD); this.Controls.Add(this.txt_UID); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SQLSecuritySettings"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Security Settings"; this.TopMost = true; this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } #endregion private void txt_ServerName_SelectedIndexChanged(object sender, EventArgs e) { string[] dbs = getDBNames(); if (dbs != null) { comboBox1.Items.AddRange(dbs); comboBox1.Enabled = true; } } private string[] getDBNames() { string[] dbNames = null; SQLConnection sql = _SQLConnections[SelectedSQLServer]; if (sql != null) { if (sql.sqlConnection.State == System.Data.ConnectionState.Open) { dbNames = SQLServers.GetDBNames(sql.sqlConnection); } else { btn_Cancel.PerformClick(); this.DialogResult = DialogResult.Abort; } } return dbNames; } private void rdb_Integrated_CheckedChanged(object sender, System.EventArgs e) { if (rdb_Integrated.Checked) { txt_UID.ReadOnly = true; txt_PWD.ReadOnly = true; chkSavePwd.Enabled = false; } } private void rdb_Mixed_CheckedChanged(object sender, System.EventArgs e) { if (rdb_Mixed.Checked) { txt_UID.ReadOnly = false; txt_PWD.ReadOnly = false; chkSavePwd.Enabled = true; } } /// <summary> /// Sets the name of the SQL server. The value is used to connect to that server. /// </summary> /// <param name="SQLServer">The SQL server.</param> public void SetServerName(string SQLServer) { txt_ServerName.Text = SQLServer; } /// <summary> /// Returns the security type setting in use for the SQL server. /// </summary> /// <returns>Returns the security type setting in use for the SQL server.</returns> public SQLMethods.SecurityType SecurityMode() { if (rdb_Integrated.Checked) return SQLMethods.SecurityType.Integrated; else if (rdb_Mixed.Checked) return SQLMethods.SecurityType.Mixed; else return SQLMethods.SecurityType.Integrated; } /// <summary> /// Gets the SQL server name from the settings/connection dialog. /// </summary> /// <value>The SQL server.</value> public string SelectedSQLServer { get { // 08-22-2008: C01: LLEWIS: fix added to resolve local machine name, otherwise sql commands fail string serverName = txt_ServerName.Text; if (serverName.Trim().ToLower().Contains("(local)") || serverName.Trim().ToLower().Contains("localhost")) { string instance = serverName.Split('\\').Length > 1 ? serverName.Split('\\')[1] : string.Empty; serverName = string.Format("{0}\\{1}", Environment.MachineName, instance); } return serverName; } } /// <summary> /// Gets or sets the user value. /// </summary> /// <value>The user.</value> public string User { get { return txt_UID.Text; } set { txt_UID.Text = value == null ? "" : value; } } /// <summary> /// Gets or sets the password value. /// </summary> /// <value>The password.</value> public string PWD { get { return txt_PWD.Text; } set { txt_PWD.Text = value == null ? "" : value; } } public bool SavePwd { get { return chkSavePwd.Checked; } set { chkSavePwd.Checked = value; } } public string SelectedDBName { get { return comboBox1.Text; } } } }
/* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using java.lang; using org.eclipse.core.resources; using org.eclipse.core.runtime; using org.eclipse.core.runtime.jobs; using org.eclipse.jface.text; using org.eclipse.jface.text.source; using org.eclipse.ui.progress; using org.eclipse.ui.texteditor; using stab.query; using stab.reflection; using cnatural.eclipse.helpers; using cnatural.syntaxtree; namespace cnatural.eclipse.editors { class BackgroundCompiler : IProjectBuildListener { private SourceEditor editor; private bool initialized; public BackgroundCompiler(SourceEditor editor) { this.editor = editor; Environment.addProjectBuildListener(this); } void dispose() { Environment.removeProjectBuildListener(this); } public void projectBuilt(ProjectBuildEvent event) { if (initialized && !editor.IsActive) { return; } var file = editor.getFile(); if (file == null) { return; } var projectManager = Environment.getProjectManager(file); if (event.getSource() == projectManager) { compileAsync(); } } public void compileAsync() { new CompileJob(this).schedule(); } public void compile(IProgressMonitor monitor) { Environment.trace(this, "compiling"); var t0 = System.nanoTime(); try { monitor.beginTask("", 5); var file = editor.getFile(); if (file == null) { monitor.worked(5); return; } var projectManager = Environment.getProjectManager(file); if (projectManager == null || projectManager.RequireFullBuild) { Environment.trace(this, "compilation aborted"); monitor.worked(5); return; } var filename = file.getProjectRelativePath().toPortableString(); var text = editor.Highlighter.Text; var parameters = new SourceCompilerParameters { ProgressiveBuild = true, ClassPath = projectManager.ClassPath, TypeSystem = projectManager.TypeSystem, DependencyInfo = projectManager.DependencyInfo }; parameters.AllFiles.addAll(projectManager.getSourceFiles()); parameters.FilesToCompile.add(filename); parameters.EditedFileName = filename; parameters.EditedFileText = text; foreach (var s in projectManager.Properties.PreprocessorSymbols) { parameters.PreprocessorSymbols.add(s); } parameters.GenerateClassFiles = false; var compiler = new SourceCompiler(); var results = compiler.compile(parameters, new SubProgressMonitor(new ProgressMonitor(monitor, text, editor.Highlighter), 4)); if (!results.Failed) { var compilationUnit = results.CompilationUnits[filename]; if (compilationUnit != null && text == editor.Highlighter.Text) { initialized = true; new HighlightJob(editor, text, compilationUnit, results.TypeSystem, results.AnnotatedTypeSystem).schedule(); } } var annotationModel = editor.getDocumentProvider().getAnnotationModel(editor.getEditorInput()); // Remove the annotations var it = annotationModel.getAnnotationIterator(); while (it.hasNext()) { var annotation = (Annotation)it.next(); switch (annotation.getType()) { case "cnatural.eclipse.parsingErrorAnnotation": case "cnatural.eclipse.parsingWarningAnnotation": annotationModel.removeAnnotation(annotation); break; } } var errors = results.CodeErrors.where(p => p.Filename.equals(filename)).toList(); if (!errors.isEmpty()) { IDocument document = null; var documentProvider = editor.getDocumentProvider(); if (documentProvider != null) { document = documentProvider.getDocument(editor.getEditorInput()); } var markers = file.findMarkers(IMarker.PROBLEM, false, IFile.DEPTH_ZERO); var tokens = editor.Highlighter.Tokens; foreach (var error in errors) { IMarker marker = null; if (markers != null) { foreach (var m in markers) { if (!error.Message.equals(m.getAttribute(IMarker.MESSAGE, null))) { continue; } if (error.Line == m.getAttribute(IMarker.LINE_NUMBER, -1)) { marker = m; break; } } } var annotationType = (error.Level == 0) ? "cnatural.eclipse.parsingErrorAnnotation" : "cnatural.eclipse.parsingWarningAnnotation"; var annotation = (marker == null) ? new Annotation(annotationType, false, error.Message) : new MarkerAnnotation(annotationType, marker); int offset = document.getLineOffset(error.Line - 1); int length; if (tokens.isEmpty()) { length = document.getLineLength(error.Line - 1); } else { int tabWidth = Environment.getTabWidth(); int start = offset; for (int i = 0; i < error.Column - 1; i++) { if (text[start++] == '\t') { i += tabWidth - 1; } offset++; } int idx = Highlighter.getPositionIndex(tokens, offset); if (idx == -1) { length = 1; } else { var tk = tokens[idx]; offset = tk.offset; length = tk.length; } } if (marker != null) { marker.setAttribute(IMarker.CHAR_START, offset); marker.setAttribute(IMarker.CHAR_END, offset + length); } annotationModel.addAnnotation(annotation, new Position(offset, length)); } } monitor.worked(1); } catch (InterruptedException) { } finally { monitor.done(); } Environment.trace(this, "compiling done in " + ((System.nanoTime() - t0) / 1e6) + "ms"); } private class ProgressMonitor : IProgressMonitor { private IProgressMonitor monitor; private char[] text; private Highlighter highlighter; ProgressMonitor(IProgressMonitor monitor, char[] text, Highlighter highlighter) { this.monitor = monitor; this.text = text; this.highlighter = highlighter; } public void beginTask(String name, int totalWork) { monitor.beginTask(name, totalWork); } public void done() { monitor.done(); } public void internalWorked(double work) { monitor.internalWorked(work); } public bool isCanceled() { return text != highlighter.Text || monitor.isCanceled(); } public void setCanceled(bool value) { monitor.setCanceled(value); } public void setTaskName(String name) { monitor.setTaskName(name); } public void subTask(String name) { monitor.subTask(name); } public void worked(int work) { monitor.worked(work); } } private class HighlightJob : UIJob { private SourceEditor editor; private char[] text; private CompilationUnitNode compilationUnit; private Library typeSystem; private Library annotatedTypeSystem; HighlightJob(SourceEditor editor, char[] text, CompilationUnitNode compilationUnit, Library typeSystem, Library annotatedTypeSystem) : super("Semantic Highlight") { this.editor = editor; this.text = text; this.compilationUnit = compilationUnit; this.typeSystem = typeSystem; this.annotatedTypeSystem = annotatedTypeSystem; } public override IStatus runInUIThread(IProgressMonitor monitor) { try { monitor.beginTask("", 1); editor.Highlighter.update(text, compilationUnit, typeSystem, annotatedTypeSystem); monitor.worked(1); monitor.done(); } catch { } return (monitor.isCanceled()) ? Status.CANCEL_STATUS : Status.OK_STATUS; } } private class CompileJob : Job { private BackgroundCompiler compiler; CompileJob(BackgroundCompiler compiler) : super("Compile") { setPriority(Job.DECORATE); this.compiler = compiler; } protected override IStatus run(IProgressMonitor monitor) { try { compiler.compile(monitor); } catch { } return (monitor.isCanceled()) ? Status.CANCEL_STATUS : Status.OK_STATUS; } } } }
/* MIT License Copyright (c) 2017 Saied Zarrinmehr Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using SpatialAnalysis.Agents.Visualization.AgentTrailVisualization; using SpatialAnalysis.Data; using System.Windows.Threading; using SpatialAnalysis.Optimization; using SpatialAnalysis.Geometry; namespace SpatialAnalysis.Agents.OptionalScenario.Visualization { /// <summary> /// Interaction logic for OptionalScenarioTraining.xaml /// </summary> public partial class OptionalScenarioTraining : Window { private StringBuilder _sb; #region Host Definition private static DependencyProperty _hostProperty = DependencyProperty.Register("_host", typeof(OSMDocument), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(null, OptionalScenarioTraining.hostPropertyChanged, OptionalScenarioTraining.PropertyCoerce)); private OSMDocument _host { get { return (OSMDocument)GetValue(_hostProperty); } set { SetValue(_hostProperty, value); } } private static void hostPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance._host = (OSMDocument)args.NewValue; } #endregion #region AllParameters Definition public static DependencyProperty AllParametersProperty = DependencyProperty.Register("AllParameters", typeof(HashSet<Parameter>), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(null, OptionalScenarioTraining.AllParametersPropertyChanged, OptionalScenarioTraining.PropertyCoerce)); private HashSet<Parameter> AllParameters { get { return (HashSet<Parameter>)GetValue(AllParametersProperty); } set { SetValue(AllParametersProperty, value); } } private static void AllParametersPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance.AllParameters = (HashSet<Parameter>)args.NewValue; } #endregion #region AllDestinations Definition public static DependencyProperty AllDestinationsProperty = DependencyProperty.Register("AllDestinations", typeof(StateBase[]), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(null, OptionalScenarioTraining.AllDestinationsPropertyChanged, OptionalScenarioTraining.PropertyCoerce)); StateBase[] AllDestinations { get { return (StateBase[])GetValue(AllDestinationsProperty); } set { SetValue(AllDestinationsProperty, value); } } private static void AllDestinationsPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance.AllDestinations = (StateBase[])args.NewValue; } #endregion #region _timeStep Definition private static DependencyProperty _timeStepValueProperty = DependencyProperty.Register("_timeStepValue", typeof(double), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(17.0d, OptionalScenarioTraining._timeStepValuePropertyChanged, OptionalScenarioTraining.PropertyCoerce)); private double _timeStepValue { get { return (double)GetValue(_timeStepValueProperty); } set { SetValue(_timeStepValueProperty, value); } } private static void _timeStepValuePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance._timeStepValue = (double)args.NewValue; } #endregion #region _durationValue Definition private static DependencyProperty _durationValueProperty = DependencyProperty.Register("_durationValue", typeof(double), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(0.0d, OptionalScenarioTraining._durationValuePropertyChanged, OptionalScenarioTraining.PropertyCoerce)); private double _durationValue { get { return (double)GetValue(_durationValueProperty); } set { SetValue(_durationValueProperty, value); } } private static void _durationValuePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance._durationValue = (double)args.NewValue; } #endregion #region _iterationCount Definition private static DependencyProperty _iterationCountProperty = DependencyProperty.Register("_iterationCount", typeof(int), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(0, OptionalScenarioTraining._iterationCountPropertyChanged, OptionalScenarioTraining.PropertyCoerce)); private int _iterationCount { get { return (int)GetValue(_iterationCountProperty); } set { SetValue(_iterationCountProperty, value); } } private static void _iterationCountPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance._iterationCount = (int)args.NewValue; } #endregion #region _iterationCount Definition private static DependencyProperty _counterProperty = DependencyProperty.Register("_counter", typeof(int), typeof(OptionalScenarioTraining), new FrameworkPropertyMetadata(0, OptionalScenarioTraining._counterPropertyChanged, OptionalScenarioTraining.PropertyCoerce)); private int _counter { get { return (int)GetValue(_counterProperty); } set { SetValue(_counterProperty, value); } } private static void _counterPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args) { OptionalScenarioTraining instance = (OptionalScenarioTraining)obj; instance._counter = (int)args.NewValue; } #endregion private static object PropertyCoerce(DependencyObject obj, object value) { return value; } //double _timeStep, _duration, _isovistRadius; //int _destinationCount; public OptionalScenarioTraining(OSMDocument host) { InitializeComponent(); this._host = host; this._dataCtrlPanel.Click += this._dataCtrlPanel_Click; this._paramCtrlPanel.Click += new RoutedEventHandler(_paramCtrlPanel_Click); this.AllDestinations = new StateBase[this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates.Length-1]; this._sb = new StringBuilder(); this._run_close.Click += this._run_Click; } private void _paramCtrlPanel_Click(object sender, RoutedEventArgs e) { var parameterSetting = new Data.Visualization.ParameterSetting(this._host, false); parameterSetting.Owner = this._host; parameterSetting.ShowDialog(); } private void _dataCtrlPanel_Click(object sender, RoutedEventArgs e) { var dataCtrlPanel = new Data.Visualization.SpatialDataControlPanel(this._host, Data.Visualization.IncludedDataTypes.SpatialData); dataCtrlPanel.Owner = this._host; dataCtrlPanel.ShowDialog(); } private void _run_Click(object sender, RoutedEventArgs e) { #region Validate simulates annealing parameters int iterationCount = 0; if (!int.TryParse(this._numberOfIterations.Text, out iterationCount)) { this.invalidInput("Number of Iterations"); return; } if (iterationCount <= 0) { this.valueSmallerThanZero("Number of Iterations"); return; } this._iterationCount = iterationCount; double minimumEnergy = 0; if (!double.TryParse(this._minimumTemperature.Text, out minimumEnergy)) { this.invalidInput("Minimum Temperature"); return; } if (minimumEnergy < 0) { MessageBox.Show("'Minimum Temperature' should not be smaller than zero!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } double maximumEnergy = 0; if (!double.TryParse(this._maximumTemperature.Text, out maximumEnergy)) { this.invalidInput("Maximum Temperature"); return; } if (maximumEnergy <= 0) { this.valueSmallerThanZero("Maximum Temperature"); return; } #endregion #region validation of training subset //double trainingRatio = 0; //if (!double.TryParse(this._ratioOfTrainingSubset.Text, out trainingRatio)) //{ // MessageBox.Show("Invalied 'Ratio of Training Subset'", "Invalid Input", // MessageBoxButton.OK, MessageBoxImage.Error); // return; //} //else //{ // if (trainingRatio <= 0 || trainingRatio > 1.0) // { // MessageBox.Show("'Ratio of Training Subset' must be larger than zero and smaller than or equal to 1", // "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); // return; // } //} #endregion #region Validate duration and timeStep parameters double timeStep = 0; if (!double.TryParse(this._timeStep.Text, out timeStep)) { MessageBox.Show("Invalid input for 'Time Step'!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } else { if (timeStep<=0) { MessageBox.Show("'Time Step' must be larger than zero!", "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); return; } } this._timeStepValue = timeStep; this._durationValue = this._host.trailVisualization.AgentWalkingTrail.TimeIntervalBetweenInterpolatedStates;//convert seconds to hours #endregion #region Check to see if spatial data has been included int spatialDataCount = 0; foreach (Function function in this._host.cellularFloor.AllSpatialDataFields.Values) { SpatialDataField dataField = function as SpatialDataField; if (dataField != null) { if (dataField.IncludeInActivityGeneration) { spatialDataCount++; } } } if (spatialDataCount == 0) { var res = MessageBox.Show("There is no a spatial data field included to calculate cost/desirability!"); return; } #endregion #region extracting the ralated parameters and checking to see if number of parameter is not zero this.AllParameters = new HashSet<Parameter>(); if (this._isoExternalDepth.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_IsovistExternalDepth.ToString()]); } if (this._numberOfDestinations.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_NumberOfDestinations.ToString()]); } if (this._velocityMagnetude.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_VelocityMagnitude.ToString()]); } if (this._angularVelocity.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AngularVelocity.ToString()]); } if (this._bodySize.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BodySize.ToString()]); } if (this._accelerationMagnitude.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AccelerationMagnitude.ToString()]); } if (this._barrierRepulsionRange.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BarrierRepulsionRange.ToString()]); } if (this._repulsionChangeRate.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_MaximumRepulsion.ToString()]); } if (this._barrierFriction.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_BarrierFriction.ToString()]); } if (this._bodyElasticity.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_AgentBodyElasticity.ToString()]); } if (this._visibilityAngle.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.GEN_VisibilityAngle.ToString()]); } if (this._decisionMakingPeriodLamdaFactor.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_DecisionMakingPeriodLambdaFactor.ToString()]); } if (this._angleDistributionLambdaFactor.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_AngleDistributionLambdaFactor.ToString()]); } if (this._desirabilityDistributionLambdaFactor.IsChecked.Value) { this.AllParameters.Add(this._host.Parameters[AgentParameters.OPT_DesirabilityDistributionLambdaFactor.ToString()]); } foreach (var item in this._host.Parameters) { foreach (var function in item.Value.LinkedFunctions) { if (function.IncludeInActivityGeneration) { this.AllParameters.Add(item.Value); break; } } } if (this.AllParameters.Count==0) { MessageBox.Show("No parameter is included to account for the variability in the optimization process", "Parameter Not Assigned", MessageBoxButton.OK, MessageBoxImage.Error); return; } #endregion //execute visibility changes in the interface Dispatcher.Invoke(new Action(() => { this._run_close.SetValue(Button.VisibilityProperty, System.Windows.Visibility.Collapsed); this._run_close.SetValue(Button.ContentProperty, "Close"); this._mainInterface.SetValue(Grid.VisibilityProperty, System.Windows.Visibility.Collapsed); this._progressPanel.SetValue(StackPanel.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); //unregister run button event this._run_close.Click -= this._run_Click; //create annealing SimulatedAnnealingSolver solver = new SimulatedAnnealingSolver(this.AllParameters); //register UI update event for best fitness changes solver.BestFitnessUpdated += solver_BestFitnessUpdated; //register UI update event for fitness changes solver.FitnessUpdated += solver_FitnessUpdated; //Setting the initial iteration to zero this._counter = 0; //initializing the trial visualization this._host.trailVisualization.InitiateTrainingVisualization(); //running the annealing process solver.Solve(minimumEnergy, maximumEnergy, iterationCount, this.measureFitnessWithInterfaceUpdate); //unregister UI update event for fitness changes solver.BestFitnessUpdated -= solver_BestFitnessUpdated; //unregister UI update event for fitness changes solver.FitnessUpdated -= solver_FitnessUpdated; //showing the close btn. The close event is not registered yet Dispatcher.Invoke(new Action(() => { this._run_close.SetValue(Button.VisibilityProperty, System.Windows.Visibility.Visible); }), DispatcherPriority.ContextIdle); //updating the FreeNavigationAgentCharacters this._host.FreeNavigationAgentCharacter = FreeNavigationAgent.Create(this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates[0]); //Show the last parameter setting on UI this._sb.Clear(); foreach (var item in this.AllParameters) { this._sb.AppendLine(item.ToString()); } this._updateMessage.SetValue(TextBlock.TextProperty, this._sb.ToString()); //set Window closing events this._run_close.Click += (s, e1) => { var result = MessageBox.Show("Do you want to clear the training data from screen?", "", MessageBoxButton.YesNo, MessageBoxImage.Exclamation); if (result == MessageBoxResult.Yes) { this._host.trailVisualization.TerminateTrainingVisualization(); } this.Close(); }; } void solver_BestFitnessUpdated(object sender, UIEventArgs e) { Dispatcher.Invoke(new Action(() => { this._host.trailVisualization.VisualizeBestTrainingOption(this.AllDestinations); this._bestFitnessValue.SetValue(TextBlock.TextProperty, e.Value.ToString()); }), DispatcherPriority.ContextIdle); } void solver_FitnessUpdated(object sender, UIEventArgs e) { Dispatcher.Invoke(new Action(() => { this._host.trailVisualization.VisualizeTrainingStep(this.AllDestinations); this._currentFitnessValue.SetValue(TextBlock.TextProperty, e.Value.ToString()); }), DispatcherPriority.ContextIdle); } //measure fitness based on sum of differences in angles private double measureFitnessWithInterfaceUpdate() { OptionalScenarioTrainer training = new OptionalScenarioTrainer(this._host, this._timeStepValue, this._durationValue); double value = 0; //OptionalWalkingTraining.TrailPoints.Clear(); //var directions = new StateBase[this._host.trailVisualization.AgentWalkingTrail.NormalizedStates.Length]; for (int i = 0; i < this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates.Length - 1; i++) { StateBase newState = this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates[i].Copy(); newState.Velocity *= training.AccelerationMagnitude; training.UpdateAgent(newState); this.AllDestinations[i] = training.CurrentState; //double fitness = StateBase.DistanceSquared(training.CurrentState, this._host.trailVisualization.AgentWalkingTrail.NormalizedStates[i + 1]); double fitness = UV.GetLengthSquared(training.CurrentState.Location, this._host.trailVisualization.AgentWalkingTrail.InterpolatedStates[i + 1].Location); value += fitness; } this._counter++; //interface update call in parallel Dispatcher.Invoke(new Action(() => { this._host.trailVisualization.VisualizeTrainingStep(this.AllDestinations); this._sb.Clear(); foreach (var item in this.AllParameters) { this._sb.AppendLine(item.ToString()); } this._updateMessage.SetValue(TextBlock.TextProperty, this._sb.ToString()); int percent = (int)((this._counter * 100.0d) / this._iterationCount); if ((int)this._progressBar.Value != percent) { this._progressReport.SetValue(TextBlock.TextProperty, string.Format("%{0}", percent.ToString())); this._progressBar.SetValue(ProgressBar.ValueProperty, (double)percent); } }), DispatcherPriority.ContextIdle); return value; } private void invalidInput(string name) { MessageBox.Show(string.Format("Invalid input for '{0}'!", name), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); } private void valueSmallerThanZero(string name) { MessageBox.Show(string.Format("'{0}' should not be smaller than or equal to zero!", name), "Invalid Input", MessageBoxButton.OK, MessageBoxImage.Error); } } }
/* Project Orleans Cloud Service SDK ver. 1.0 Copyright (c) Microsoft Corporation All rights reserved. MIT License Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Orleans.Runtime.Configuration; namespace Orleans.Runtime.MembershipService { internal class MembershipOracleData { private readonly Dictionary<SiloAddress, MembershipEntry> localTable; // all silos not including current silo private Dictionary<SiloAddress, SiloStatus> localTableCopy; // a cached copy of a local table, including current silo, for fast access private Dictionary<SiloAddress, SiloStatus> localTableCopyOnlyActive; // a cached copy of a local table, for fast access, including only active nodes and current silo (if active) private Dictionary<SiloAddress, string> localNamesTableCopy; // a cached copy of a map from SiloAddress to Silo Name, not including current silo, for fast access private readonly List<ISiloStatusListener> statusListeners; private readonly TraceLogger logger; private IntValueStatistic clusterSizeStatistic; private StringValueStatistic clusterStatistic; internal readonly DateTime SiloStartTime; internal readonly SiloAddress MyAddress; internal readonly string MyHostname; internal SiloStatus CurrentStatus { get; private set; } // current status of this silo. internal string SiloName { get; private set; } // name of this silo. internal MembershipOracleData(Silo silo, TraceLogger log) { logger = log; localTable = new Dictionary<SiloAddress, MembershipEntry>(); localTableCopy = new Dictionary<SiloAddress, SiloStatus>(); localTableCopyOnlyActive = new Dictionary<SiloAddress, SiloStatus>(); localNamesTableCopy = new Dictionary<SiloAddress, string>(); statusListeners = new List<ISiloStatusListener>(); SiloStartTime = DateTime.UtcNow; MyAddress = silo.SiloAddress; MyHostname = silo.LocalConfig.DNSHostName; SiloName = silo.LocalConfig.SiloName; CurrentStatus = SiloStatus.Created; clusterSizeStatistic = IntValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER_SIZE, () => localTableCopyOnlyActive.Count); clusterStatistic = StringValueStatistic.FindOrCreate(StatisticNames.MEMBERSHIP_ACTIVE_CLUSTER, () => { List<string> list = localTableCopyOnlyActive.Keys.Select(addr => addr.ToLongString()).ToList(); list.Sort(); return Utils.EnumerableToString(list); }); } // ONLY access localTableCopy and not the localTable, to prevent races, as this method may be called outside the turn. internal SiloStatus GetApproximateSiloStatus(SiloAddress siloAddress) { var status = SiloStatus.None; if (siloAddress.Equals(MyAddress)) { status = CurrentStatus; } else { if (!localTableCopy.TryGetValue(siloAddress, out status)) { if (CurrentStatus.Equals(SiloStatus.Active)) if (logger.IsVerbose) logger.Verbose(ErrorCode.Runtime_Error_100209, "-The given siloAddress {0} is not registered in this MembershipOracle.", siloAddress.ToLongString()); status = SiloStatus.None; } } if (logger.IsVerbose3) logger.Verbose3("-GetApproximateSiloStatus returned {0} for silo: {1}", status, siloAddress.ToLongString()); return status; } // ONLY access localTableCopy or localTableCopyOnlyActive and not the localTable, to prevent races, as this method may be called outside the turn. internal Dictionary<SiloAddress, SiloStatus> GetApproximateSiloStatuses(bool onlyActive = false) { Dictionary<SiloAddress, SiloStatus> dict = onlyActive ? localTableCopyOnlyActive : localTableCopy; if (logger.IsVerbose3) logger.Verbose3("-GetApproximateSiloStatuses returned {0} silos: {1}", dict.Count, Utils.DictionaryToString(dict)); return dict; } internal bool TryGetSiloName(SiloAddress siloAddress, out string siloName) { if (siloAddress.Equals(MyAddress)) { siloName = SiloName; return true; } return localNamesTableCopy.TryGetValue(siloAddress, out siloName); } internal bool SubscribeToSiloStatusEvents(ISiloStatusListener observer) { lock (statusListeners) { if (statusListeners.Contains(observer)) return false; statusListeners.Add(observer); return true; } } internal bool UnSubscribeFromSiloStatusEvents(ISiloStatusListener observer) { lock (statusListeners) { return statusListeners.Contains(observer) && statusListeners.Remove(observer); } } internal void UpdateMyStatusLocal(SiloStatus status) { if (CurrentStatus == status) return; // make copies var tmpLocalTableCopy = GetSiloStatuses(st => true, true); // all the silos including me. var tmpLocalTableCopyOnlyActive = GetSiloStatuses(st => st.Equals(SiloStatus.Active), true); // only active silos including me. var tmpLocalTableNamesCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.InstanceName); // all the silos excluding me. CurrentStatus = status; tmpLocalTableCopy[MyAddress] = status; if (status.Equals(SiloStatus.Active)) { tmpLocalTableCopyOnlyActive[MyAddress] = status; } else if (tmpLocalTableCopyOnlyActive.ContainsKey(MyAddress)) { tmpLocalTableCopyOnlyActive.Remove(MyAddress); } localTableCopy = tmpLocalTableCopy; localTableCopyOnlyActive = tmpLocalTableCopyOnlyActive; localNamesTableCopy = tmpLocalTableNamesCopy; NotifyLocalSubscribers(MyAddress, CurrentStatus); } private SiloStatus GetSiloStatus(SiloAddress siloAddress) { if (siloAddress.Equals(MyAddress)) return CurrentStatus; MembershipEntry data; return !localTable.TryGetValue(siloAddress, out data) ? SiloStatus.None : data.Status; } internal MembershipEntry GetSiloEntry(SiloAddress siloAddress) { return localTable[siloAddress]; } internal Dictionary<SiloAddress, SiloStatus> GetSiloStatuses(Func<SiloStatus, bool> filter, bool includeMyself) { Dictionary<SiloAddress, SiloStatus> dict = localTable.Where( pair => filter(pair.Value.Status)).ToDictionary(pair => pair.Key, pair => pair.Value.Status); if (includeMyself && filter(CurrentStatus)) // add myself dict.Add(MyAddress, CurrentStatus); return dict; } internal MembershipEntry CreateNewMembershipEntry(NodeConfiguration nodeConf, SiloStatus myStatus) { return CreateNewMembershipEntry(nodeConf, MyAddress, MyHostname, myStatus, SiloStartTime); } private static MembershipEntry CreateNewMembershipEntry(NodeConfiguration nodeConf, SiloAddress myAddress, string myHostname, SiloStatus myStatus, DateTime startTime) { var assy = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly(); var roleName = assy.GetName().Name; var entry = new MembershipEntry { SiloAddress = myAddress, HostName = myHostname, InstanceName = nodeConf.SiloName, Status = myStatus, ProxyPort = (nodeConf.IsGatewayNode ? nodeConf.ProxyGatewayEndpoint.Port : 0), IsPrimary = nodeConf.IsPrimaryNode, RoleName = roleName, SuspectTimes = new List<Tuple<SiloAddress, DateTime>>(), StartTime = startTime, IAmAliveTime = DateTime.UtcNow }; return entry; } internal bool TryUpdateStatusAndNotify(MembershipEntry entry) { if (!TryUpdateStatus(entry)) return false; localTableCopy = GetSiloStatuses(status => true, true); // all the silos including me. localTableCopyOnlyActive = GetSiloStatuses(status => status.Equals(SiloStatus.Active), true); // only active silos including me. localNamesTableCopy = localTable.ToDictionary(pair => pair.Key, pair => pair.Value.InstanceName); // all the silos excluding me. if (logger.IsVerbose) logger.Verbose("-Updated my local view of {0} status. It is now {1}.", entry.SiloAddress.ToLongString(), GetSiloStatus(entry.SiloAddress)); NotifyLocalSubscribers(entry.SiloAddress, entry.Status); return true; } // return true if the status changed private bool TryUpdateStatus(MembershipEntry updatedSilo) { MembershipEntry currSiloData = null; if (!localTable.TryGetValue(updatedSilo.SiloAddress, out currSiloData)) { // an optimization - if I learn about dead silo and I never knew about him before, I don't care, can just ignore him. if (updatedSilo.Status == SiloStatus.Dead) return false; localTable.Add(updatedSilo.SiloAddress, updatedSilo); return true; } if (currSiloData.Status == updatedSilo.Status) return false; currSiloData.Update(updatedSilo); return true; } private void NotifyLocalSubscribers(SiloAddress siloAddress, SiloStatus newStatus) { if (logger.IsVerbose2) logger.Verbose2("-NotifyLocalSubscribers about {0} status {1}", siloAddress.ToLongString(), newStatus); List<ISiloStatusListener> copy; lock (statusListeners) { copy = statusListeners.ToList(); } foreach (ISiloStatusListener listener in copy) { try { listener.SiloStatusChangeNotification(siloAddress, newStatus); } catch (Exception exc) { logger.Error(ErrorCode.MembershipLocalSubscriberException, String.Format("Local ISiloStatusListener {0} has thrown an exception when was notified about SiloStatusChangeNotification about silo {1} new status {2}", listener.GetType().FullName, siloAddress.ToLongString(), newStatus), exc); } } } public override string ToString() { return string.Format("CurrentSiloStatus = {0}, {1} silos: {2}.", CurrentStatus, localTableCopy.Count, Utils.EnumerableToString(localTableCopy, pair => String.Format("SiloAddress={0} Status={1}", pair.Key.ToLongString(), pair.Value))); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using Lucene.Net.Search; using Spatial4n.Core.Context; using Spatial4n.Core.Shapes; namespace Lucene.Net.Spatial.BBox { /// <summary> /// The algorithm is implemented as envelope on envelope overlays rather than /// complex polygon on complex polygon overlays. /// <p/> /// <p/> /// Spatial relevance scoring algorithm: /// <p/> /// <br/> queryArea = the area of the input query envelope /// <br/> targetArea = the area of the target envelope (per Lucene document) /// <br/> intersectionArea = the area of the intersection for the query/target envelopes /// <br/> queryPower = the weighting power associated with the query envelope (default = 1.0) /// <br/> targetPower = the weighting power associated with the target envelope (default = 1.0) /// <p/> /// <br/> queryRatio = intersectionArea / queryArea; /// <br/> targetRatio = intersectionArea / targetArea; /// <br/> queryFactor = Math.pow(queryRatio,queryPower); /// <br/> targetFactor = Math.pow(targetRatio,targetPower); /// <br/> score = queryFactor /// targetFactor; /// <p/> /// Based on Geoportal's /// <a href="http://geoportal.svn.sourceforge.net/svnroot/geoportal/Geoportal/trunk/src/com/esri/gpt/catalog/lucene/SpatialRankingValueSource.java"> /// SpatialRankingValueSource</a>. /// /// @lucene.experimental /// </summary> public class AreaSimilarity : BBoxSimilarity { /* * Properties associated with the query envelope */ private readonly Rectangle queryExtent; private readonly double queryArea; private readonly double targetPower; private readonly double queryPower; public AreaSimilarity(Rectangle queryExtent, double queryPower, double targetPower) { this.queryExtent = queryExtent; this.queryArea = queryExtent.GetArea(null); this.queryPower = queryPower; this.targetPower = targetPower; // if (this.qryMinX > queryExtent.getMaxX()) { // this.qryCrossedDateline = true; // this.qryArea = Math.abs(qryMaxX + 360.0 - qryMinX) * Math.abs(qryMaxY - qryMinY); // } else { // this.qryArea = Math.abs(qryMaxX - qryMinX) * Math.abs(qryMaxY - qryMinY); // } } public AreaSimilarity(Rectangle queryExtent) : this(queryExtent, 2.0, 0.5) { } public String GetDelimiterQueryParameters() { return queryExtent + ";" + queryPower + ";" + targetPower; } public double Score(Rectangle target, Explanation exp) { if (target == null || queryArea <= 0) { return 0; } double targetArea = target.GetArea(null); if (targetArea <= 0) { return 0; } double score = 0; double top = Math.Min(queryExtent.GetMaxY(), target.GetMaxY()); double bottom = Math.Max(queryExtent.GetMinY(), target.GetMinY()); double height = top - bottom; double width = 0; // queries that cross the date line if (queryExtent.GetCrossesDateLine()) { // documents that cross the date line if (target.GetCrossesDateLine()) { double left = Math.Max(queryExtent.GetMinX(), target.GetMinX()); double right = Math.Min(queryExtent.GetMaxX(), target.GetMaxX()); width = right + 360.0 - left; } else { double qryWestLeft = Math.Max(queryExtent.GetMinX(), target.GetMaxX()); double qryWestRight = Math.Min(target.GetMaxX(), 180.0); double qryWestWidth = qryWestRight - qryWestLeft; if (qryWestWidth > 0) { width = qryWestWidth; } else { double qryEastLeft = Math.Max(target.GetMaxX(), -180.0); double qryEastRight = Math.Min(queryExtent.GetMaxX(), target.GetMaxX()); double qryEastWidth = qryEastRight - qryEastLeft; if (qryEastWidth > 0) { width = qryEastWidth; } } } } else { // queries that do not cross the date line if (target.GetCrossesDateLine()) { double tgtWestLeft = Math.Max(queryExtent.GetMinX(), target.GetMinX()); double tgtWestRight = Math.Min(queryExtent.GetMaxX(), 180.0); double tgtWestWidth = tgtWestRight - tgtWestLeft; if (tgtWestWidth > 0) { width = tgtWestWidth; } else { double tgtEastLeft = Math.Max(queryExtent.GetMinX(), -180.0); double tgtEastRight = Math.Min(queryExtent.GetMaxX(), target.GetMaxX()); double tgtEastWidth = tgtEastRight - tgtEastLeft; if (tgtEastWidth > 0) { width = tgtEastWidth; } } } else { double left = Math.Max(queryExtent.GetMinX(), target.GetMinX()); double right = Math.Min(queryExtent.GetMaxX(), target.GetMaxX()); width = right - left; } } // calculate the score if ((width > 0) && (height > 0)) { double intersectionArea = width * height; double queryRatio = intersectionArea / queryArea; double targetRatio = intersectionArea / targetArea; double queryFactor = Math.Pow(queryRatio, queryPower); double targetFactor = Math.Pow(targetRatio, targetPower); score = queryFactor * targetFactor * 10000.0; if (exp != null) { // StringBuilder sb = new StringBuilder(); // sb.append("\nscore=").append(score); // sb.append("\n query=").append(); // sb.append("\n target=").append(target.toString()); // sb.append("\n intersectionArea=").append(intersectionArea); // // sb.append(" queryArea=").append(queryArea).append(" targetArea=").append(targetArea); // sb.append("\n queryRatio=").append(queryRatio).append(" targetRatio=").append(targetRatio); // sb.append("\n queryFactor=").append(queryFactor).append(" targetFactor=").append(targetFactor); // sb.append(" (queryPower=").append(queryPower).append(" targetPower=").append(targetPower).append(")"); exp.Value = (float) score; exp.Description = GetType().Name; Explanation e = null; exp.AddDetail(e = new Explanation((float)intersectionArea, "IntersectionArea")); e.AddDetail(new Explanation((float)width, "width; Query: " + queryExtent)); e.AddDetail(new Explanation((float)height, "height; Target: " + target)); exp.AddDetail(e = new Explanation((float)queryFactor, "Query")); e.AddDetail(new Explanation((float)queryArea, "area")); e.AddDetail(new Explanation((float)queryRatio, "ratio")); e.AddDetail(new Explanation((float)queryPower, "power")); exp.AddDetail(e = new Explanation((float)targetFactor, "Target")); e.AddDetail(new Explanation((float)targetArea, "area")); e.AddDetail(new Explanation((float)targetRatio, "ratio")); e.AddDetail(new Explanation((float)targetPower, "power")); } } else if (exp != null) { exp.Value = 0; exp.Description = "Shape does not intersect"; } return score; } public override bool Equals(object obj) { var other = obj as AreaSimilarity; if (other == null) return false; return GetDelimiterQueryParameters().Equals(other.GetDelimiterQueryParameters()); } public override int GetHashCode() { return GetDelimiterQueryParameters().GetHashCode(); } } }
// Copyright (c) Rotorz Limited. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root. using Rotorz.Games.UnityEditorExtensions; using System; using UnityEditor; using UnityEngine; namespace Rotorz.Tile.Editor { /// <summary> /// Brush palette allows user to select the brushes that they would like to use when /// interacting with tile systems. /// </summary> internal sealed class BrushPaletteWindow : RotorzWindow { [NonSerialized] private BrushListControl brushList; /// <inheritdoc/> protected override void DoEnable() { this.wantsMouseMove = true; this.titleContent = new GUIContent(TileLang.Text("Brushes")); this.minSize = new Vector2(255, 200); // Set up brush list. this.brushList = new BrushListControl(this); this.brushList.Model = ToolUtility.SharedBrushListModel; this.brushList.CanShowHidden = true; this.brushList.EnableDragAndDrop = true; this.brushList.DragThreshold = 16; this.brushList.EmptyLabel = TileLang.ParticularText("Action", "(Erase)"); this.brushList.VisibleViews = BrushListView.Brushes | BrushListView.Tileset; this.brushList.ShowTilesetContextMenu = true; this.brushList.BrushMouseDown += this._brushList_BrushMouseDown; this.brushList.BrushClicked += this._brushList_BrushClicked; this.brushList.BrushContextMenu += this._brushList_BrushContextMenu; this.brushList.Model.ViewChanged += this.Model_ViewChanged; this.brushList.Model.SelectedBrushChanged += this.Model_SelectedBrushChanged; this.brushList.Model.SelectedTilesetChanged += this.Model_SelectedTilesetChanged; } /// <inheritdoc/> protected override void DoDestroy() { // Remove event handlers to avoid memory leak. this.brushList.Model.ViewChanged -= this.Model_ViewChanged; this.brushList.Model.SelectedBrushChanged -= this.Model_SelectedBrushChanged; this.brushList.Model.SelectedTilesetChanged -= this.Model_SelectedTilesetChanged; this.brushList.BrushMouseDown -= this._brushList_BrushMouseDown; this.brushList.BrushClicked -= this._brushList_BrushClicked; this.brushList.BrushContextMenu -= this._brushList_BrushContextMenu; } /// <inheritdoc/> protected override void DoGUI() { this.DrawBrushesGUI(); RotorzEditorGUI.DrawHoverTip(this); } private void Model_ViewChanged(BrushListView previous, BrushListView current) { this.Repaint(); } private void Model_SelectedBrushChanged(Brush previous, Brush current) { this.Repaint(); } private void Model_SelectedTilesetChanged(Tileset previous, Tileset current) { this.Repaint(); } private void _brushList_BrushMouseDown(Brush brush) { // Double-click to ensure that designer window is shown. if (Event.current.clickCount == 2 && brush != null) { ToolUtility.ShowBrushInDesigner(brush); GUIUtility.hotControl = 0; GUIUtility.ExitGUI(); return; } // If right mouse button was depressed, without holding control key, select // as primary brush ready for context menu. if (Event.current.button == 1 && !Event.current.control) { ToolUtility.SelectedBrush = brush; } } private void _brushList_BrushClicked(Brush brush) { // Only proceed if either the left mouse button or right mouse button was used. if (Event.current.button != 0 && Event.current.button != 1) { return; } Brush previousSelectedBrush = null; // Left click to select brush, or holding control to select secondary brush. if (Event.current.button == 0) { previousSelectedBrush = ToolUtility.SelectedBrush; if (brush != previousSelectedBrush) { ToolUtility.SelectedBrush = brush; this.brushList.ScrollToBrush(brush); } else { // Brush is already selected, open in designer? var designerWindow = RotorzWindow.GetInstance<DesignerWindow>(); if (designerWindow != null && !designerWindow.IsLocked) { designerWindow.SelectedObject = brush; } } Event.current.Use(); } else if (Event.current.control) { previousSelectedBrush = ToolUtility.SelectedBrushSecondary; ToolUtility.SelectedBrushSecondary = brush; Event.current.Use(); } // If control was held, toggle paint tool. if (Event.current.control) { if (ToolManager.Instance.CurrentTool == null) { ToolManager.Instance.CurrentTool = ToolManager.DefaultPaintTool; } else if (Event.current.button == 0 && previousSelectedBrush == brush) { // Deselect paint tool if control was held whilst clicking selected brush. ToolManager.Instance.CurrentTool = null; } } // If painting tool is active then repaint active scene view so that gizmos, // handles and other annotations are properly updated. if (ToolManager.Instance.CurrentTool != null && SceneView.lastActiveSceneView != null) { SceneView.lastActiveSceneView.Repaint(); } } private void _brushList_BrushContextMenu(Brush brush) { // Do not attempt to display context menu for "(Erase)" item. if (brush == null) { return; } var brushRecord = BrushDatabase.Instance.FindRecord(brush); var brushContextMenu = new EditorMenu(); brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Show in Designer"))) .Enabled(!brushRecord.IsMaster) // Cannot edit a master brush :) .Action(() => { ToolUtility.ShowBrushInDesigner(brush); }); var selectedTilesetBrush = brush as TilesetBrush; if (selectedTilesetBrush != null) { brushContextMenu.AddCommand(TileLang.ParticularText("Action", "Goto Tileset")) .Action(() => { this.brushList.Model.View = BrushListView.Tileset; this.brushList.Model.SelectedTileset = selectedTilesetBrush.Tileset; var designerWindow = RotorzWindow.GetInstance<DesignerWindow>(); if (designerWindow != null && !designerWindow.IsLocked) { designerWindow.SelectedObject = selectedTilesetBrush.Tileset; } this.Repaint(); }); } brushContextMenu.AddCommand(TileLang.ParticularText("Action", "Reveal Asset")) .Action(() => { EditorGUIUtility.PingObject(brush); }); brushContextMenu.AddSeparator(); brushContextMenu.AddCommand(TileLang.ParticularText("Action", "Refresh Preview")) .Action(() => { BrushUtility.RefreshPreviewIncludingDependencies(brush); }); brushContextMenu.AddSeparator(); brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Create Duplicate"))) .Action(() => { var window = CreateBrushWindow.ShowWindow<DuplicateBrushCreator>(); window.SharedProperties["targetBrush"] = brush; }); var brushDescriptor = BrushUtility.GetDescriptor(brush.GetType()); brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Create Alias"))) .Enabled(brushDescriptor.SupportsAliases) .Action(() => { var window = CreateBrushWindow.ShowWindow<AliasBrushCreator>(); window.SharedProperties["targetBrush"] = brush; }); brushContextMenu.AddCommand(TileLang.OpensWindow(TileLang.ParticularText("Action", "Delete Brush"))) .Action(() => { TileSystemCommands.DeleteBrush(brush, ToolUtility.SharedBrushListModel.View == BrushListView.Tileset); }); brushContextMenu.ShowAsContext(); } internal void DrawBrushesGUI() { this.DrawToolbar(); if (GUIUtility.keyboardControl == 0) { ToolManager.Instance.CheckForKeyboardShortcut(); ToolUtility.CheckToolKeyboardShortcuts(); } GUILayout.Space(-1); // Is selected brush (primary or secondary) about to be changed? this.brushList.Draw(false); this.DrawPrimarySecondaryBrushSwitcher(); GUILayout.Space(5); } private void DrawToolbar() { GUILayout.BeginHorizontal(EditorStyles.toolbar); if (GUILayout.Button(TileLang.OpensWindow(TileLang.ParticularText("Action", "Create")), EditorStyles.toolbarButton, RotorzEditorStyles.ContractWidth)) { CreateBrushWindow.ShowWindow().Focus(); GUIUtility.ExitGUI(); } GUILayout.Space(5); this.brushList.DrawToolbarButtons(); GUILayout.EndHorizontal(); } private void DrawPrimarySecondaryBrushSwitcher() { Rect r; GUILayout.Space(5); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); GUILayout.Label(RotorzEditorStyles.Skin.MouseLeft); GUILayout.Box(GUIContent.none, RotorzEditorStyles.Instance.SelectedBrushPreviewBox); r = GUILayoutUtility.GetLastRect(); if (ToolUtility.SelectedBrush != null) { RotorzEditorGUI.DrawBrushPreview(new Rect(r.x + 2, r.y + 2, r.width - 4, r.height - 4), ToolUtility.SelectedBrush); } else { GUI.Label(r, TileLang.ParticularText("Action", "Erase"), RotorzEditorStyles.Instance.MiniCenteredLabel); } GUILayout.Space(10); GUILayout.Label(RotorzEditorStyles.Skin.MouseRight); GUILayout.Box(GUIContent.none, RotorzEditorStyles.Instance.SelectedBrushPreviewBox); r = GUILayoutUtility.GetLastRect(); if (ToolUtility.SelectedBrushSecondary != null) { RotorzEditorGUI.DrawBrushPreview(new Rect(r.x + 2, r.y + 2, r.width - 4, r.height - 4), ToolUtility.SelectedBrushSecondary); } else { GUI.Label(r, TileLang.ParticularText("Action", "Erase"), RotorzEditorStyles.Instance.MiniCenteredLabel); } GUILayout.Space(5); using (var content = ControlContent.Basic( RotorzEditorStyles.Skin.SwitchPrimarySecondary, TileLang.ParticularText("Action", "Switch primary and secondary brushes (X)") )) { if (RotorzEditorGUI.HoverButton(content, GUILayout.Height(42))) { Brush t = ToolUtility.SelectedBrush; ToolUtility.SelectedBrush = ToolUtility.SelectedBrushSecondary; ToolUtility.SelectedBrushSecondary = t; GUIUtility.ExitGUI(); } } GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.Space(5); } internal void RevealBrush(Brush brush) { this.brushList.RevealBrush(brush); } } }